Procházet zdrojové kódy

Feature #306 - Line endigs cohrrence, Part 3: Converting \r\n line endings (Windows style) to \n (Unix style) in php, html, js, xml, txt files.

Ivan Tcholakov před 15 roky
rodič
revize
de0ec5ca3d
100 změnil soubory, kde provedl 32337 přidání a 32337 odebrání
  1. 7 7
      main/WCAG/index.html
  2. 816 816
      main/install/index.php
  3. 1210 1210
      main/install/install_functions.inc.php
  4. 74 74
      main/install/update-files-1.8.6-1.8.6.1.inc.php
  5. 925 925
      main/install/upgrade.php
  6. 388 388
      main/messages/message.class.php
  7. 19 19
      main/messages/plugin.php
  8. 108 108
      main/messaging/email_editor.php
  9. 194 194
      main/metadata/phpdig/en-language.php
  10. 323 323
      main/mySpace/access_details.php
  11. 3 3
      main/mySpace/coaches.php
  12. 172 172
      main/mySpace/course.php
  13. 1208 1208
      main/mySpace/index.php
  14. 1202 1202
      main/mySpace/myStudents.php
  15. 43 43
      main/mySpace/myspace.lib.php
  16. 81 81
      main/mySpace/progression.php
  17. 121 121
      main/mySpace/reussite.php
  18. 178 178
      main/mySpace/session.php
  19. 282 282
      main/mySpace/student.php
  20. 136 136
      main/mySpace/teachers.php
  21. 15 15
      main/newscorm/README.txt
  22. 951 951
      main/newscorm/aicc.class.php
  23. 54 54
      main/newscorm/aiccBlock.class.php
  24. 134 134
      main/newscorm/aiccItem.class.php
  25. 54 54
      main/newscorm/aiccObjective.class.php
  26. 51 51
      main/newscorm/aiccResource.class.php
  27. 716 716
      main/newscorm/aicc_api.php
  28. 230 230
      main/newscorm/aicc_hacp.php
  29. 14 14
      main/newscorm/back_compat.inc.php
  30. 43 43
      main/newscorm/blank.php
  31. 51 51
      main/newscorm/content_makers.inc.php
  32. 39 39
      main/newscorm/display_audiorecorder.php
  33. 470 470
      main/newscorm/document.php
  34. 16 16
      main/newscorm/index.php
  35. 2338 2338
      main/newscorm/learnpathItem.class.php
  36. 101 101
      main/newscorm/learnpathList.class.php
  37. 2675 2675
      main/newscorm/learnpath_functions.inc.php
  38. 158 158
      main/newscorm/lp_add.php
  39. 263 263
      main/newscorm/lp_admin_view.php
  40. 22 22
      main/newscorm/lp_api.php
  41. 214 214
      main/newscorm/lp_build.php
  42. 24 24
      main/newscorm/lp_comm.common.php
  43. 441 441
      main/newscorm/lp_comm.server.php
  44. 85 85
      main/newscorm/lp_content.php
  45. 724 724
      main/newscorm/lp_controller.php
  46. 159 159
      main/newscorm/lp_edit.php
  47. 203 203
      main/newscorm/lp_edit_item.php
  48. 177 177
      main/newscorm/lp_edit_item_prereq.php
  49. 17 17
      main/newscorm/lp_export.php
  50. 14 14
      main/newscorm/lp_footer.php
  51. 80 80
      main/newscorm/lp_header.php
  52. 43 43
      main/newscorm/lp_log.php
  53. 53 53
      main/newscorm/lp_message.php
  54. 182 182
      main/newscorm/lp_move_item.php
  55. 48 48
      main/newscorm/lp_nav.php
  56. 32 32
      main/newscorm/lp_save.php
  57. 671 671
      main/newscorm/lp_stats.php
  58. 48 48
      main/newscorm/lp_toc.php
  59. 155 155
      main/newscorm/lp_upload.php
  60. 60 60
      main/newscorm/lp_view.lib.js
  61. 554 554
      main/newscorm/lp_view.php
  62. 175 175
      main/newscorm/lp_view_item.php
  63. 128 128
      main/newscorm/openoffice_document.class.php
  64. 210 210
      main/newscorm/openoffice_presentation.class.php
  65. 308 308
      main/newscorm/openoffice_text.class.php
  66. 311 311
      main/newscorm/openoffice_text_document.class.php
  67. 1117 1117
      main/newscorm/resourcelinker.php
  68. 977 977
      main/newscorm/scorm.class.php
  69. 191 191
      main/newscorm/scorm.lib.php
  70. 302 302
      main/newscorm/scormItem.class.php
  71. 200 200
      main/newscorm/scormMetadata.class.php
  72. 206 206
      main/newscorm/scormResource.class.php
  73. 414 414
      main/newscorm/scorm_admin.php
  74. 1448 1448
      main/newscorm/scorm_api.php
  75. 9 9
      main/newscorm/scorm_manage.php
  76. 305 305
      main/notebook/index.php
  77. 161 161
      main/permissions/blog_permissions.inc.php
  78. 647 647
      main/permissions/permissions_functions.inc.php
  79. 248 248
      main/permissions/roles.php
  80. 85 85
      main/plugin/hotspot/jsmethods.js
  81. 6 6
      main/reservation/index.html
  82. 146 146
      main/reservation/m_category.php
  83. 474 474
      main/reservation/m_item.php
  84. 433 433
      main/reservation/m_item_origineel.php
  85. 538 538
      main/reservation/m_reservation.php
  86. 103 103
      main/reservation/mysubscriptions.php
  87. 439 439
      main/reservation/rcalendar.php
  88. 134 134
      main/reservation/reservation.php
  89. 1081 1081
      main/reservation/rsys.php
  90. 173 173
      main/reservation/subscribe.php
  91. 67 67
      main/social/contacts.inc.php
  92. 85 85
      main/social/group_contact.inc.php
  93. 451 451
      main/social/index.php
  94. 25 25
      main/social/select_options.php
  95. 77 77
      main/social/show_search_image.inc.php
  96. 318 318
      main/survey/create_new_survey.php
  97. 173 173
      main/survey/question.php
  98. 189 189
      main/survey/survey_invitation.php
  99. 1 1
      main/survey/survey_invite.php
  100. 113 113
      main/template/exampletables.php

+ 7 - 7
main/WCAG/index.html

@@ -1,7 +1,7 @@
-<html>
-<head>
-<meta http-equiv="refresh" content="0; url=../gradebook.php">
-</head>
-<body>
-</body>
-</html>
+<html>
+<head>
+<meta http-equiv="refresh" content="0; url=../gradebook.php">
+</head>
+<body>
+</body>
+</html>

+ 816 - 816
main/install/index.php

@@ -1,820 +1,820 @@
-<?php //$id: $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-* GOAL : Dokeos installation
-* As seen from the user, the installation proceeds in 6 steps.
-* The user is presented with several webpages where he/she has to make choices
-* and/or fill in data.
-*
-* The aim is, as always, to have good default settings and suggestions.
-*
-* @todo	reduce high level of duplication in this code
-* @todo (busy) organise code into functions
-* @package dokeos.install
-==============================================================================
-*/
-
-/*
-==============================================================================
-		PHP VERSION CHECK & MBSTRING EXTENSION CHECK
-==============================================================================
-*/
-
-if ( !function_exists('version_compare') || version_compare( phpversion(), '5', '<' )) {
-	$error_message_php_version = <<<EOM
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html>
-		<head>
-			<title>Wrong PHP version!</title>
-			<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-			<style type="text/css" media="screen, projection">
-				/*<![CDATA[*/
-				@import "../css/dokeos_blue/default.css";
-				/*]]>*/
-			</style>
-		</head>
-		<body>
-			<div id="wrapper">
-				<div id="header">
-					<div id="header1"><a href="http://www.dokeos.com" target="_blank">Dokeos Homepage</a></div>
-					<div class="clear"></div>
-					<div id="header2">&nbsp;</div>
-					<div id="header3">
-						<ul id="logout">
-							<li><a href="" target="_top"><span>&nbsp;</span></a></li>
-						</ul>
-						<ul>
-							<li id="current"><a href="#"><span>Installation</span></a></li>
-						</ul>
-						<div style="clear:both;" class="clear"></div>
-					</div>
-					<div id="header4">&nbsp;</div>
-				</div>
-
-				<div style="text-align: center;"><br /><br />
-						The version of scripting language on your server is wrong. Your server has to support PHP 5.x.x .<br />
-						<a href="../../documentation/installation_guide.html" target="_blank">Read the installation guide</a><br /><br />
-				</div>
-				<div id="push"></div>
-				</div>
-
-			<div id="footer">
-				<div class="copyright">Platform <a href="http://www.dokeos.com" target="_blank"> Dokeos </a> &copy; 2009 </div>
-				&nbsp;
-			</div>
-
-		</body>
-</html>
-EOM;
-	header('Content-Type: text/html; charset=UTF-8');
-	die($error_message_php_version);
-}
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-session_start();
-// Including necessary files
-@include '../inc/installedVersion.inc.php';
-require '../inc/lib/main_api.lib.php';
-
-require '../lang/english/trad4all.inc.php';
-require '../lang/english/install.inc.php';
-
-if (!empty($_POST['language_list'])) {
-	$search = array('../','\\0');
-	$install_language = str_replace($search,'',urldecode($_POST['language_list']));
-	if(!is_dir('../lang/'.$install_language)){$install_language = 'english';}
-	include_once "../lang/$install_language/trad4all.inc.php";
-	include_once "../lang/$install_language/install.inc.php";
-	api_session_register('install_language');
-} elseif ( isset($_SESSION['install_language']) && $_SESSION['install_language'] ) {
-	$install_language = $_SESSION['install_language'];
-	include_once "../lang/$install_language/trad4all.inc.php";
-	include_once "../lang/$install_language/install.inc.php";
-}
-
-// These global variables must be set for proper working of the function get_lang(...) during the installation.
-$language_interface = $install_language;
-$language_interface_initial_value = $install_language;
-
-/* TODO: Obsolete logic, to be removed.
-$charset = '';
-//force ISO-8859-15 for European languages. Leave Apache determine the encoding for others (HTML declaring UTF-8)
-$euro_langs = array('english','french','french_KM','french_corporate','french_org','dutch','spanish','german','italian','greek','danish','swedish','norwegian','polish','galician','catalan','czech','finnish');
-if (isset($install_language))
-{
-	if(in_array($install_language,$euro_langs))
-	{
-		$charset = 'ISO-8859-15'; // TODO: This should be UTF-8 for some languages.
-		header('Content-Type: text/html; charset='. $charset);
-	}
-}
-*/
-
-// Character set during installation: ISO-8859-15 for Latin 1 languages, UTF-8 for other languages.
-$charset = 'UTF-8';
-if (isset($install_language)) {
-	if (strpos($install_language, 'unicode') === false && api_is_latin1_compatible($install_language))
-	{
-		// TODO: This is for backward compatibility. Actually, all the languages may use UTF-8.
-		$charset = 'ISO-8859-15';
-	}
-}
-header('Content-Type: text/html; charset='. $charset);
-
+<?php //$id: $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+* GOAL : Dokeos installation
+* As seen from the user, the installation proceeds in 6 steps.
+* The user is presented with several webpages where he/she has to make choices
+* and/or fill in data.
+*
+* The aim is, as always, to have good default settings and suggestions.
+*
+* @todo	reduce high level of duplication in this code
+* @todo (busy) organise code into functions
+* @package dokeos.install
+==============================================================================
+*/
+
+/*
+==============================================================================
+		PHP VERSION CHECK & MBSTRING EXTENSION CHECK
+==============================================================================
+*/
+
+if ( !function_exists('version_compare') || version_compare( phpversion(), '5', '<' )) {
+	$error_message_php_version = <<<EOM
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+		<head>
+			<title>Wrong PHP version!</title>
+			<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+			<style type="text/css" media="screen, projection">
+				/*<![CDATA[*/
+				@import "../css/dokeos_blue/default.css";
+				/*]]>*/
+			</style>
+		</head>
+		<body>
+			<div id="wrapper">
+				<div id="header">
+					<div id="header1"><a href="http://www.dokeos.com" target="_blank">Dokeos Homepage</a></div>
+					<div class="clear"></div>
+					<div id="header2">&nbsp;</div>
+					<div id="header3">
+						<ul id="logout">
+							<li><a href="" target="_top"><span>&nbsp;</span></a></li>
+						</ul>
+						<ul>
+							<li id="current"><a href="#"><span>Installation</span></a></li>
+						</ul>
+						<div style="clear:both;" class="clear"></div>
+					</div>
+					<div id="header4">&nbsp;</div>
+				</div>
+
+				<div style="text-align: center;"><br /><br />
+						The version of scripting language on your server is wrong. Your server has to support PHP 5.x.x .<br />
+						<a href="../../documentation/installation_guide.html" target="_blank">Read the installation guide</a><br /><br />
+				</div>
+				<div id="push"></div>
+				</div>
+
+			<div id="footer">
+				<div class="copyright">Platform <a href="http://www.dokeos.com" target="_blank"> Dokeos </a> &copy; 2009 </div>
+				&nbsp;
+			</div>
+
+		</body>
+</html>
+EOM;
+	header('Content-Type: text/html; charset=UTF-8');
+	die($error_message_php_version);
+}
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+session_start();
+// Including necessary files
+@include '../inc/installedVersion.inc.php';
+require '../inc/lib/main_api.lib.php';
+
+require '../lang/english/trad4all.inc.php';
+require '../lang/english/install.inc.php';
+
+if (!empty($_POST['language_list'])) {
+	$search = array('../','\\0');
+	$install_language = str_replace($search,'',urldecode($_POST['language_list']));
+	if(!is_dir('../lang/'.$install_language)){$install_language = 'english';}
+	include_once "../lang/$install_language/trad4all.inc.php";
+	include_once "../lang/$install_language/install.inc.php";
+	api_session_register('install_language');
+} elseif ( isset($_SESSION['install_language']) && $_SESSION['install_language'] ) {
+	$install_language = $_SESSION['install_language'];
+	include_once "../lang/$install_language/trad4all.inc.php";
+	include_once "../lang/$install_language/install.inc.php";
+}
+
+// These global variables must be set for proper working of the function get_lang(...) during the installation.
+$language_interface = $install_language;
+$language_interface_initial_value = $install_language;
+
+/* TODO: Obsolete logic, to be removed.
+$charset = '';
+//force ISO-8859-15 for European languages. Leave Apache determine the encoding for others (HTML declaring UTF-8)
+$euro_langs = array('english','french','french_KM','french_corporate','french_org','dutch','spanish','german','italian','greek','danish','swedish','norwegian','polish','galician','catalan','czech','finnish');
+if (isset($install_language))
+{
+	if(in_array($install_language,$euro_langs))
+	{
+		$charset = 'ISO-8859-15'; // TODO: This should be UTF-8 for some languages.
+		header('Content-Type: text/html; charset='. $charset);
+	}
+}
+*/
+
+// Character set during installation: ISO-8859-15 for Latin 1 languages, UTF-8 for other languages.
+$charset = 'UTF-8';
+if (isset($install_language)) {
+	if (strpos($install_language, 'unicode') === false && api_is_latin1_compatible($install_language))
+	{
+		// TODO: This is for backward compatibility. Actually, all the languages may use UTF-8.
+		$charset = 'ISO-8859-15';
+	}
+}
+header('Content-Type: text/html; charset='. $charset);
+
 // Initialization of the internationalization library.
 api_initialize_internationalization();
 // Initialization of the default encoding that will be used by the multibyte string routines in the internationalization library.
 api_set_internationalization_default_encoding($charset);
-
-require_once 'install_upgrade.lib.php'; //also defines constants
-require_once 'install_functions.inc.php';
-
-// Some constants
-define('DOKEOS_INSTALL',1);
-define('MAX_COURSE_TRANSFER',100);
-define('INSTALL_TYPE_UPDATE', 'update');
-define('FORM_FIELD_DISPLAY_LENGTH', 40);
-define('DATABASE_FORM_FIELD_DISPLAY_LENGTH', 25);
-define('MAX_FORM_FIELD_LENGTH', 80);
-define('DEFAULT_LANGUAGE', 'english');
-
-// setting the error reporting
-error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
-
-// overriding the timelimit (for large campusses that have to be migrated)
-@set_time_limit(0);
-
-//upgrading from any subversion of 1.6 is just like upgrading from 1.6.5
-$update_from_version_6=array('1.6','1.6.1','1.6.2','1.6.3','1.6.4','1.6.5');
-//upgrading from any subversion of 1.8 avoids the additional step of upgrading from 1.6
-$update_from_version_8=array('1.8','1.8.2','1.8.3','1.8.4','1.8.5','1.8.6');
-$my_old_version = '';
-$tmp_version = get_config_param('dokeos_version');
-if(!empty($_POST['old_version'])) {
-	$my_old_version = $_POST['old_version'];
-} elseif(!empty($tmp_version)) {
-    $my_old_version = $tmp_version;
-}
-elseif(!empty($dokeos_version)) //variable coming from installedVersion, normally
-{
-	$my_old_version = $dokeos_version;
-}
-
-$new_version = '1.8.6.1';
-$new_version_stable = true;
-$new_version_major = false;
-/*
-==============================================================================
-		STEP 1 : INITIALIZES FORM VARIABLES IF IT IS THE FIRST VISIT
-==============================================================================
-*/
-
-//Is valid request
-$is_valid_request=$_REQUEST['is_executable'];
-foreach ($_POST as $request_index=>$request_value) {
-	if (substr($request_index,0,4)=='step') {
-		if ($request_index<>$is_valid_request) {
-			unset($_POST[$request_index]);
-		}
-	}
-}
-
-$badUpdatePath=false;
-$emptyUpdatePath=true;
-$proposedUpdatePath = '';
-if(!empty($_POST['updatePath']))
-{
-	$proposedUpdatePath = $_POST['updatePath'];
-}
-
-if ($_POST['step2_install'] || $_POST['step2_update_8'] || $_POST['step2_update_6']) {
-	if ($_POST['step2_install']) {
-		$installType='new';
-
-		$_POST['step2']=1;
-	} else {
-		$installType='update';
-		if($_POST['step2_update_8'])
-		{
-			$emptyUpdatePath = false;
-			if(empty($_POST['updatePath']))
-			{
-				$proposedUpdatePath = $_SERVER['DOCUMENT_ROOT'];
-			}
-			else
-			{
-				$proposedUpdatePath = $_POST['updatePath'];
-			}
-			if(substr($proposedUpdatePath,-1) != '/')
-			{
-				$proposedUpdatePath.='/';
-			}
-			if(file_exists($proposedUpdatePath))
-			{
-				if(in_array($my_old_version,$update_from_version_8))
-				{
-					$_POST['step2']=1;
-				}
-				else
-				{
-					$badUpdatePath=true;
-				}
-			}
-			else
-			{
-				$badUpdatePath=true;
-			}
-		}
-		else //step2_update_6, presumably
-		{
-			if(empty($_POST['updatePath']))
-			{
-				$_POST['step1']=1;
-			}
-			else
-			{
-				$emptyUpdatePath = false;
-				if(substr($_POST['updatePath'],-1) != '/')
-				{
-					$_POST['updatePath'].='/';
-				}
-
-				if(file_exists($_POST['updatePath']))
-				{
-					//1.6.x
-					$my_old_version = get_config_param('clarolineVersion',$_POST['updatePath']);
-					if(in_array($my_old_version,$update_from_version_6))
-					{
-						$_POST['step2']=1;
-						$proposedUpdatePath = $_POST['updatePath'];
-					}
-					else
-					{
-						$badUpdatePath=true;
-					}
-				}
-				else
-				{
-					$badUpdatePath=true;
-				}
-			}
-		}
-	}
-}
-elseif($_POST['step1'])
-{
-	$_POST['updatePath']='';
-	$installType='';
-	$updateFromConfigFile='';
-	unset($_GET['running']);
-}
-else
-{
-	$installType=$_GET['installType'];
-	$updateFromConfigFile=$_GET['updateFromConfigFile'];
-}
-
-if($installType=='update' && in_array($my_old_version,$update_from_version_8))
-{
-	include_once '../inc/conf/configuration.php';
-}
-
-if(!isset($_GET['running'])) {
-	$dbHostForm='localhost';
-	$dbUsernameForm='root';
-	$dbPassForm='';
- 	$dbPrefixForm='';
-	$dbNameForm='dokeos_main';
-	$dbStatsForm='dokeos_stats';
-	$dbScormForm='dokeos_scorm';
-	$dbUserForm='dokeos_user';
-
-	// extract the path to append to the url if Dokeos is not installed on the web root directory
-	$urlAppendPath=str_replace('/main/install/index.php','',api_get_self());
-  	$urlForm='http://'.$_SERVER['HTTP_HOST'].$urlAppendPath.'/';
-	$pathForm=str_replace('\\','/',realpath('../..')).'/';
-
-	$emailForm=$_SERVER['SERVER_ADMIN'];
-	$email_parts = explode('@',$emailForm);
-	if($email_parts[1] == 'localhost')
-	{
-		$emailForm .= '.localdomain';
-	}
-	$adminLastName='Doe';
-	$adminFirstName='John';
-	$loginForm='admin';
-	$passForm=api_generate_password();
-
-	$campusForm='My campus';
-	$educationForm='Albert Einstein';
-	$adminPhoneForm='(000) 001 02 03';
-	$institutionForm='My Organisation';
-	$institutionUrlForm='http://www.dokeos.com';
-
-	$languageForm='english';
-
-	$checkEmailByHashSent=0;
-	$ShowEmailnotcheckedToStudent=1;
-	$userMailCanBeEmpty=1;
-	$allowSelfReg=1;
-	$allowSelfRegProf=1;
-	$enableTrackingForm=1;
-	$singleDbForm=0;
-	$encryptPassForm='md5';
-	$session_lifetime=360000;
-}
-else
-{
-	foreach($_POST as $key=>$val)
-	{
-		$magic_quotes_gpc=ini_get('magic_quotes_gpc')?true:false;
-
-		if(is_string($val))
-		{
-			if($magic_quotes_gpc)
-			{
-				$val=stripslashes($val);
-			}
-
-			$val=trim($val);
-
-			$_POST[$key]=$val;
-		}
-		elseif(is_array($val))
-		{
-			foreach($val as $key2=>$val2)
-			{
-				if($magic_quotes_gpc)
-				{
-					$val2=stripslashes($val2);
-				}
-
-				$val2=trim($val2);
-
-				$_POST[$key][$key2]=$val2;
-			}
-		}
-
-		$GLOBALS[$key]=$_POST[$key];
-	}
-}
-
-// The Steps
-$total_steps=7;
-if (!$_POST)
-{
-	$current_step=1;
-}
-elseif (!empty($_POST['language_list']) or !empty($_POST['step1']) or ((!empty($_POST['step2_update_8']) or (!empty($_POST['step2_update_6'])))  && ($emptyUpdatePath or $badUpdatePath)))
-{
-	$current_step=2;
-}
-elseif (!empty($_POST['step2']) or (!empty($_POST['step2_update_8']) or (!empty($_POST['step2_update_6'])) ))
-{
-	$current_step=3;
-}
-elseif (!empty($_POST['step3']))
-{
-	$current_step=4;
-}
-elseif (!empty($_POST['step4']))
-{
-	$current_step=5;
-}
-elseif (!empty($_POST['step5']))
-{
-	$current_step=6;
-}
-
-
-// Managing the $encryptPassForm
-if ($encryptPassForm=='1' ) {
-	$encryptPassForm = 'md5';
-} elseif ($encryptPassForm=='0') {
-	$encryptPassForm = 'none';
-}
-
-?>
-<!DOCTYPE html
-     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-	<title>&mdash; <?php echo get_lang('DokeosInstallation').' &mdash; '.get_lang('Version_').' '.$new_version; ?></title>
-	<style type="text/css" media="screen, projection">
-		/*<![CDATA[*/
-		@import "../css/dokeos_blue/default.css";
-		/*]]>*/
-	</style>
-	<script type="text/javascript" src="../inc/lib/javascript/jquery.js"></script>
-	<script type="text/javascript" >
-		$(document).ready( function() {
-			 //checked
-			if ($('#singleDb1').attr('checked')==false) {
-					$('#dbStatsForm').removeAttr('disabled');
-					$('#dbUserForm').removeAttr('disabled');
-					$('#dbStatsForm').attr('value','dokeos_stats');
-					$('#dbUserForm').attr('value','dokeos_user');
-			} else if($('#singleDb1').attr('checked')==true){
-					$('#dbStatsForm').attr('disabled','disabled');
-					$('#dbUserForm').attr('disabled','disabled');
-					$('#dbStatsForm').attr('value','dokeos_main');
-					$('#dbUserForm').attr('value','dokeos_main');
-			}
-		//Allow dokeos install in IE
-		$("button").click(function() {
-			$("#is_executable").attr("value",$(this).attr("name"));
-		});
-
-	 	} );
-	</script>
-	<script type="text/javascript">
-
-		function show_hide_tracking_and_user_db (my_option) {
-			if (my_option=='singleDb1') {
-				$('#dbStatsForm').attr('disabled','true');
-				$('#dbUserForm').attr('disabled','true');
-				$('#dbStatsForm').attr('value','dokeos_main');
-				$('#dbUserForm').attr('value','dokeos_main');
-			} else if (my_option=='singleDb0') {
-				$('#dbStatsForm').removeAttr('disabled');
-				$('#dbUserForm').removeAttr('disabled');
-				$('#dbStatsForm').attr('value','dokeos_stats');
-				$('#dbUserForm').attr('value','dokeos_user');
-			}
-		}
-	</script>
-	<script language="javascript">
-		init_visibility=0;
-		function show_hide_option() {
-			if(init_visibility == 0) {
-				document.getElementById('optional_param1').style.display = '';
-				document.getElementById('optional_param2').style.display = '';
-				if(document.getElementById('optional_param3'))
-				{
-					document.getElementById('optional_param3').style.display = '';
-				}
-				document.getElementById('optional_param4').style.display = '';
-				document.getElementById('optional_param5').style.display = '';
-				document.getElementById('optional_param6').style.display = '';
-				init_visibility = 1;
-			document.getElementById('optionalparameters').innerHTML='<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" /> <?php echo get_lang('OptionalParameters'); ?>';
-			} else {
-				document.getElementById('optional_param1').style.display = 'none';
-				document.getElementById('optional_param2').style.display = 'none';
-				if(document.getElementById('optional_param3')) {
-					document.getElementById('optional_param3').style.display = 'none';
-				}
-				document.getElementById('optional_param4').style.display = 'none';
-				document.getElementById('optional_param5').style.display = 'none';
-				document.getElementById('optional_param6').style.display = 'none';
-			document.getElementById('optionalparameters').innerHTML='<img style="vertical-align:middle;" src="../img/div_show.gif" alt="" /> <?php echo get_lang('OptionalParameters'); ?>';
-				init_visibility = 0;
-			}
-		}
-	</script>
-<?php if(!empty($charset)){ ?>
-	<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset ?>" />
-<?php } ?>
-</head>
-<body dir="<?php echo $text_dir ?>">
-
-<div id="wrapper">
-
-<div id="header">
-	<div id="header1"><?php echo get_lang('DokeosInstallation').' &mdash; '.get_lang('Version_').' '.$new_version; ?><?php if($installType == 'new') echo ' &ndash; '.get_lang('NewInstallation'); else if($installType == 'update') echo ' &ndash; '.get_lang('UpdateFromDokeosVersion').(is_array($update_from_version)?implode('|',$update_from_version):''); ?></div>
-	<div id="header2">&nbsp;</div>
-	<div id="header3">
-		<ul>
-			<li id="current"><a href="#"><span>Installation</span></a></li>
-		</ul>
-	</div>
-</div>
-
-
-<form style="padding: 0px; margin: 0px;" method="post" action="<?php echo api_get_self(); ?>?running=1&amp;installType=<?php echo $installType; ?>&amp;updateFromConfigFile=<?php echo urlencode($updateFromConfigFile); ?>">
-
-<div id="installation_steps" style="width:240px">
-	<img src="../img/bluelogo.gif" hspace="10" vspace="10" alt="Dokeos logo" />
-	<ol>
-		<li <?php step_active('1'); ?>><?php echo get_lang('InstallationLanguage'); ?></li>
-		<li <?php step_active('2'); ?>><?php echo get_lang('Requirements'); ?></li>
-		<li <?php step_active('3'); ?>><?php echo get_lang('Licence'); ?></li>
-		<li <?php step_active('4'); ?>><?php echo get_lang('DBSetting'); ?></li>
-		<li <?php step_active('5'); ?>><?php echo get_lang('CfgSetting'); ?></li>
-		<li <?php step_active('6'); ?>><?php echo get_lang('PrintOverview'); ?></li>
-		<li <?php step_active('7'); ?>><?php echo get_lang('Installing'); ?></li>
-	</ol>
-</div>
-
-<table cellpadding="6" cellspacing="0" border="0" width="72%" align="center">
-<tr>
-<td>
-	<div id="note" style="float:right;">
-		<a href="../../documentation/installation_guide.html" target="_blank">Read the installation guide</a>
-	</div>
-</td>
-</tr>
-<tr>
-  <td>
-	<input type="hidden" name="updatePath"           value="<?php if(!$badUpdatePath) echo api_htmlentities($proposedUpdatePath, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="urlAppendPath"        value="<?php echo api_htmlentities($urlAppendPath, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="pathForm"             value="<?php echo api_htmlentities($pathForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="urlForm"              value="<?php echo api_htmlentities($urlForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="dbHostForm"           value="<?php echo api_htmlentities($dbHostForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="dbUsernameForm"       value="<?php echo api_htmlentities($dbUsernameForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="dbPassForm"           value="<?php echo api_htmlentities($dbPassForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="singleDbForm"         value="<?php echo api_htmlentities($singleDbForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="dbPrefixForm"         value="<?php echo api_htmlentities($dbPrefixForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="dbNameForm"           value="<?php echo api_htmlentities($dbNameForm, ENT_QUOTES, $charset); ?>" />
-<?php
-	if($installType == 'update' OR $singleDbForm == 0)
-	{
-?>
-	<input type="hidden" name="dbStatsForm"          value="<?php echo api_htmlentities($dbStatsForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="dbScormForm"          value="<?php echo api_htmlentities($dbScormForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="dbUserForm"           value="<?php echo api_htmlentities($dbUserForm, ENT_QUOTES, $charset); ?>" />
-<?php
-	}
-	else
-	{
-?>
-	<input type="hidden" name="dbStatsForm"          value="<?php echo api_htmlentities($dbNameForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="dbUserForm"           value="<?php echo api_htmlentities($dbNameForm, ENT_QUOTES, $charset); ?>" />
-<?php
-	}
-?>
-	<input type="hidden" name="enableTrackingForm"   value="<?php echo api_htmlentities($enableTrackingForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="allowSelfReg"         value="<?php echo api_htmlentities($allowSelfReg, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="allowSelfRegProf"     value="<?php echo api_htmlentities($allowSelfRegProf, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="emailForm"            value="<?php echo api_htmlentities($emailForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="adminLastName"        value="<?php echo api_htmlentities($adminLastName, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="adminFirstName"       value="<?php echo api_htmlentities($adminFirstName, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="adminPhoneForm"       value="<?php echo api_htmlentities($adminPhoneForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="loginForm"            value="<?php echo api_htmlentities($loginForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="passForm"             value="<?php echo api_htmlentities($passForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="languageForm"         value="<?php echo api_htmlentities($languageForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="campusForm"           value="<?php echo api_htmlentities($campusForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="educationForm"        value="<?php echo api_htmlentities($educationForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="institutionForm"      value="<?php echo api_htmlentities($institutionForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="institutionUrlForm"   value="<?php echo api_stristr($institutionUrlForm, 'http://', false, $charset) ? api_htmlentities($institutionUrlForm, ENT_QUOTES, $charset) : api_stristr($institutionUrlForm, 'https://', false, $charset) ? api_htmlentities($institutionUrlForm, ENT_QUOTES, $charset) : 'http://'.api_htmlentities($institutionUrlForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="checkEmailByHashSent" value="<?php echo api_htmlentities($checkEmailByHashSent, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="ShowEmailnotcheckedToStudent" value="<?php echo api_htmlentities($ShowEmailnotcheckedToStudent, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="userMailCanBeEmpty"   value="<?php echo api_htmlentities($userMailCanBeEmpty, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="encryptPassForm"      value="<?php echo api_htmlentities($encryptPassForm, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="session_lifetime"  value="<?php echo api_htmlentities($session_lifetime, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="old_version"  value="<?php echo api_htmlentities($my_old_version, ENT_QUOTES, $charset); ?>" />
-	<input type="hidden" name="new_version"  value="<?php echo api_htmlentities($new_version, ENT_QUOTES, $charset); ?>" />
-
-
-
-
-<?php
-if($_POST['step2'])
-{
-	//STEP 3 : LICENSE
-	display_license_agreement();
-}
-elseif($_POST['step3'])
-{
-	//STEP 4 : MYSQL DATABASE SETTINGS
-	display_database_settings_form($installType, $dbHostForm, $dbUsernameForm, $dbPassForm, $dbPrefixForm, $enableTrackingForm, $singleDbForm, $dbNameForm, $dbStatsForm, $dbScormForm, $dbUserForm);
-}
-elseif($_POST['step4'])
-{
-
-	//STEP 5 : CONFIGURATION SETTINGS
-	//if update, try getting settings from the database...
-	if($installType == 'update')
-	{
-		$db_name = $dbNameForm;
-		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'platformLanguage');
-		if(!empty($tmp)) $languageForm = $tmp;
-		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'emailAdministrator');
-		if(!empty($tmp)) $emailForm = $tmp;
-		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'administratorName');
-		if(!empty($tmp)) $adminFirstName = $tmp;
-		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'administratorSurname');
-		if(!empty($tmp)) $adminLastName = $tmp;
-		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'administratorTelephone');
-		if(!empty($tmp)) $adminPhoneForm = $tmp;
-		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'siteName');
-		if(!empty($tmp)) $campusForm = $tmp;
-		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'Institution');
-		if(!empty($tmp)) $institutionForm = $tmp;
-		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'InstitutionUrl');
-		if(!empty($tmp)) $institutionUrlForm = $tmp;
-		if(in_array($my_old_version,$update_from_version_6))
-		{   //for version 1.6
-			$urlForm = get_config_param('rootWeb');
-			$encryptPassForm = get_config_param('userPasswordCrypted');
-			// Managing the $encryptPassForm
-			if ($encryptPassForm=='1' ) {
-				$encryptPassForm = 'md5';
-			} elseif ($encryptPassForm=='0') {
-				$encryptPassForm = 'none';
-			}
-
-			$allowSelfReg = get_config_param('allowSelfReg');
-			$allowSelfRegProf = get_config_param('allowSelfRegProf');
-		}
-		else
-		{   //for version 1.8
-			$urlForm = $_configuration['root_web'];
-			$encryptPassForm = get_config_param('userPasswordCrypted');
-			// Managing the $encryptPassForm
-			if ($encryptPassForm=='1' ) {
-				$encryptPassForm = 'md5';
-			} elseif ($encryptPassForm=='0') {
-				$encryptPassForm = 'none';
-			}
-
-			$allowSelfReg = false;
-			$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'allow_registration');
-			if(!empty($tmp)) $allowSelfReg = $tmp;
-			$allowSelfRegProf = false;
-			$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'allow_registration_as_teacher');
-			if(!empty($tmp)) $allowSelfRegProf = $tmp;
-		}
-	}
-	display_configuration_settings_form($installType, $urlForm, $languageForm, $emailForm, $adminFirstName, $adminLastName, $adminPhoneForm, $campusForm, $institutionForm, $institutionUrlForm, $encryptPassForm, $allowSelfReg, $allowSelfRegProf, $loginForm, $passForm);
-}
-elseif($_POST['step5'])
-{
-	//STEP 6 : LAST CHECK BEFORE INSTALL
-?>
-
-	<h2><?php echo display_step_sequence().get_lang('LastCheck'); ?></h2>
-
-	<?php echo get_lang('HereAreTheValuesYouEntered');?>
-	<br />
-	<b><?php echo get_lang('PrintThisPageToRememberPassAndOthers');?></b>
-
-	<blockquote>
-
-	<?php echo get_lang('MainLang').' : '.$languageForm; ?><br /><br />
-
-	<?php echo get_lang('DBHost').' : '.$dbHostForm; ?><br />
-	<?php echo get_lang('DBLogin').' : '.$dbUsernameForm; ?><br />
-	<?php echo get_lang('DBPassword').' : '.str_repeat('*',strlen($dbPassForm)); ?><br />
-	<?php if(!empty($dbPrefixForm)) echo get_lang('DbPrefixForm').' : '.$dbPrefixForm.'<br />'; ?>
-	<?php echo get_lang('MainDB').' : <b>'.$dbNameForm; ?></b><?php if($installType == 'new') echo ' (<font color="#cc0033">'.get_lang('ReadWarningBelow').'</font>)'; ?><br />
-	<?php
-	if(!$singleDbForm)
-	{
-		echo get_lang('StatDB').' : <b>'.$dbStatsForm.'</b>';
-		if($installType == 'new')
-		{
-			echo ' (<font color="#cc0033">'.get_lang('ReadWarningBelow').'</font>)';
-		}
-		echo '<br />';
-
-		echo get_lang('UserDB').' : <b>'.$dbUserForm.'</b>';
-		if($installType == 'new')
-		{
-			echo ' (<font color="#cc0033">'.get_lang('ReadWarningBelow').'</font>)';
-		}
-		echo '<br />';
-	}
-	?>
-	<?php echo get_lang('EnableTracking').' : '.($enableTrackingForm?get_lang('Yes'):get_lang('No')); ?><br />
-	<?php echo get_lang('SingleDb').' : '.($singleDbForm?get_lang('One'):get_lang('Several')); ?><br /><br />
-
-	<?php echo get_lang('AllowSelfReg').' : '.($allowSelfReg?get_lang('Yes'):get_lang('No')); ?><br />
-	<?php echo get_lang('EncryptMethodUserPass').' : ';
-  	echo $encryptPassForm;
-	?><br /><br/>
-
-	<?php echo get_lang('AdminEmail').' : '.$emailForm; ?><br />
-	<?php
-	if (api_is_western_name_order()) {
-		echo get_lang('AdminFirstName').' : '.$adminFirstName, '<br />', get_lang('AdminLastName').' : '.$adminLastName, '<br />';
-	} else {
-		echo get_lang('AdminLastName').' : '.$adminLastName, '<br />', get_lang('AdminFirstName').' : '.$adminFirstName, '<br />';
-	}
-	?>
-	<?php echo get_lang('AdminPhone').' : '.$adminPhoneForm; ?><br />
-
-	<?php if($installType == 'new'): ?>
-	<?php echo get_lang('AdminLogin').' : <b>'.$loginForm; ?></b><br />
-	<?php echo get_lang('AdminPass').' : <b>'.$passForm; ?></b><br /><br />
-	<?php else: ?>
-	<br />
-	<?php endif; ?>
-
-	<?php echo get_lang('CampusName').' : '.$campusForm; ?><br />
-	<?php echo get_lang('InstituteShortName').' : '.$institutionForm; ?><br />
-	<?php echo get_lang('InstituteURL').' : '.$institutionUrlForm; ?><br />
-	<?php echo get_lang('DokeosURL').' : '.$urlForm; ?><br />
-
-	</blockquote>
-
-	<?php if($installType == 'new'): ?>
-	<div style="background-color:#FFFFFF">
-	<p align="center"><b><font color="red">
-	<?php echo get_lang('Warning');?> !<br />
-	<?php echo get_lang('TheInstallScriptWillEraseAllTables');?>
-	</font></b></p>
-	</div>
-	<?php endif; ?>
-
-	<table width="100%">
-	<tr>
-	  <td><button type="submit" class="back" name="step4" value="&lt; <?php echo get_lang('Previous'); ?>" /><?php echo get_lang('Previous'); ?></button></td>
-	  <td align="right"><input type="hidden" name="is_executable" id="is_executable" value="-" /><button class="save" type="submit" name="step6" value="<?php echo get_lang('InstallDokeos'); ?> &gt;" onclick="javascript:if(this.value == '<?php $msg = get_lang('PleaseWait');?>...') return false; else this.value='<?php $msg = get_lang('InstallDokeos');?>...';" ><?php echo $msg; ?></button></td>
-	</tr>
-	</table>
-
-<?php
-}
-elseif($_POST['step6'])
-{
-	//STEP 6 : INSTALLATION PROCESS
-	if($installType == 'update')
-	{
-		if(empty($my_old_version)){$my_old_version='1.8.6';} //we guess
-		$_configuration['main_database'] = $dbNameForm;
-		//$urlAppendPath = get_config_param('urlAppend');
-        error_log('Starting migration process from '.$my_old_version.' ('.time().')',0);
-
-    	if ($userPasswordCrypted=='1' ) {
-			$userPasswordCrypted = 'md5';
-		} elseif ($userPasswordCrypted=='0') {
-			$userPasswordCrypted = 'none';
-		}
-
-		switch($my_old_version)
-		{
-			case '1.6':
-			case '1.6.0':
-			case '1.6.1':
-			case '1.6.2':
-			case '1.6.3':
-			case '1.6.4':
-			case '1.6.5':
-				include('update-db-1.6.x-1.8.0.inc.php');
-				include('update-files-1.6.x-1.8.0.inc.php');
-				//intentionally no break to continue processing
-			case '1.8':
-			case '1.8.0':
-				include('update-db-1.8.0-1.8.2.inc.php');
-				//intentionally no break to continue processing
-			case '1.8.2':
-				include('update-db-1.8.2-1.8.3.inc.php');
-				//intentionally no break to continue processing
-			case '1.8.3':
-				include('update-db-1.8.3-1.8.4.inc.php');
-				include('update-files-1.8.3-1.8.4.inc.php');
-			case '1.8.4':
-				include('update-db-1.8.4-1.8.5.inc.php');
-                include('update-files-1.8.4-1.8.5.inc.php');
-			case '1.8.5':
-				include('update-db-1.8.5-1.8.6.inc.php');
-                include('update-files-1.8.5-1.8.6.inc.php');
-            case '1.8.6':
-                include('update-db-1.8.6-1.8.6.1.inc.php');
-                include('update-files-1.8.6-1.8.6.1.inc.php');
-            default:
-
-				break;
-		}
-	}
-	else
-	{
-		include('install_db.inc.php');
-		include('install_files.inc.php');
-	}
-
-	display_after_install_message($installType, $nbr_courses);
-}
-elseif($_POST['step1'] || $badUpdatePath)
-{
-	//STEP 1 : REQUIREMENTS
-	//make sure that proposed path is set, shouldn't be necessary but...
-	if(empty($proposedUpdatePath)){$proposedUpdatePath = $_POST['updatePath'];}
-	display_requirements($installType, $badUpdatePath, $proposedUpdatePath, $update_from_version_8, $update_from_version_6);
-}
-else
-{
-	//start screen
-	display_language_selection();
-}
-?>
-  </td>
-</tr>
-</table>
-</form>
-<br style="clear:both;" />
-<div class="push"></div>
-</div><!-- wrapper end-->
-<div id="footer">
-	<div class="copyright"><?php echo get_lang('Platform');?> <a href="http://www.dokeos.com" target="_blank"> Dokeos <?php echo $new_version ?></a> &copy; <?php echo date('Y'); ?> </div>
-	&nbsp;
-</div>
-</body>
-</html>
+
+require_once 'install_upgrade.lib.php'; //also defines constants
+require_once 'install_functions.inc.php';
+
+// Some constants
+define('DOKEOS_INSTALL',1);
+define('MAX_COURSE_TRANSFER',100);
+define('INSTALL_TYPE_UPDATE', 'update');
+define('FORM_FIELD_DISPLAY_LENGTH', 40);
+define('DATABASE_FORM_FIELD_DISPLAY_LENGTH', 25);
+define('MAX_FORM_FIELD_LENGTH', 80);
+define('DEFAULT_LANGUAGE', 'english');
+
+// setting the error reporting
+error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
+
+// overriding the timelimit (for large campusses that have to be migrated)
+@set_time_limit(0);
+
+//upgrading from any subversion of 1.6 is just like upgrading from 1.6.5
+$update_from_version_6=array('1.6','1.6.1','1.6.2','1.6.3','1.6.4','1.6.5');
+//upgrading from any subversion of 1.8 avoids the additional step of upgrading from 1.6
+$update_from_version_8=array('1.8','1.8.2','1.8.3','1.8.4','1.8.5','1.8.6');
+$my_old_version = '';
+$tmp_version = get_config_param('dokeos_version');
+if(!empty($_POST['old_version'])) {
+	$my_old_version = $_POST['old_version'];
+} elseif(!empty($tmp_version)) {
+    $my_old_version = $tmp_version;
+}
+elseif(!empty($dokeos_version)) //variable coming from installedVersion, normally
+{
+	$my_old_version = $dokeos_version;
+}
+
+$new_version = '1.8.6.1';
+$new_version_stable = true;
+$new_version_major = false;
+/*
+==============================================================================
+		STEP 1 : INITIALIZES FORM VARIABLES IF IT IS THE FIRST VISIT
+==============================================================================
+*/
+
+//Is valid request
+$is_valid_request=$_REQUEST['is_executable'];
+foreach ($_POST as $request_index=>$request_value) {
+	if (substr($request_index,0,4)=='step') {
+		if ($request_index<>$is_valid_request) {
+			unset($_POST[$request_index]);
+		}
+	}
+}
+
+$badUpdatePath=false;
+$emptyUpdatePath=true;
+$proposedUpdatePath = '';
+if(!empty($_POST['updatePath']))
+{
+	$proposedUpdatePath = $_POST['updatePath'];
+}
+
+if ($_POST['step2_install'] || $_POST['step2_update_8'] || $_POST['step2_update_6']) {
+	if ($_POST['step2_install']) {
+		$installType='new';
+
+		$_POST['step2']=1;
+	} else {
+		$installType='update';
+		if($_POST['step2_update_8'])
+		{
+			$emptyUpdatePath = false;
+			if(empty($_POST['updatePath']))
+			{
+				$proposedUpdatePath = $_SERVER['DOCUMENT_ROOT'];
+			}
+			else
+			{
+				$proposedUpdatePath = $_POST['updatePath'];
+			}
+			if(substr($proposedUpdatePath,-1) != '/')
+			{
+				$proposedUpdatePath.='/';
+			}
+			if(file_exists($proposedUpdatePath))
+			{
+				if(in_array($my_old_version,$update_from_version_8))
+				{
+					$_POST['step2']=1;
+				}
+				else
+				{
+					$badUpdatePath=true;
+				}
+			}
+			else
+			{
+				$badUpdatePath=true;
+			}
+		}
+		else //step2_update_6, presumably
+		{
+			if(empty($_POST['updatePath']))
+			{
+				$_POST['step1']=1;
+			}
+			else
+			{
+				$emptyUpdatePath = false;
+				if(substr($_POST['updatePath'],-1) != '/')
+				{
+					$_POST['updatePath'].='/';
+				}
+
+				if(file_exists($_POST['updatePath']))
+				{
+					//1.6.x
+					$my_old_version = get_config_param('clarolineVersion',$_POST['updatePath']);
+					if(in_array($my_old_version,$update_from_version_6))
+					{
+						$_POST['step2']=1;
+						$proposedUpdatePath = $_POST['updatePath'];
+					}
+					else
+					{
+						$badUpdatePath=true;
+					}
+				}
+				else
+				{
+					$badUpdatePath=true;
+				}
+			}
+		}
+	}
+}
+elseif($_POST['step1'])
+{
+	$_POST['updatePath']='';
+	$installType='';
+	$updateFromConfigFile='';
+	unset($_GET['running']);
+}
+else
+{
+	$installType=$_GET['installType'];
+	$updateFromConfigFile=$_GET['updateFromConfigFile'];
+}
+
+if($installType=='update' && in_array($my_old_version,$update_from_version_8))
+{
+	include_once '../inc/conf/configuration.php';
+}
+
+if(!isset($_GET['running'])) {
+	$dbHostForm='localhost';
+	$dbUsernameForm='root';
+	$dbPassForm='';
+ 	$dbPrefixForm='';
+	$dbNameForm='dokeos_main';
+	$dbStatsForm='dokeos_stats';
+	$dbScormForm='dokeos_scorm';
+	$dbUserForm='dokeos_user';
+
+	// extract the path to append to the url if Dokeos is not installed on the web root directory
+	$urlAppendPath=str_replace('/main/install/index.php','',api_get_self());
+  	$urlForm='http://'.$_SERVER['HTTP_HOST'].$urlAppendPath.'/';
+	$pathForm=str_replace('\\','/',realpath('../..')).'/';
+
+	$emailForm=$_SERVER['SERVER_ADMIN'];
+	$email_parts = explode('@',$emailForm);
+	if($email_parts[1] == 'localhost')
+	{
+		$emailForm .= '.localdomain';
+	}
+	$adminLastName='Doe';
+	$adminFirstName='John';
+	$loginForm='admin';
+	$passForm=api_generate_password();
+
+	$campusForm='My campus';
+	$educationForm='Albert Einstein';
+	$adminPhoneForm='(000) 001 02 03';
+	$institutionForm='My Organisation';
+	$institutionUrlForm='http://www.dokeos.com';
+
+	$languageForm='english';
+
+	$checkEmailByHashSent=0;
+	$ShowEmailnotcheckedToStudent=1;
+	$userMailCanBeEmpty=1;
+	$allowSelfReg=1;
+	$allowSelfRegProf=1;
+	$enableTrackingForm=1;
+	$singleDbForm=0;
+	$encryptPassForm='md5';
+	$session_lifetime=360000;
+}
+else
+{
+	foreach($_POST as $key=>$val)
+	{
+		$magic_quotes_gpc=ini_get('magic_quotes_gpc')?true:false;
+
+		if(is_string($val))
+		{
+			if($magic_quotes_gpc)
+			{
+				$val=stripslashes($val);
+			}
+
+			$val=trim($val);
+
+			$_POST[$key]=$val;
+		}
+		elseif(is_array($val))
+		{
+			foreach($val as $key2=>$val2)
+			{
+				if($magic_quotes_gpc)
+				{
+					$val2=stripslashes($val2);
+				}
+
+				$val2=trim($val2);
+
+				$_POST[$key][$key2]=$val2;
+			}
+		}
+
+		$GLOBALS[$key]=$_POST[$key];
+	}
+}
+
+// The Steps
+$total_steps=7;
+if (!$_POST)
+{
+	$current_step=1;
+}
+elseif (!empty($_POST['language_list']) or !empty($_POST['step1']) or ((!empty($_POST['step2_update_8']) or (!empty($_POST['step2_update_6'])))  && ($emptyUpdatePath or $badUpdatePath)))
+{
+	$current_step=2;
+}
+elseif (!empty($_POST['step2']) or (!empty($_POST['step2_update_8']) or (!empty($_POST['step2_update_6'])) ))
+{
+	$current_step=3;
+}
+elseif (!empty($_POST['step3']))
+{
+	$current_step=4;
+}
+elseif (!empty($_POST['step4']))
+{
+	$current_step=5;
+}
+elseif (!empty($_POST['step5']))
+{
+	$current_step=6;
+}
+
+
+// Managing the $encryptPassForm
+if ($encryptPassForm=='1' ) {
+	$encryptPassForm = 'md5';
+} elseif ($encryptPassForm=='0') {
+	$encryptPassForm = 'none';
+}
+
+?>
+<!DOCTYPE html
+     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+	<title>&mdash; <?php echo get_lang('DokeosInstallation').' &mdash; '.get_lang('Version_').' '.$new_version; ?></title>
+	<style type="text/css" media="screen, projection">
+		/*<![CDATA[*/
+		@import "../css/dokeos_blue/default.css";
+		/*]]>*/
+	</style>
+	<script type="text/javascript" src="../inc/lib/javascript/jquery.js"></script>
+	<script type="text/javascript" >
+		$(document).ready( function() {
+			 //checked
+			if ($('#singleDb1').attr('checked')==false) {
+					$('#dbStatsForm').removeAttr('disabled');
+					$('#dbUserForm').removeAttr('disabled');
+					$('#dbStatsForm').attr('value','dokeos_stats');
+					$('#dbUserForm').attr('value','dokeos_user');
+			} else if($('#singleDb1').attr('checked')==true){
+					$('#dbStatsForm').attr('disabled','disabled');
+					$('#dbUserForm').attr('disabled','disabled');
+					$('#dbStatsForm').attr('value','dokeos_main');
+					$('#dbUserForm').attr('value','dokeos_main');
+			}
+		//Allow dokeos install in IE
+		$("button").click(function() {
+			$("#is_executable").attr("value",$(this).attr("name"));
+		});
+
+	 	} );
+	</script>
+	<script type="text/javascript">
+
+		function show_hide_tracking_and_user_db (my_option) {
+			if (my_option=='singleDb1') {
+				$('#dbStatsForm').attr('disabled','true');
+				$('#dbUserForm').attr('disabled','true');
+				$('#dbStatsForm').attr('value','dokeos_main');
+				$('#dbUserForm').attr('value','dokeos_main');
+			} else if (my_option=='singleDb0') {
+				$('#dbStatsForm').removeAttr('disabled');
+				$('#dbUserForm').removeAttr('disabled');
+				$('#dbStatsForm').attr('value','dokeos_stats');
+				$('#dbUserForm').attr('value','dokeos_user');
+			}
+		}
+	</script>
+	<script language="javascript">
+		init_visibility=0;
+		function show_hide_option() {
+			if(init_visibility == 0) {
+				document.getElementById('optional_param1').style.display = '';
+				document.getElementById('optional_param2').style.display = '';
+				if(document.getElementById('optional_param3'))
+				{
+					document.getElementById('optional_param3').style.display = '';
+				}
+				document.getElementById('optional_param4').style.display = '';
+				document.getElementById('optional_param5').style.display = '';
+				document.getElementById('optional_param6').style.display = '';
+				init_visibility = 1;
+			document.getElementById('optionalparameters').innerHTML='<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" /> <?php echo get_lang('OptionalParameters'); ?>';
+			} else {
+				document.getElementById('optional_param1').style.display = 'none';
+				document.getElementById('optional_param2').style.display = 'none';
+				if(document.getElementById('optional_param3')) {
+					document.getElementById('optional_param3').style.display = 'none';
+				}
+				document.getElementById('optional_param4').style.display = 'none';
+				document.getElementById('optional_param5').style.display = 'none';
+				document.getElementById('optional_param6').style.display = 'none';
+			document.getElementById('optionalparameters').innerHTML='<img style="vertical-align:middle;" src="../img/div_show.gif" alt="" /> <?php echo get_lang('OptionalParameters'); ?>';
+				init_visibility = 0;
+			}
+		}
+	</script>
+<?php if(!empty($charset)){ ?>
+	<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset ?>" />
+<?php } ?>
+</head>
+<body dir="<?php echo $text_dir ?>">
+
+<div id="wrapper">
+
+<div id="header">
+	<div id="header1"><?php echo get_lang('DokeosInstallation').' &mdash; '.get_lang('Version_').' '.$new_version; ?><?php if($installType == 'new') echo ' &ndash; '.get_lang('NewInstallation'); else if($installType == 'update') echo ' &ndash; '.get_lang('UpdateFromDokeosVersion').(is_array($update_from_version)?implode('|',$update_from_version):''); ?></div>
+	<div id="header2">&nbsp;</div>
+	<div id="header3">
+		<ul>
+			<li id="current"><a href="#"><span>Installation</span></a></li>
+		</ul>
+	</div>
+</div>
+
+
+<form style="padding: 0px; margin: 0px;" method="post" action="<?php echo api_get_self(); ?>?running=1&amp;installType=<?php echo $installType; ?>&amp;updateFromConfigFile=<?php echo urlencode($updateFromConfigFile); ?>">
+
+<div id="installation_steps" style="width:240px">
+	<img src="../img/bluelogo.gif" hspace="10" vspace="10" alt="Dokeos logo" />
+	<ol>
+		<li <?php step_active('1'); ?>><?php echo get_lang('InstallationLanguage'); ?></li>
+		<li <?php step_active('2'); ?>><?php echo get_lang('Requirements'); ?></li>
+		<li <?php step_active('3'); ?>><?php echo get_lang('Licence'); ?></li>
+		<li <?php step_active('4'); ?>><?php echo get_lang('DBSetting'); ?></li>
+		<li <?php step_active('5'); ?>><?php echo get_lang('CfgSetting'); ?></li>
+		<li <?php step_active('6'); ?>><?php echo get_lang('PrintOverview'); ?></li>
+		<li <?php step_active('7'); ?>><?php echo get_lang('Installing'); ?></li>
+	</ol>
+</div>
+
+<table cellpadding="6" cellspacing="0" border="0" width="72%" align="center">
+<tr>
+<td>
+	<div id="note" style="float:right;">
+		<a href="../../documentation/installation_guide.html" target="_blank">Read the installation guide</a>
+	</div>
+</td>
+</tr>
+<tr>
+  <td>
+	<input type="hidden" name="updatePath"           value="<?php if(!$badUpdatePath) echo api_htmlentities($proposedUpdatePath, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="urlAppendPath"        value="<?php echo api_htmlentities($urlAppendPath, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="pathForm"             value="<?php echo api_htmlentities($pathForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="urlForm"              value="<?php echo api_htmlentities($urlForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="dbHostForm"           value="<?php echo api_htmlentities($dbHostForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="dbUsernameForm"       value="<?php echo api_htmlentities($dbUsernameForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="dbPassForm"           value="<?php echo api_htmlentities($dbPassForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="singleDbForm"         value="<?php echo api_htmlentities($singleDbForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="dbPrefixForm"         value="<?php echo api_htmlentities($dbPrefixForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="dbNameForm"           value="<?php echo api_htmlentities($dbNameForm, ENT_QUOTES, $charset); ?>" />
+<?php
+	if($installType == 'update' OR $singleDbForm == 0)
+	{
+?>
+	<input type="hidden" name="dbStatsForm"          value="<?php echo api_htmlentities($dbStatsForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="dbScormForm"          value="<?php echo api_htmlentities($dbScormForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="dbUserForm"           value="<?php echo api_htmlentities($dbUserForm, ENT_QUOTES, $charset); ?>" />
+<?php
+	}
+	else
+	{
+?>
+	<input type="hidden" name="dbStatsForm"          value="<?php echo api_htmlentities($dbNameForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="dbUserForm"           value="<?php echo api_htmlentities($dbNameForm, ENT_QUOTES, $charset); ?>" />
+<?php
+	}
+?>
+	<input type="hidden" name="enableTrackingForm"   value="<?php echo api_htmlentities($enableTrackingForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="allowSelfReg"         value="<?php echo api_htmlentities($allowSelfReg, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="allowSelfRegProf"     value="<?php echo api_htmlentities($allowSelfRegProf, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="emailForm"            value="<?php echo api_htmlentities($emailForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="adminLastName"        value="<?php echo api_htmlentities($adminLastName, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="adminFirstName"       value="<?php echo api_htmlentities($adminFirstName, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="adminPhoneForm"       value="<?php echo api_htmlentities($adminPhoneForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="loginForm"            value="<?php echo api_htmlentities($loginForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="passForm"             value="<?php echo api_htmlentities($passForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="languageForm"         value="<?php echo api_htmlentities($languageForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="campusForm"           value="<?php echo api_htmlentities($campusForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="educationForm"        value="<?php echo api_htmlentities($educationForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="institutionForm"      value="<?php echo api_htmlentities($institutionForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="institutionUrlForm"   value="<?php echo api_stristr($institutionUrlForm, 'http://', false, $charset) ? api_htmlentities($institutionUrlForm, ENT_QUOTES, $charset) : api_stristr($institutionUrlForm, 'https://', false, $charset) ? api_htmlentities($institutionUrlForm, ENT_QUOTES, $charset) : 'http://'.api_htmlentities($institutionUrlForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="checkEmailByHashSent" value="<?php echo api_htmlentities($checkEmailByHashSent, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="ShowEmailnotcheckedToStudent" value="<?php echo api_htmlentities($ShowEmailnotcheckedToStudent, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="userMailCanBeEmpty"   value="<?php echo api_htmlentities($userMailCanBeEmpty, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="encryptPassForm"      value="<?php echo api_htmlentities($encryptPassForm, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="session_lifetime"  value="<?php echo api_htmlentities($session_lifetime, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="old_version"  value="<?php echo api_htmlentities($my_old_version, ENT_QUOTES, $charset); ?>" />
+	<input type="hidden" name="new_version"  value="<?php echo api_htmlentities($new_version, ENT_QUOTES, $charset); ?>" />
+
+
+
+
+<?php
+if($_POST['step2'])
+{
+	//STEP 3 : LICENSE
+	display_license_agreement();
+}
+elseif($_POST['step3'])
+{
+	//STEP 4 : MYSQL DATABASE SETTINGS
+	display_database_settings_form($installType, $dbHostForm, $dbUsernameForm, $dbPassForm, $dbPrefixForm, $enableTrackingForm, $singleDbForm, $dbNameForm, $dbStatsForm, $dbScormForm, $dbUserForm);
+}
+elseif($_POST['step4'])
+{
+
+	//STEP 5 : CONFIGURATION SETTINGS
+	//if update, try getting settings from the database...
+	if($installType == 'update')
+	{
+		$db_name = $dbNameForm;
+		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'platformLanguage');
+		if(!empty($tmp)) $languageForm = $tmp;
+		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'emailAdministrator');
+		if(!empty($tmp)) $emailForm = $tmp;
+		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'administratorName');
+		if(!empty($tmp)) $adminFirstName = $tmp;
+		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'administratorSurname');
+		if(!empty($tmp)) $adminLastName = $tmp;
+		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'administratorTelephone');
+		if(!empty($tmp)) $adminPhoneForm = $tmp;
+		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'siteName');
+		if(!empty($tmp)) $campusForm = $tmp;
+		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'Institution');
+		if(!empty($tmp)) $institutionForm = $tmp;
+		$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'InstitutionUrl');
+		if(!empty($tmp)) $institutionUrlForm = $tmp;
+		if(in_array($my_old_version,$update_from_version_6))
+		{   //for version 1.6
+			$urlForm = get_config_param('rootWeb');
+			$encryptPassForm = get_config_param('userPasswordCrypted');
+			// Managing the $encryptPassForm
+			if ($encryptPassForm=='1' ) {
+				$encryptPassForm = 'md5';
+			} elseif ($encryptPassForm=='0') {
+				$encryptPassForm = 'none';
+			}
+
+			$allowSelfReg = get_config_param('allowSelfReg');
+			$allowSelfRegProf = get_config_param('allowSelfRegProf');
+		}
+		else
+		{   //for version 1.8
+			$urlForm = $_configuration['root_web'];
+			$encryptPassForm = get_config_param('userPasswordCrypted');
+			// Managing the $encryptPassForm
+			if ($encryptPassForm=='1' ) {
+				$encryptPassForm = 'md5';
+			} elseif ($encryptPassForm=='0') {
+				$encryptPassForm = 'none';
+			}
+
+			$allowSelfReg = false;
+			$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'allow_registration');
+			if(!empty($tmp)) $allowSelfReg = $tmp;
+			$allowSelfRegProf = false;
+			$tmp = get_config_param_from_db($dbHostForm,$dbUsernameForm,$dbPassForm,$db_name,'allow_registration_as_teacher');
+			if(!empty($tmp)) $allowSelfRegProf = $tmp;
+		}
+	}
+	display_configuration_settings_form($installType, $urlForm, $languageForm, $emailForm, $adminFirstName, $adminLastName, $adminPhoneForm, $campusForm, $institutionForm, $institutionUrlForm, $encryptPassForm, $allowSelfReg, $allowSelfRegProf, $loginForm, $passForm);
+}
+elseif($_POST['step5'])
+{
+	//STEP 6 : LAST CHECK BEFORE INSTALL
+?>
+
+	<h2><?php echo display_step_sequence().get_lang('LastCheck'); ?></h2>
+
+	<?php echo get_lang('HereAreTheValuesYouEntered');?>
+	<br />
+	<b><?php echo get_lang('PrintThisPageToRememberPassAndOthers');?></b>
+
+	<blockquote>
+
+	<?php echo get_lang('MainLang').' : '.$languageForm; ?><br /><br />
+
+	<?php echo get_lang('DBHost').' : '.$dbHostForm; ?><br />
+	<?php echo get_lang('DBLogin').' : '.$dbUsernameForm; ?><br />
+	<?php echo get_lang('DBPassword').' : '.str_repeat('*',strlen($dbPassForm)); ?><br />
+	<?php if(!empty($dbPrefixForm)) echo get_lang('DbPrefixForm').' : '.$dbPrefixForm.'<br />'; ?>
+	<?php echo get_lang('MainDB').' : <b>'.$dbNameForm; ?></b><?php if($installType == 'new') echo ' (<font color="#cc0033">'.get_lang('ReadWarningBelow').'</font>)'; ?><br />
+	<?php
+	if(!$singleDbForm)
+	{
+		echo get_lang('StatDB').' : <b>'.$dbStatsForm.'</b>';
+		if($installType == 'new')
+		{
+			echo ' (<font color="#cc0033">'.get_lang('ReadWarningBelow').'</font>)';
+		}
+		echo '<br />';
+
+		echo get_lang('UserDB').' : <b>'.$dbUserForm.'</b>';
+		if($installType == 'new')
+		{
+			echo ' (<font color="#cc0033">'.get_lang('ReadWarningBelow').'</font>)';
+		}
+		echo '<br />';
+	}
+	?>
+	<?php echo get_lang('EnableTracking').' : '.($enableTrackingForm?get_lang('Yes'):get_lang('No')); ?><br />
+	<?php echo get_lang('SingleDb').' : '.($singleDbForm?get_lang('One'):get_lang('Several')); ?><br /><br />
+
+	<?php echo get_lang('AllowSelfReg').' : '.($allowSelfReg?get_lang('Yes'):get_lang('No')); ?><br />
+	<?php echo get_lang('EncryptMethodUserPass').' : ';
+  	echo $encryptPassForm;
+	?><br /><br/>
+
+	<?php echo get_lang('AdminEmail').' : '.$emailForm; ?><br />
+	<?php
+	if (api_is_western_name_order()) {
+		echo get_lang('AdminFirstName').' : '.$adminFirstName, '<br />', get_lang('AdminLastName').' : '.$adminLastName, '<br />';
+	} else {
+		echo get_lang('AdminLastName').' : '.$adminLastName, '<br />', get_lang('AdminFirstName').' : '.$adminFirstName, '<br />';
+	}
+	?>
+	<?php echo get_lang('AdminPhone').' : '.$adminPhoneForm; ?><br />
+
+	<?php if($installType == 'new'): ?>
+	<?php echo get_lang('AdminLogin').' : <b>'.$loginForm; ?></b><br />
+	<?php echo get_lang('AdminPass').' : <b>'.$passForm; ?></b><br /><br />
+	<?php else: ?>
+	<br />
+	<?php endif; ?>
+
+	<?php echo get_lang('CampusName').' : '.$campusForm; ?><br />
+	<?php echo get_lang('InstituteShortName').' : '.$institutionForm; ?><br />
+	<?php echo get_lang('InstituteURL').' : '.$institutionUrlForm; ?><br />
+	<?php echo get_lang('DokeosURL').' : '.$urlForm; ?><br />
+
+	</blockquote>
+
+	<?php if($installType == 'new'): ?>
+	<div style="background-color:#FFFFFF">
+	<p align="center"><b><font color="red">
+	<?php echo get_lang('Warning');?> !<br />
+	<?php echo get_lang('TheInstallScriptWillEraseAllTables');?>
+	</font></b></p>
+	</div>
+	<?php endif; ?>
+
+	<table width="100%">
+	<tr>
+	  <td><button type="submit" class="back" name="step4" value="&lt; <?php echo get_lang('Previous'); ?>" /><?php echo get_lang('Previous'); ?></button></td>
+	  <td align="right"><input type="hidden" name="is_executable" id="is_executable" value="-" /><button class="save" type="submit" name="step6" value="<?php echo get_lang('InstallDokeos'); ?> &gt;" onclick="javascript:if(this.value == '<?php $msg = get_lang('PleaseWait');?>...') return false; else this.value='<?php $msg = get_lang('InstallDokeos');?>...';" ><?php echo $msg; ?></button></td>
+	</tr>
+	</table>
+
+<?php
+}
+elseif($_POST['step6'])
+{
+	//STEP 6 : INSTALLATION PROCESS
+	if($installType == 'update')
+	{
+		if(empty($my_old_version)){$my_old_version='1.8.6';} //we guess
+		$_configuration['main_database'] = $dbNameForm;
+		//$urlAppendPath = get_config_param('urlAppend');
+        error_log('Starting migration process from '.$my_old_version.' ('.time().')',0);
+
+    	if ($userPasswordCrypted=='1' ) {
+			$userPasswordCrypted = 'md5';
+		} elseif ($userPasswordCrypted=='0') {
+			$userPasswordCrypted = 'none';
+		}
+
+		switch($my_old_version)
+		{
+			case '1.6':
+			case '1.6.0':
+			case '1.6.1':
+			case '1.6.2':
+			case '1.6.3':
+			case '1.6.4':
+			case '1.6.5':
+				include('update-db-1.6.x-1.8.0.inc.php');
+				include('update-files-1.6.x-1.8.0.inc.php');
+				//intentionally no break to continue processing
+			case '1.8':
+			case '1.8.0':
+				include('update-db-1.8.0-1.8.2.inc.php');
+				//intentionally no break to continue processing
+			case '1.8.2':
+				include('update-db-1.8.2-1.8.3.inc.php');
+				//intentionally no break to continue processing
+			case '1.8.3':
+				include('update-db-1.8.3-1.8.4.inc.php');
+				include('update-files-1.8.3-1.8.4.inc.php');
+			case '1.8.4':
+				include('update-db-1.8.4-1.8.5.inc.php');
+                include('update-files-1.8.4-1.8.5.inc.php');
+			case '1.8.5':
+				include('update-db-1.8.5-1.8.6.inc.php');
+                include('update-files-1.8.5-1.8.6.inc.php');
+            case '1.8.6':
+                include('update-db-1.8.6-1.8.6.1.inc.php');
+                include('update-files-1.8.6-1.8.6.1.inc.php');
+            default:
+
+				break;
+		}
+	}
+	else
+	{
+		include('install_db.inc.php');
+		include('install_files.inc.php');
+	}
+
+	display_after_install_message($installType, $nbr_courses);
+}
+elseif($_POST['step1'] || $badUpdatePath)
+{
+	//STEP 1 : REQUIREMENTS
+	//make sure that proposed path is set, shouldn't be necessary but...
+	if(empty($proposedUpdatePath)){$proposedUpdatePath = $_POST['updatePath'];}
+	display_requirements($installType, $badUpdatePath, $proposedUpdatePath, $update_from_version_8, $update_from_version_6);
+}
+else
+{
+	//start screen
+	display_language_selection();
+}
+?>
+  </td>
+</tr>
+</table>
+</form>
+<br style="clear:both;" />
+<div class="push"></div>
+</div><!-- wrapper end-->
+<div id="footer">
+	<div class="copyright"><?php echo get_lang('Platform');?> <a href="http://www.dokeos.com" target="_blank"> Dokeos <?php echo $new_version ?></a> &copy; <?php echo date('Y'); ?> </div>
+	&nbsp;
+</div>
+</body>
+</html>

+ 1210 - 1210
main/install/install_functions.inc.php

@@ -1,1231 +1,1231 @@
-<?php
-/**
- * This function prints class=active_step $current_step=$param
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- */
-function step_active($param)
-{
-	global $current_step;
-
-	if ($param==$current_step)
-	{
-		echo 'class="current_step" ';
-	}
-}
-
-/**
- * This function displays the Step X of Y -
- * @return	string	String that says 'Step X of Y' with the right values
- */
-function display_step_sequence()
-{
-	global $current_step;
-	global $total_steps;
-
-	return get_lang('Step'.$current_step).' &ndash; ';
-}
-/**
- * This function checks if a php extension exists or not and returns an HTML
- * status string.
- *
- * @param 	string  Name of the PHP extension to be checked
- * @param 	string  Text to show when extension is available (defaults to 'OK')
- * @param	string	Text to show when extension is available (defaults to 'KO')
- * @param	boolean	Whether this extension is optional (in this case show unavailable text in orange rather than red)
- * @return	string	HTML string reporting the status of this extension. Language-aware.
- * @author 	Christophe Gesche
- * @author 	Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @author	Yannick Warnier <yannick.warnier@dokeos.com>
- * @version Dokeos 1.8.1, May 2007
- */
-function check_extension($extension_name,$return_success='Yes',$return_failure='No',$optional=false)
-{
-	if(extension_loaded($extension_name))
-	{
-		return '<strong><font color="green">'.$return_success.'</font></strong>';
-	}
-	else
-	{
-		if($optional===true)
-		{
-			return '<strong><font color="#ff9900">'.$return_failure.'</font></strong>';
-		}
-		else
-		{
-			return '<strong><font color="red">'.$return_failure.'</font></strong>';
-		}
-	}
-}
-
-
-/**
- * This function checks whether a php setting matches the recommended value
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @version Dokeos 1.8, august 2006
- */
-function check_php_setting($php_setting, $recommended_value, $return_success=false, $return_failure=false)
-{
-	$current_php_value = get_php_setting($php_setting);
-	if ( $current_php_value== $recommended_value)
-	{
-		return '<strong><font color="green">'.$current_php_value.' '.$return_success.'</font></strong>';
-	}
-	else
-	{
-		return '<strong><font color="red">'.$current_php_value.' '.$return_failure.'</font></strong>';
-	}
-}
-/**
- * Enter description here...
- *
- * @param string $val a php ini value
- * @return boolean: ON or OFF
- * @author Joomla <http://www.joomla.org>
- */
-function get_php_setting($val) {
-	$r =  (ini_get($val) == '1' ? 1 : 0);
-	return $r ? 'ON' : 'OFF';
-}
-
-/**
- * This function checks if the given folder is writable
- */
-function check_writable($folder)
-{
-	if (is_writable('../'.$folder))
-	{
-		return '<strong><font color="green">'.get_lang('Writable').'</font></strong>';
-	}
-	else
-	{
-		return '<strong><font color="red">'.get_lang('NotWritable').'</font></strong>';
-	}
-}
-
-/**
- * this function returns a string "FALSE" or "TRUE" according to the variable in parameter
- *
- * @param integer  $var  the variable to convert
- * @return  string  the string "FALSE" or "TRUE"
- * @author Christophe Gesche
- */
-function trueFalse($var)
-{
-	return $var?'true':'false';
-}
-
-/**
- * This function is similar to the core file() function, except that it
- * works with line endings in Windows (which is not the case of file())
- * @param	string	File path
- * @return	array	The lines of the file returned as an array
- */
-function file_to_array($filename)
-{
-	$fp = fopen($filename, "rb");
-	$buffer = fread($fp, filesize($filename));
-	fclose($fp);
-	$result = explode('<br />',nl2br($buffer));
-	return $result;
-}
-
-/**
- * This function returns the value of a parameter from the configuration file
- *
- * WARNING - this function relies heavily on global variables $updateFromConfigFile
- * and $configFile, and also changes these globals. This can be rewritten.
- *
- * @param 	string  $param  the parameter of which the value is returned
- * @param	string	If we want to give the path rather than take it from POST
- * @return  string  the value of the parameter
- * @author Olivier Brouckaert
- */
-function get_config_param($param,$updatePath='')
-{
-	global $configFile, $updateFromConfigFile;
-	//look if we already have the queried param
-	if(is_array($configFile) && isset($configFile[$param]))
-	{
-		return $configFile[$param];
-	}
-	if(empty($updatePath) && !empty($_POST['updatePath']))
-	{
-		$updatePath = $_POST['updatePath'];
-	}
-	$updatePath = realpath($updatePath).'/';
-	$updateFromInstalledVersionFile = '';
-
-	if(empty($updateFromConfigFile)) //if update from previous install was requested
-	{
-		//try to recover old config file from dokeos 1.8.x
-		if(file_exists($updatePath.'main/inc/conf/configuration.php'))
-		{
-			$updateFromConfigFile='main/inc/conf/configuration.php';
-		}
-		elseif(file_exists($updatePath.'claroline/inc/conf/claro_main.conf.php'))
-		{
-			$updateFromConfigFile='claroline/inc/conf/claro_main.conf.php';
-		}
-		//give up recovering
-		else
-		{
-			error_log('Could not find config file in '.$updatePath.' in get_config_param()',0);
-			return null;
-		}
+<?php
+/**
+ * This function prints class=active_step $current_step=$param
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+ */
+function step_active($param)
+{
+	global $current_step;
+
+	if ($param==$current_step)
+	{
+		echo 'class="current_step" ';
 	}
-	if(file_exists($updatePath.'main/inc/installedVersion.inc.php'))
-	{
-		$updateFromInstalledVersionFile = $updatePath.'main/inc/installedVersion.inc.php';
-	}
-	//the param was not found in global vars, so look into the old config file
-	elseif(file_exists($updatePath.$updateFromConfigFile))
-	{
-		//make sure the installedVersion file is read first so it is overwritten
-		//by the config file if the config file contains the version (from 1.8.4)
-		$temp2 = array();
-		if(file_exists($updatePath.$updateFromInstalledVersionFile))
-		{
-			$temp2 = file_to_array($updatePath.$updateFromInstalledVersionFile);
+}
+
+/**
+ * This function displays the Step X of Y -
+ * @return	string	String that says 'Step X of Y' with the right values
+ */
+function display_step_sequence()
+{
+	global $current_step;
+	global $total_steps;
+
+	return get_lang('Step'.$current_step).' &ndash; ';
+}
+/**
+ * This function checks if a php extension exists or not and returns an HTML
+ * status string.
+ *
+ * @param 	string  Name of the PHP extension to be checked
+ * @param 	string  Text to show when extension is available (defaults to 'OK')
+ * @param	string	Text to show when extension is available (defaults to 'KO')
+ * @param	boolean	Whether this extension is optional (in this case show unavailable text in orange rather than red)
+ * @return	string	HTML string reporting the status of this extension. Language-aware.
+ * @author 	Christophe Gesche
+ * @author 	Patrick Cool <patrick.cool@UGent.be>, Ghent University
+ * @author	Yannick Warnier <yannick.warnier@dokeos.com>
+ * @version Dokeos 1.8.1, May 2007
+ */
+function check_extension($extension_name,$return_success='Yes',$return_failure='No',$optional=false)
+{
+	if(extension_loaded($extension_name))
+	{
+		return '<strong><font color="green">'.$return_success.'</font></strong>';
+	}
+	else
+	{
+		if($optional===true)
+		{
+			return '<strong><font color="#ff9900">'.$return_failure.'</font></strong>';
+		}
+		else
+		{
+			return '<strong><font color="red">'.$return_failure.'</font></strong>';
 		}
-		$configFile=array();
-		$temp=file_to_array($updatePath.$updateFromConfigFile);
-		$temp = array_merge($temp,$temp2);
-		$val='';
-
-		//parse the config file (TODO clarify why it has to be so complicated)
-		foreach($temp as $enreg)
-		{
-			if(strstr($enreg,'='))
-			{
-				$enreg=explode('=',$enreg);
-				$enreg[0] = trim($enreg[0]);
-				if($enreg[0][0] == '$')
-				{
-					list($enreg[1])=explode(' //',$enreg[1]);
-
-					$enreg[0]=trim(str_replace('$','',$enreg[0]));
-					$enreg[1]=str_replace('\"','"',ereg_replace('(^"|"$)','',substr(trim($enreg[1]),0,-1)));
-					$enreg[1]=str_replace('\'','"',ereg_replace('(^\'|\'$)','',$enreg[1]));
-					if(strtolower($enreg[1]) == 'true')
-					{
-						$enreg[1]=1;
-					}
-					if(strtolower($enreg[1]) == 'false')
-					{
-						$enreg[1]=0;
-					}
-					else
-					{
-						$implode_string=' ';
-
-						if(!strstr($enreg[1],'." ".') && strstr($enreg[1],'.$'))
-						{
-							$enreg[1]=str_replace('.$','." ".$',$enreg[1]);
-							$implode_string='';
-						}
-
-						$tmp=explode('." ".',$enreg[1]);
-
-						foreach($tmp as $tmp_key=>$tmp_val)
-						{
-							if(eregi('^\$[a-z_][a-z0-9_]*$',$tmp_val))
-							{
-								$tmp[$tmp_key]=get_config_param(str_replace('$','',$tmp_val));
-							}
-						}
-
-						$enreg[1]=implode($implode_string,$tmp);
-					}
-
-					$configFile[$enreg[0]]=$enreg[1];
-
-					$a=explode("'",$enreg[0]);
+	}
+}
+
+
+/**
+ * This function checks whether a php setting matches the recommended value
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+ * @version Dokeos 1.8, august 2006
+ */
+function check_php_setting($php_setting, $recommended_value, $return_success=false, $return_failure=false)
+{
+	$current_php_value = get_php_setting($php_setting);
+	if ( $current_php_value== $recommended_value)
+	{
+		return '<strong><font color="green">'.$current_php_value.' '.$return_success.'</font></strong>';
+	}
+	else
+	{
+		return '<strong><font color="red">'.$current_php_value.' '.$return_failure.'</font></strong>';
+	}
+}
+/**
+ * Enter description here...
+ *
+ * @param string $val a php ini value
+ * @return boolean: ON or OFF
+ * @author Joomla <http://www.joomla.org>
+ */
+function get_php_setting($val) {
+	$r =  (ini_get($val) == '1' ? 1 : 0);
+	return $r ? 'ON' : 'OFF';
+}
+
+/**
+ * This function checks if the given folder is writable
+ */
+function check_writable($folder)
+{
+	if (is_writable('../'.$folder))
+	{
+		return '<strong><font color="green">'.get_lang('Writable').'</font></strong>';
+	}
+	else
+	{
+		return '<strong><font color="red">'.get_lang('NotWritable').'</font></strong>';
+	}
+}
+
+/**
+ * this function returns a string "FALSE" or "TRUE" according to the variable in parameter
+ *
+ * @param integer  $var  the variable to convert
+ * @return  string  the string "FALSE" or "TRUE"
+ * @author Christophe Gesche
+ */
+function trueFalse($var)
+{
+	return $var?'true':'false';
+}
+
+/**
+ * This function is similar to the core file() function, except that it
+ * works with line endings in Windows (which is not the case of file())
+ * @param	string	File path
+ * @return	array	The lines of the file returned as an array
+ */
+function file_to_array($filename)
+{
+	$fp = fopen($filename, "rb");
+	$buffer = fread($fp, filesize($filename));
+	fclose($fp);
+	$result = explode('<br />',nl2br($buffer));
+	return $result;
+}
+
+/**
+ * This function returns the value of a parameter from the configuration file
+ *
+ * WARNING - this function relies heavily on global variables $updateFromConfigFile
+ * and $configFile, and also changes these globals. This can be rewritten.
+ *
+ * @param 	string  $param  the parameter of which the value is returned
+ * @param	string	If we want to give the path rather than take it from POST
+ * @return  string  the value of the parameter
+ * @author Olivier Brouckaert
+ */
+function get_config_param($param,$updatePath='')
+{
+	global $configFile, $updateFromConfigFile;
+	//look if we already have the queried param
+	if(is_array($configFile) && isset($configFile[$param]))
+	{
+		return $configFile[$param];
+	}
+	if(empty($updatePath) && !empty($_POST['updatePath']))
+	{
+		$updatePath = $_POST['updatePath'];
+	}
+	$updatePath = realpath($updatePath).'/';
+	$updateFromInstalledVersionFile = '';
+
+	if(empty($updateFromConfigFile)) //if update from previous install was requested
+	{
+		//try to recover old config file from dokeos 1.8.x
+		if(file_exists($updatePath.'main/inc/conf/configuration.php'))
+		{
+			$updateFromConfigFile='main/inc/conf/configuration.php';
+		}
+		elseif(file_exists($updatePath.'claroline/inc/conf/claro_main.conf.php'))
+		{
+			$updateFromConfigFile='claroline/inc/conf/claro_main.conf.php';
+		}
+		//give up recovering
+		else
+		{
+			error_log('Could not find config file in '.$updatePath.' in get_config_param()',0);
+			return null;
+		}
+	}
+	if(file_exists($updatePath.'main/inc/installedVersion.inc.php'))
+	{
+		$updateFromInstalledVersionFile = $updatePath.'main/inc/installedVersion.inc.php';
+	}
+	//the param was not found in global vars, so look into the old config file
+	elseif(file_exists($updatePath.$updateFromConfigFile))
+	{
+		//make sure the installedVersion file is read first so it is overwritten
+		//by the config file if the config file contains the version (from 1.8.4)
+		$temp2 = array();
+		if(file_exists($updatePath.$updateFromInstalledVersionFile))
+		{
+			$temp2 = file_to_array($updatePath.$updateFromInstalledVersionFile);
+		}
+		$configFile=array();
+		$temp=file_to_array($updatePath.$updateFromConfigFile);
+		$temp = array_merge($temp,$temp2);
+		$val='';
+
+		//parse the config file (TODO clarify why it has to be so complicated)
+		foreach($temp as $enreg)
+		{
+			if(strstr($enreg,'='))
+			{
+				$enreg=explode('=',$enreg);
+				$enreg[0] = trim($enreg[0]);
+				if($enreg[0][0] == '$')
+				{
+					list($enreg[1])=explode(' //',$enreg[1]);
+
+					$enreg[0]=trim(str_replace('$','',$enreg[0]));
+					$enreg[1]=str_replace('\"','"',ereg_replace('(^"|"$)','',substr(trim($enreg[1]),0,-1)));
+					$enreg[1]=str_replace('\'','"',ereg_replace('(^\'|\'$)','',$enreg[1]));
+					if(strtolower($enreg[1]) == 'true')
+					{
+						$enreg[1]=1;
+					}
+					if(strtolower($enreg[1]) == 'false')
+					{
+						$enreg[1]=0;
+					}
+					else
+					{
+						$implode_string=' ';
+
+						if(!strstr($enreg[1],'." ".') && strstr($enreg[1],'.$'))
+						{
+							$enreg[1]=str_replace('.$','." ".$',$enreg[1]);
+							$implode_string='';
+						}
+
+						$tmp=explode('." ".',$enreg[1]);
+
+						foreach($tmp as $tmp_key=>$tmp_val)
+						{
+							if(eregi('^\$[a-z_][a-z0-9_]*$',$tmp_val))
+							{
+								$tmp[$tmp_key]=get_config_param(str_replace('$','',$tmp_val));
+							}
+						}
+
+						$enreg[1]=implode($implode_string,$tmp);
+					}
+
+					$configFile[$enreg[0]]=$enreg[1];
+
+					$a=explode("'",$enreg[0]);
 					$key_tmp=$a[1];
 					if($key_tmp== $param)
 					{
 						$val=$enreg[1];
 					}
-				}
-			}
-		}
-
-		return $val;
+				}
+			}
+		}
+
+		return $val;
 	}
 	else
-	{
-		error_log('Config array could not be found in get_config_param()',0);
-		return null;
-	}
-}
-
-/**
- * Get the config param from the database. If not found, return null
- * @param	string	DB Host
- * @param	string	DB login
- * @param	string	DB pass
- * @param	string	DB name
- * @param	string 	Name of param we want
- * @return	mixed	The parameter value or null if not found
- */
-function get_config_param_from_db($host,$login,$pass,$db_name,$param='')
-{
-	$mydb = mysql_connect($host,$login,$pass);
-
-	// The Dokeos system has not been designed to use special SQL modes that were introduced since MySQL 5
-	@mysql_query("set session sql_mode='';");
-
-	$myconnect = mysql_select_db($db_name);
-	$sql = "SELECT * FROM settings_current WHERE variable = '$param'";
-	$res = mysql_query($sql);
-	if($res===false){return null;}
-	if(mysql_num_rows($res)>0)
-	{
-		$row = mysql_fetch_array($res);
-		$value = $row['selected_value'];
-		return $value;
-	}
-	return null;
-}
-
-/**
-*	Return a list of language directories.
-*	@todo function does not belong here, move to code library,
-*	also see infocours.php which contains similar function
-*/
-function get_language_folder_list($dirname)
-{
-	if ($dirname[strlen($dirname)-1] != '/') $dirname .= '/';
-	$handle = opendir($dirname);
-	$language_list = array();
-
-	while ($entries = readdir($handle))
-	{
-		if ($entries=='.' || $entries=='..' || $entries=='CVS'  || $entries == '.svn') continue;
-		if (is_dir($dirname.$entries))
-		{
-			$language_list[] = $entries;
-		}
-	}
-
-	closedir($handle);
-
-	return $language_list;
-}
-
-/*
-==============================================================================
-		DISPLAY FUNCTIONS
-==============================================================================
-*/
-
-
-/**
-*	Displays a form (drop down menu) so the user can select
-*	his/her preferred language.
-*/
-function display_language_selection_box()
-{
-	//get language list
-	$dirname = '../lang/';
-	$language_list = get_language_folder_list($dirname);
-	sort($language_list);
-	//Reduce the number of languages shown to only show those with higher than 90% translation in DLTT
-	//This option can be easily removed later on. The aim is to test people response to less choice
-	//$language_to_display = $language_list;
-	$language_to_display = array('asturian','english','italian','french','slovenian','slovenian_unicode','spanish');
-
-	//display
-	echo "\t\t<select name=\"language_list\">\n";
-
-	$default_language = 'english';
-	foreach ($language_to_display as $key => $value)
-	{
-		if ($value == $default_language) $option_end = ' selected="selected">';
-		else $option_end = '>';
-		echo "\t\t\t<option value=\"$value\"$option_end";
-
-		echo api_ucfirst($value);
-		echo "</option>\n";
-	}
-
-	echo "\t\t</select>\n";
-}
-
-/**
- * This function displays a language dropdown box so that the installatioin
- * can be done in the language of the user
- */
-function display_language_selection()
-{ ?>
-	<h1><?php get_lang('WelcomeToTheDokeosInstaller');?></h1>
-	<h2><?php echo display_step_sequence(); ?><?php echo get_lang('InstallationLanguage');?></h2>
-	<p><?php echo get_lang('PleaseSelectInstallationProcessLanguage');?>:</p>
-	<form id="lang_form" method="post" action="<?php echo api_get_self(); ?>">
-<?php display_language_selection_box(); ?>
-	<button type="submit" name="step1" class="next" value="<?php get_lang('Next');?> &gt;"><?php echo get_lang('Next');?></button>
-	<input type="hidden" name="is_executable" id="is_executable" value="-" />
-	</form>
-<?php }
-
-/**
- * This function displays the requirements for installing Dokeos.
- *
- * @param string $installType
- * @param boolean $badUpdatePath
- * @param string The updatePath given (if given)
- * @param array $update_from_version_8 The different subversions from version 1.8
- * @param array	$update_from_version_6 The different subversions from version 1.6
- *
- * @author unknow
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-*/
-function display_requirements($installType, $badUpdatePath, $updatePath='', $update_from_version_8=array(), $update_from_version_6=array())
-{
-	echo '<h2>'.display_step_sequence().get_lang('Requirements')."</h2>\n";
-
-	echo '<strong>'.get_lang('ReadThoroughly').'</strong><br />';
-	echo get_lang('MoreDetails').' <a href="../../documentation/installation_guide.html" target="_blank">'.get_lang('ReadTheInstallGuide').'</a>.<br />'."\n";
-
-	//	SERVER REQUIREMENTS
-	echo '<div class="RequirementHeading"><h1>'.get_lang('ServerRequirements').'</h1>';
-	echo '<div class="RequirementText">'.get_lang('ServerRequirementsInfo').'</div>';
-	echo '<div class="RequirementContent">';
-	echo '<table class="requirements">
-			<tr>
-				<td class="requirements-item">'.get_lang('PHPVersion').'>= 5.0</td>
-				<td class="requirements-value">';
-					if (phpversion() < '5.0')
-					{
-						echo '<strong><font color="red">'.get_lang('PHPVersionError').'</font></strong>';
-					}
-					else
-					{
-						echo '<strong><font color="green">'.get_lang('PHPVersionOK'). ' '.phpversion().'</font></strong>';
-					}
-	echo '		</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.session.php" target="_blank">Session</a> '.get_lang('support').'</td>
-				<td class="requirements-value">'.check_extension('session', get_lang('Yes'), get_lang('ExtensionSessionsNotAvailable')).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.mysql.php" target="_blank">MySQL</a> '.get_lang('support').'</td>
-				<td class="requirements-value">'.check_extension('mysql', get_lang('Yes'), get_lang('ExtensionMySQLNotAvailable')).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.zlib.php" target="_blank">Zlib</a> '.get_lang('support').'</td>
-				<td class="requirements-value">'.check_extension('zlib', get_lang('Yes'), get_lang('ExtensionZlibNotAvailable')).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.pcre.php" target="_blank">Perl-compatible regular expressions</a> '.get_lang('support').'</td>
-				<td class="requirements-value">'.check_extension('pcre', get_lang('Yes'), get_lang('ExtensionPCRENotAvailable')).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.xml.php" target="_blank">XML</a> '.get_lang('support').'</td>
-				<td class="requirements-value">'.check_extension('xml', get_lang('Yes'), get_lang('No')).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.mbstring.php" target="_blank">Multibyte string</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-				<td class="requirements-value">'.check_extension('mbstring', get_lang('Yes'), get_lang('ExtensionMBStringNotAvailable'), true).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.iconv.php" target="_blank">Iconv</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-				<td class="requirements-value">'.check_extension('iconv', get_lang('Yes'), get_lang('No'), true).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.intl.php" target="_blank">Internationalization</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-				<td class="requirements-value">'.check_extension('intl', get_lang('Yes'), get_lang('No'), true).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.image.php" target="_blank">GD</a> '.get_lang('support').'</td>
-				<td class="requirements-value">'.check_extension('gd', get_lang('Yes'), get_lang('ExtensionGDNotAvailable')).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.json.php" target="_blank">JSON</a> '.get_lang('support').'</td>
-				<td class="requirements-value">'.check_extension('json', get_lang('Yes'), get_lang('No')).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/en/book.ldap.php" target="_blank">LDAP</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-				<td class="requirements-value">'.check_extension('ldap', get_lang('Yes'), get_lang('ExtensionLDAPNotAvailable'), true).'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://xapian.org/" target="_blank">Xapian</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
-				<td class="requirements-value">'.check_extension('xapian', get_lang('Yes'), get_lang('No'), true).'</td>
-			</tr>
-
-		  </table>';
-	echo '	</div>';
-	echo '</div>';
-
-	// RECOMMENDED SETTINGS
-	// Note: these are the settings for Joomla, does this also apply for Dokeos?
-	// Note: also add upload_max_filesize here so that large uploads are possible
-	echo '<div class="RequirementHeading"><h1>'.get_lang('RecommendedSettings').'</h1>';
-	echo '<div class="RequirementText">'.get_lang('RecommendedSettingsInfo').'</div>';
-	echo '<div class="RequirementContent">';
-	echo '<table class="requirements">
-			<tr>
-				<th>'.get_lang('Setting').'</th>
-				<th>'.get_lang('Recommended').'</th>
-				<th>'.get_lang('Actual').'</th>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/features.safe-mode.php">Safe Mode</a></td>
-				<td class="requirements-recommended">OFF</td>
-				<td class="requirements-value">'.check_php_setting('safe_mode','OFF').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/ref.errorfunc.php#ini.display-errors">Display Errors</a></td>
-				<td class="requirements-recommended">OFF</td>
-				<td class="requirements-value">'.check_php_setting('display_errors','OFF').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.file-uploads">File Uploads</a></td>
-				<td class="requirements-recommended">ON</td>
-				<td class="requirements-value">'.check_php_setting('file_uploads','ON').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-gpc">Magic Quotes GPC</a></td>
-				<td class="requirements-recommended">OFF</td>
-				<td class="requirements-value">'.check_php_setting('magic_quotes_gpc','OFF').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-runtime">Magic Quotes Runtime</a></td>
-				<td class="requirements-recommended">OFF</td>
-				<td class="requirements-value">'.check_php_setting('magic_quotes_runtime','OFF').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/security.globals.php">Register Globals</a></td>
-				<td class="requirements-recommended">OFF</td>
-				<td class="requirements-value">'.check_php_setting('register_globals','OFF').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/ref.session.php#ini.session.auto-start">Session auto start</a></td>
-				<td class="requirements-recommended">OFF</td>
-				<td class="requirements-value">'.check_php_setting('session.auto_start','OFF').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.short-open-tag">Short Open Tag</a></td>
-				<td class="requirements-recommended">OFF</td>
-				<td class="requirements-value">'.check_php_setting('short_open_tag','OFF').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.upload-max-filesize">Maximum upload file size</a></td>
-				<td class="requirements-recommended">10M-100M</td>
-				<td class="requirements-value">'.ini_get('upload_max_filesize').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.post-max-size">Maximum post size</a></td>
-				<td class="requirements-recommended">10M-100M</td>
-				<td class="requirements-value">'.ini_get('post_max_size').'</td>
-			</tr>
-		  </table>';
-	echo '	</div>';
-	echo '</div>';
-
-	// DIRECTORY AND FILE PERMISSIONS
-	echo '<div class="RequirementHeading"><h1>'.get_lang('DirectoryAndFilePermissions').'</h1>';
-	echo '<div class="RequirementText">'.get_lang('DirectoryAndFilePermissionsInfo').'</div>';
-	echo '<div class="RequirementContent">';
-	echo '<table class="requirements">
-			<tr>
-				<td class="requirements-item">dokeos/main/inc/conf/</td>
-				<td class="requirements-value">'.check_writable('inc/conf/').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item">dokeos/main/upload/users/</td>
-				<td class="requirements-value">'.check_writable('upload/users/').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item">dokeos/main/default_course_document/images/</td>
-				<td class="requirements-value">'.check_writable('default_course_document/images/').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item">dokeos/archive/</td>
-				<td class="requirements-value">'.check_writable('../archive/').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item">dokeos/courses/</td>
-				<td class="requirements-value">'.check_writable('../courses/').'</td>
-			</tr>
-			<tr>
-				<td class="requirements-item">dokeos/home/</td>
-				<td class="requirements-value">'.check_writable('../home/').'</td>
-			</tr>'.
-            //'<tr>
-            //    <td class="requirements-item">dokeos/searchdb/</td>
-            //    <td class="requirements-value">'.check_writable('../searchdb/').'</td>
-            //</tr>'.
-            //'<tr>
-            //    <td class="requirements-item">'.session_save_path().'</td>
+	{
+		error_log('Config array could not be found in get_config_param()',0);
+		return null;
+	}
+}
+
+/**
+ * Get the config param from the database. If not found, return null
+ * @param	string	DB Host
+ * @param	string	DB login
+ * @param	string	DB pass
+ * @param	string	DB name
+ * @param	string 	Name of param we want
+ * @return	mixed	The parameter value or null if not found
+ */
+function get_config_param_from_db($host,$login,$pass,$db_name,$param='')
+{
+	$mydb = mysql_connect($host,$login,$pass);
+
+	// The Dokeos system has not been designed to use special SQL modes that were introduced since MySQL 5
+	@mysql_query("set session sql_mode='';");
+
+	$myconnect = mysql_select_db($db_name);
+	$sql = "SELECT * FROM settings_current WHERE variable = '$param'";
+	$res = mysql_query($sql);
+	if($res===false){return null;}
+	if(mysql_num_rows($res)>0)
+	{
+		$row = mysql_fetch_array($res);
+		$value = $row['selected_value'];
+		return $value;
+	}
+	return null;
+}
+
+/**
+*	Return a list of language directories.
+*	@todo function does not belong here, move to code library,
+*	also see infocours.php which contains similar function
+*/
+function get_language_folder_list($dirname)
+{
+	if ($dirname[strlen($dirname)-1] != '/') $dirname .= '/';
+	$handle = opendir($dirname);
+	$language_list = array();
+
+	while ($entries = readdir($handle))
+	{
+		if ($entries=='.' || $entries=='..' || $entries=='CVS'  || $entries == '.svn') continue;
+		if (is_dir($dirname.$entries))
+		{
+			$language_list[] = $entries;
+		}
+	}
+
+	closedir($handle);
+
+	return $language_list;
+}
+
+/*
+==============================================================================
+		DISPLAY FUNCTIONS
+==============================================================================
+*/
+
+
+/**
+*	Displays a form (drop down menu) so the user can select
+*	his/her preferred language.
+*/
+function display_language_selection_box()
+{
+	//get language list
+	$dirname = '../lang/';
+	$language_list = get_language_folder_list($dirname);
+	sort($language_list);
+	//Reduce the number of languages shown to only show those with higher than 90% translation in DLTT
+	//This option can be easily removed later on. The aim is to test people response to less choice
+	//$language_to_display = $language_list;
+	$language_to_display = array('asturian','english','italian','french','slovenian','slovenian_unicode','spanish');
+
+	//display
+	echo "\t\t<select name=\"language_list\">\n";
+
+	$default_language = 'english';
+	foreach ($language_to_display as $key => $value)
+	{
+		if ($value == $default_language) $option_end = ' selected="selected">';
+		else $option_end = '>';
+		echo "\t\t\t<option value=\"$value\"$option_end";
+
+		echo api_ucfirst($value);
+		echo "</option>\n";
+	}
+
+	echo "\t\t</select>\n";
+}
+
+/**
+ * This function displays a language dropdown box so that the installatioin
+ * can be done in the language of the user
+ */
+function display_language_selection()
+{ ?>
+	<h1><?php get_lang('WelcomeToTheDokeosInstaller');?></h1>
+	<h2><?php echo display_step_sequence(); ?><?php echo get_lang('InstallationLanguage');?></h2>
+	<p><?php echo get_lang('PleaseSelectInstallationProcessLanguage');?>:</p>
+	<form id="lang_form" method="post" action="<?php echo api_get_self(); ?>">
+<?php display_language_selection_box(); ?>
+	<button type="submit" name="step1" class="next" value="<?php get_lang('Next');?> &gt;"><?php echo get_lang('Next');?></button>
+	<input type="hidden" name="is_executable" id="is_executable" value="-" />
+	</form>
+<?php }
+
+/**
+ * This function displays the requirements for installing Dokeos.
+ *
+ * @param string $installType
+ * @param boolean $badUpdatePath
+ * @param string The updatePath given (if given)
+ * @param array $update_from_version_8 The different subversions from version 1.8
+ * @param array	$update_from_version_6 The different subversions from version 1.6
+ *
+ * @author unknow
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+*/
+function display_requirements($installType, $badUpdatePath, $updatePath='', $update_from_version_8=array(), $update_from_version_6=array())
+{
+	echo '<h2>'.display_step_sequence().get_lang('Requirements')."</h2>\n";
+
+	echo '<strong>'.get_lang('ReadThoroughly').'</strong><br />';
+	echo get_lang('MoreDetails').' <a href="../../documentation/installation_guide.html" target="_blank">'.get_lang('ReadTheInstallGuide').'</a>.<br />'."\n";
+
+	//	SERVER REQUIREMENTS
+	echo '<div class="RequirementHeading"><h1>'.get_lang('ServerRequirements').'</h1>';
+	echo '<div class="RequirementText">'.get_lang('ServerRequirementsInfo').'</div>';
+	echo '<div class="RequirementContent">';
+	echo '<table class="requirements">
+			<tr>
+				<td class="requirements-item">'.get_lang('PHPVersion').'>= 5.0</td>
+				<td class="requirements-value">';
+					if (phpversion() < '5.0')
+					{
+						echo '<strong><font color="red">'.get_lang('PHPVersionError').'</font></strong>';
+					}
+					else
+					{
+						echo '<strong><font color="green">'.get_lang('PHPVersionOK'). ' '.phpversion().'</font></strong>';
+					}
+	echo '		</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.session.php" target="_blank">Session</a> '.get_lang('support').'</td>
+				<td class="requirements-value">'.check_extension('session', get_lang('Yes'), get_lang('ExtensionSessionsNotAvailable')).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.mysql.php" target="_blank">MySQL</a> '.get_lang('support').'</td>
+				<td class="requirements-value">'.check_extension('mysql', get_lang('Yes'), get_lang('ExtensionMySQLNotAvailable')).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.zlib.php" target="_blank">Zlib</a> '.get_lang('support').'</td>
+				<td class="requirements-value">'.check_extension('zlib', get_lang('Yes'), get_lang('ExtensionZlibNotAvailable')).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.pcre.php" target="_blank">Perl-compatible regular expressions</a> '.get_lang('support').'</td>
+				<td class="requirements-value">'.check_extension('pcre', get_lang('Yes'), get_lang('ExtensionPCRENotAvailable')).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.xml.php" target="_blank">XML</a> '.get_lang('support').'</td>
+				<td class="requirements-value">'.check_extension('xml', get_lang('Yes'), get_lang('No')).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.mbstring.php" target="_blank">Multibyte string</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
+				<td class="requirements-value">'.check_extension('mbstring', get_lang('Yes'), get_lang('ExtensionMBStringNotAvailable'), true).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.iconv.php" target="_blank">Iconv</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
+				<td class="requirements-value">'.check_extension('iconv', get_lang('Yes'), get_lang('No'), true).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.intl.php" target="_blank">Internationalization</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
+				<td class="requirements-value">'.check_extension('intl', get_lang('Yes'), get_lang('No'), true).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.image.php" target="_blank">GD</a> '.get_lang('support').'</td>
+				<td class="requirements-value">'.check_extension('gd', get_lang('Yes'), get_lang('ExtensionGDNotAvailable')).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.json.php" target="_blank">JSON</a> '.get_lang('support').'</td>
+				<td class="requirements-value">'.check_extension('json', get_lang('Yes'), get_lang('No')).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/en/book.ldap.php" target="_blank">LDAP</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
+				<td class="requirements-value">'.check_extension('ldap', get_lang('Yes'), get_lang('ExtensionLDAPNotAvailable'), true).'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://xapian.org/" target="_blank">Xapian</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
+				<td class="requirements-value">'.check_extension('xapian', get_lang('Yes'), get_lang('No'), true).'</td>
+			</tr>
+
+		  </table>';
+	echo '	</div>';
+	echo '</div>';
+
+	// RECOMMENDED SETTINGS
+	// Note: these are the settings for Joomla, does this also apply for Dokeos?
+	// Note: also add upload_max_filesize here so that large uploads are possible
+	echo '<div class="RequirementHeading"><h1>'.get_lang('RecommendedSettings').'</h1>';
+	echo '<div class="RequirementText">'.get_lang('RecommendedSettingsInfo').'</div>';
+	echo '<div class="RequirementContent">';
+	echo '<table class="requirements">
+			<tr>
+				<th>'.get_lang('Setting').'</th>
+				<th>'.get_lang('Recommended').'</th>
+				<th>'.get_lang('Actual').'</th>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/features.safe-mode.php">Safe Mode</a></td>
+				<td class="requirements-recommended">OFF</td>
+				<td class="requirements-value">'.check_php_setting('safe_mode','OFF').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/ref.errorfunc.php#ini.display-errors">Display Errors</a></td>
+				<td class="requirements-recommended">OFF</td>
+				<td class="requirements-value">'.check_php_setting('display_errors','OFF').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.file-uploads">File Uploads</a></td>
+				<td class="requirements-recommended">ON</td>
+				<td class="requirements-value">'.check_php_setting('file_uploads','ON').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-gpc">Magic Quotes GPC</a></td>
+				<td class="requirements-recommended">OFF</td>
+				<td class="requirements-value">'.check_php_setting('magic_quotes_gpc','OFF').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-runtime">Magic Quotes Runtime</a></td>
+				<td class="requirements-recommended">OFF</td>
+				<td class="requirements-value">'.check_php_setting('magic_quotes_runtime','OFF').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/security.globals.php">Register Globals</a></td>
+				<td class="requirements-recommended">OFF</td>
+				<td class="requirements-value">'.check_php_setting('register_globals','OFF').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/ref.session.php#ini.session.auto-start">Session auto start</a></td>
+				<td class="requirements-recommended">OFF</td>
+				<td class="requirements-value">'.check_php_setting('session.auto_start','OFF').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.short-open-tag">Short Open Tag</a></td>
+				<td class="requirements-recommended">OFF</td>
+				<td class="requirements-value">'.check_php_setting('short_open_tag','OFF').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.upload-max-filesize">Maximum upload file size</a></td>
+				<td class="requirements-recommended">10M-100M</td>
+				<td class="requirements-value">'.ini_get('upload_max_filesize').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.post-max-size">Maximum post size</a></td>
+				<td class="requirements-recommended">10M-100M</td>
+				<td class="requirements-value">'.ini_get('post_max_size').'</td>
+			</tr>
+		  </table>';
+	echo '	</div>';
+	echo '</div>';
+
+	// DIRECTORY AND FILE PERMISSIONS
+	echo '<div class="RequirementHeading"><h1>'.get_lang('DirectoryAndFilePermissions').'</h1>';
+	echo '<div class="RequirementText">'.get_lang('DirectoryAndFilePermissionsInfo').'</div>';
+	echo '<div class="RequirementContent">';
+	echo '<table class="requirements">
+			<tr>
+				<td class="requirements-item">dokeos/main/inc/conf/</td>
+				<td class="requirements-value">'.check_writable('inc/conf/').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item">dokeos/main/upload/users/</td>
+				<td class="requirements-value">'.check_writable('upload/users/').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item">dokeos/main/default_course_document/images/</td>
+				<td class="requirements-value">'.check_writable('default_course_document/images/').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item">dokeos/archive/</td>
+				<td class="requirements-value">'.check_writable('../archive/').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item">dokeos/courses/</td>
+				<td class="requirements-value">'.check_writable('../courses/').'</td>
+			</tr>
+			<tr>
+				<td class="requirements-item">dokeos/home/</td>
+				<td class="requirements-value">'.check_writable('../home/').'</td>
+			</tr>'.
+            //'<tr>
+            //    <td class="requirements-item">dokeos/searchdb/</td>
+            //    <td class="requirements-value">'.check_writable('../searchdb/').'</td>
+            //</tr>'.
+            //'<tr>
+            //    <td class="requirements-item">'.session_save_path().'</td>
             //    <td class="requirements-value">'.(is_writable(session_save_path())
-			//		? '<strong><font color="green">'.get_lang('Writable').'</font></strong>'
-			//		: '<strong><font color="red">'.get_lang('NotWritable').'</font></strong>').'</td>
-            //</tr>'.
-            '';
-	echo '    </table>';
-	echo '	</div>';
-	echo '</div>';
-
-	if($installType == 'update' && (empty($updatePath) || $badUpdatePath))
-	{
-		if($badUpdatePath)
-		{ ?>
-			<div style="color:red; background-color:white; font-weight:bold; text-align:center;">
-				<?php echo get_lang('Error');?>!<br />
-				Dokeos <?php echo (isset($_POST['step2_update_6'])?implode('|',$update_from_version_6):implode('|',$update_from_version_8)).' '.get_lang('HasNotBeenFoundInThatDir'); ?>.
-			</div>
-		<?php }
-		else
-		{
-			echo '<br />';
-		}
-		?>
-			<table border="0" cellpadding="5" align="center">
-			<tr>
-			<td><?php echo get_lang('OldVersionRootPath');?>:</td>
-			<td><input type="text" name="updatePath" size="50" value="<?php echo ($badUpdatePath && !empty($updatePath))?htmlentities($updatePath):$_SERVER['DOCUMENT_ROOT'].'/old_version/'; ?>" /></td>
-			</tr>
-			<tr>
-			<td colspan="2" align="center">
-				<button type="submit" class="back" name="step1" value="&lt; <?php echo get_lang('Back');?>" ><?php echo get_lang('Back');?></button>
+			//		? '<strong><font color="green">'.get_lang('Writable').'</font></strong>'
+			//		: '<strong><font color="red">'.get_lang('NotWritable').'</font></strong>').'</td>
+            //</tr>'.
+            '';
+	echo '    </table>';
+	echo '	</div>';
+	echo '</div>';
+
+	if($installType == 'update' && (empty($updatePath) || $badUpdatePath))
+	{
+		if($badUpdatePath)
+		{ ?>
+			<div style="color:red; background-color:white; font-weight:bold; text-align:center;">
+				<?php echo get_lang('Error');?>!<br />
+				Dokeos <?php echo (isset($_POST['step2_update_6'])?implode('|',$update_from_version_6):implode('|',$update_from_version_8)).' '.get_lang('HasNotBeenFoundInThatDir'); ?>.
+			</div>
+		<?php }
+		else
+		{
+			echo '<br />';
+		}
+		?>
+			<table border="0" cellpadding="5" align="center">
+			<tr>
+			<td><?php echo get_lang('OldVersionRootPath');?>:</td>
+			<td><input type="text" name="updatePath" size="50" value="<?php echo ($badUpdatePath && !empty($updatePath))?htmlentities($updatePath):$_SERVER['DOCUMENT_ROOT'].'/old_version/'; ?>" /></td>
+			</tr>
+			<tr>
+			<td colspan="2" align="center">
+				<button type="submit" class="back" name="step1" value="&lt; <?php echo get_lang('Back');?>" ><?php echo get_lang('Back');?></button>
 				<input type="hidden" name="is_executable" id="is_executable" value="-" />
-				<button type="submit" class="next" name="<?php echo (isset($_POST['step2_update_6'])?'step2_update_6':'step2_update_8');?>" value="<?php echo get_lang('Next');?> &gt;" ><?php echo get_lang('Next');?></button>
-			</td>
-			</tr>
-			</table>
-		<?php
-	}
-	else
-	{
-		$error=false;
-
-		$perm = api_get_setting('permissions_for_new_directories');
-		$perm = octdec(!empty($perm)?$perm:'0770');
-		$perm_file = api_get_setting('permissions_for_new_files');
-		$perm_file = octdec(!empty($perm_file)?$perm_file:'0660');
-
-		//First, attempt to set writing permissions if we don't have them yet
-		//0xxx is an octal number, this is the required format
-		$notwritable = array();
-        $curdir = getcwd();
-		if(!is_writable('../inc/conf'))
-		{
-			$notwritable[] = realpath($curdir.'/../inc/conf');
-			@chmod('../inc/conf',$perm);
-		}
-
-		if(!is_writable('../upload/users'))
-		{
-			$notwritable[] = realpath($curdir.'/../upload/users');
-			@chmod('../upload/users', $perm);
-		}
-
-        if(!is_writable('../default_course_document/images/'))
-        {
-            $notwritable[] = realpath($curdir.'/../default_course_document/images/');
-            @chmod('../default_course_document/images/', $perm);
-        }
-
-		if(!is_writable('../../archive'))
-		{
-			$notwritable[] = realpath($curdir.'/../../archive');
-			@chmod('../../archive',$perm);
-		}
-
-		if(!is_writable('../../courses'))
-		{
-			$notwritable[] = realpath($curdir.'/../../courses');
-			@chmod('../../courses',$perm);
-		}
-
-		if(!is_writable('../../home'))
-		{
-			$notwritable[] = realpath($curdir.'/../../home');
-			@chmod('../../home',$perm);
-		}
-
-		if(file_exists('../inc/conf/configuration.php') && !is_writable('../inc/conf/configuration.php'))
-		{
-			$notwritable[]= realpath($curdir.'/../inc/conf/configuration.php');
-			@chmod('../inc/conf/configuration.php',$perm_file);
-		}
-
-		//Second, if this fails, report an error
-		//--> the user will have to adjust the permissions manually
-		if(count($notwritable)>0)
-		{
-			$error=true;
-			echo '<div style="color:red; background-color:white; font-weight:bold; text-align:center;">';
-			echo get_lang('Warning').':<br />';
-			printf(get_lang('NoWritePermissionPleaseReadInstallGuide'),'</font><a href="../../documentation/installation_guide.html" target="blank">','</a> <font color="red">');
-			echo '<ul>';
-			foreach ($notwritable as $value)
-			{
-				echo '<li>'.$value.'</li>';
-			}
-			echo '</ul>';
+				<button type="submit" class="next" name="<?php echo (isset($_POST['step2_update_6'])?'step2_update_6':'step2_update_8');?>" value="<?php echo get_lang('Next');?> &gt;" ><?php echo get_lang('Next');?></button>
+			</td>
+			</tr>
+			</table>
+		<?php
+	}
+	else
+	{
+		$error=false;
+
+		$perm = api_get_setting('permissions_for_new_directories');
+		$perm = octdec(!empty($perm)?$perm:'0770');
+		$perm_file = api_get_setting('permissions_for_new_files');
+		$perm_file = octdec(!empty($perm_file)?$perm_file:'0660');
+
+		//First, attempt to set writing permissions if we don't have them yet
+		//0xxx is an octal number, this is the required format
+		$notwritable = array();
+        $curdir = getcwd();
+		if(!is_writable('../inc/conf'))
+		{
+			$notwritable[] = realpath($curdir.'/../inc/conf');
+			@chmod('../inc/conf',$perm);
+		}
+
+		if(!is_writable('../upload/users'))
+		{
+			$notwritable[] = realpath($curdir.'/../upload/users');
+			@chmod('../upload/users', $perm);
+		}
+
+        if(!is_writable('../default_course_document/images/'))
+        {
+            $notwritable[] = realpath($curdir.'/../default_course_document/images/');
+            @chmod('../default_course_document/images/', $perm);
+        }
+
+		if(!is_writable('../../archive'))
+		{
+			$notwritable[] = realpath($curdir.'/../../archive');
+			@chmod('../../archive',$perm);
+		}
+
+		if(!is_writable('../../courses'))
+		{
+			$notwritable[] = realpath($curdir.'/../../courses');
+			@chmod('../../courses',$perm);
+		}
+
+		if(!is_writable('../../home'))
+		{
+			$notwritable[] = realpath($curdir.'/../../home');
+			@chmod('../../home',$perm);
+		}
+
+		if(file_exists('../inc/conf/configuration.php') && !is_writable('../inc/conf/configuration.php'))
+		{
+			$notwritable[]= realpath($curdir.'/../inc/conf/configuration.php');
+			@chmod('../inc/conf/configuration.php',$perm_file);
+		}
+
+		//Second, if this fails, report an error
+		//--> the user will have to adjust the permissions manually
+		if(count($notwritable)>0)
+		{
+			$error=true;
+			echo '<div style="color:red; background-color:white; font-weight:bold; text-align:center;">';
+			echo get_lang('Warning').':<br />';
+			printf(get_lang('NoWritePermissionPleaseReadInstallGuide'),'</font><a href="../../documentation/installation_guide.html" target="blank">','</a> <font color="red">');
+			echo '<ul>';
+			foreach ($notwritable as $value)
+			{
+				echo '<li>'.$value.'</li>';
+			}
+			echo '</ul>';
 			echo '</div>';
-		}
-		// check wether a Dokeos configuration file already exists.
-		elseif(file_exists('../inc/conf/configuration.php'))
-		{
-				echo '<div style="color:red; background-color:white; font-weight:bold; text-align:center;">';
-				echo get_lang('WarningExistingDokeosInstallationDetected');
-				echo '</div>';
-		}
-		//and now display the choice buttons (go back or install)
-		?>
-		<p align="center">
-		<button type="submit" name="step1" class="back" onclick="window.location='index.php';return false;" value="&lt; <?php echo get_lang('Previous'); ?>" ><?php echo get_lang('Previous'); ?></button>
-		<button type="submit" name="step2_install" class="add" value="<?php echo get_lang("NewInstallation"); ?>" <?php if($error) if($error)echo 'disabled="disabled"'; ?> ><?php echo get_lang('NewInstallation'); ?></button>
-		<input type="hidden" name="is_executable" id="is_executable" value="-" />
-		<?php
-		//real code
-		echo '<button type="submit" class="save" name="step2_update_8" value="Upgrade from Dokeos 1.8.x"';
-		if($error) echo ' disabled="disabled"';
-		//temporary code for alpha version, disabling upgrade
-		//echo '<input type="submit" name="step2_update" value="Upgrading is not possible in this beta version"';
-		//echo ' disabled="disabled"';
-		//end temp code
-		echo ' >'.get_lang('UpgradeFromDokeos18x').'</button>';
-		echo '<button type="submit" class="save" name="step2_update_6" value="Upgrade from Dokeos 1.6.x"';
-		if($error) echo ' disabled="disabled"';
-		echo ' >'.get_lang('UpgradeFromDokeos16x').'</button>';
-		echo '</p>';
-	}
-}
-
-/**
-* Displays the license (GNU GPL) as step 2, with
-* - an "I accept" button named step3 to proceed to step 3;
-* - a "Back" button named step1 to go back to the first step.
-*/
-function display_license_agreement()
-{
-	echo '<h2>'.display_step_sequence().get_lang('Licence').'</h2>';
-	echo '<p>'.get_lang('DokeosLicenseInfo').'</p>';
-	echo '<p><a href="../../documentation/license.html" target="_blank">'.get_lang('PrintVers').'</a></p>';
-	?>
-	<table><tr><td>
-		<p><textarea cols="75" rows="15" ><?php htmlentities(include('../../documentation/license.txt')); ?></textarea></p>
-		</td>
-		</tr>
-		<tr>
-		<td>
-		<p><?php echo get_lang('DokeosArtLicense');?></p>
-		</td>
-		</tr>
-		<td>
-		<table width="100%">
-			<tr>
-				<td></td>
-				<td align="center">
-					<button type="submit" class="back" name="step1" value="&lt; <?php echo get_lang('Previous'); ?>" ><?php echo get_lang('Previous'); ?></button>
-					<input type="hidden" name="is_executable" id="is_executable" value="-" />
-					<button type="submit" class="next" name="step3" value="<?php echo get_lang('IAccept'); ?> &gt;" ><?php echo get_lang('IAccept'); ?></button>
-				</td>
-			</tr>
-		</table>
-	</td></tr></table>
-	<?php
-}
-
-/**
-* Displays a parameter in a table row.
-* Used by the display_database_settings_form function.
-* @param	string	Type of install
-* @param	string	Name of parameter
-* @param	string	Field name (in the HTML form)
-* @param	string	Field value
-* @param	string	Extra notice (to show on the right side)
-* @param	boolean	Whether to display in update mode
-* @param	string	Additional attribute for the <tr> element
+		}
+		// check wether a Dokeos configuration file already exists.
+		elseif(file_exists('../inc/conf/configuration.php'))
+		{
+				echo '<div style="color:red; background-color:white; font-weight:bold; text-align:center;">';
+				echo get_lang('WarningExistingDokeosInstallationDetected');
+				echo '</div>';
+		}
+		//and now display the choice buttons (go back or install)
+		?>
+		<p align="center">
+		<button type="submit" name="step1" class="back" onclick="window.location='index.php';return false;" value="&lt; <?php echo get_lang('Previous'); ?>" ><?php echo get_lang('Previous'); ?></button>
+		<button type="submit" name="step2_install" class="add" value="<?php echo get_lang("NewInstallation"); ?>" <?php if($error) if($error)echo 'disabled="disabled"'; ?> ><?php echo get_lang('NewInstallation'); ?></button>
+		<input type="hidden" name="is_executable" id="is_executable" value="-" />
+		<?php
+		//real code
+		echo '<button type="submit" class="save" name="step2_update_8" value="Upgrade from Dokeos 1.8.x"';
+		if($error) echo ' disabled="disabled"';
+		//temporary code for alpha version, disabling upgrade
+		//echo '<input type="submit" name="step2_update" value="Upgrading is not possible in this beta version"';
+		//echo ' disabled="disabled"';
+		//end temp code
+		echo ' >'.get_lang('UpgradeFromDokeos18x').'</button>';
+		echo '<button type="submit" class="save" name="step2_update_6" value="Upgrade from Dokeos 1.6.x"';
+		if($error) echo ' disabled="disabled"';
+		echo ' >'.get_lang('UpgradeFromDokeos16x').'</button>';
+		echo '</p>';
+	}
+}
+
+/**
+* Displays the license (GNU GPL) as step 2, with
+* - an "I accept" button named step3 to proceed to step 3;
+* - a "Back" button named step1 to go back to the first step.
+*/
+function display_license_agreement()
+{
+	echo '<h2>'.display_step_sequence().get_lang('Licence').'</h2>';
+	echo '<p>'.get_lang('DokeosLicenseInfo').'</p>';
+	echo '<p><a href="../../documentation/license.html" target="_blank">'.get_lang('PrintVers').'</a></p>';
+	?>
+	<table><tr><td>
+		<p><textarea cols="75" rows="15" ><?php htmlentities(include('../../documentation/license.txt')); ?></textarea></p>
+		</td>
+		</tr>
+		<tr>
+		<td>
+		<p><?php echo get_lang('DokeosArtLicense');?></p>
+		</td>
+		</tr>
+		<td>
+		<table width="100%">
+			<tr>
+				<td></td>
+				<td align="center">
+					<button type="submit" class="back" name="step1" value="&lt; <?php echo get_lang('Previous'); ?>" ><?php echo get_lang('Previous'); ?></button>
+					<input type="hidden" name="is_executable" id="is_executable" value="-" />
+					<button type="submit" class="next" name="step3" value="<?php echo get_lang('IAccept'); ?> &gt;" ><?php echo get_lang('IAccept'); ?></button>
+				</td>
+			</tr>
+		</table>
+	</td></tr></table>
+	<?php
+}
+
+/**
+* Displays a parameter in a table row.
+* Used by the display_database_settings_form function.
+* @param	string	Type of install
+* @param	string	Name of parameter
+* @param	string	Field name (in the HTML form)
+* @param	string	Field value
+* @param	string	Extra notice (to show on the right side)
+* @param	boolean	Whether to display in update mode
+* @param	string	Additional attribute for the <tr> element
 * @return	void	Direct output
-*/
-function display_database_parameter($install_type, $parameter_name, $form_field_name, $parameter_value, $extra_notice, $display_when_update = true, $tr_attribute='')
-{
-	echo "<tr ".$tr_attribute.">\n";
-	echo "<td>$parameter_name&nbsp;&nbsp;</td>\n";
-	if ($install_type == INSTALL_TYPE_UPDATE && $display_when_update)
-	{
-		echo '<td><input type="hidden" name="'.$form_field_name.'" id="'.$form_field_name.'" value="'.htmlentities($parameter_value).'" />'.$parameter_value."</td>\n";
-	}
-	else
-	{
+*/
+function display_database_parameter($install_type, $parameter_name, $form_field_name, $parameter_value, $extra_notice, $display_when_update = true, $tr_attribute='')
+{
+	echo "<tr ".$tr_attribute.">\n";
+	echo "<td>$parameter_name&nbsp;&nbsp;</td>\n";
+	if ($install_type == INSTALL_TYPE_UPDATE && $display_when_update)
+	{
+		echo '<td><input type="hidden" name="'.$form_field_name.'" id="'.$form_field_name.'" value="'.htmlentities($parameter_value).'" />'.$parameter_value."</td>\n";
+	}
+	else
+	{
 		if ($form_field_name=='dbPassForm') {
-			$inputtype = 'password';
-		} else {
-			$inputtype = 'text';
-		}
+			$inputtype = 'password';
+		} else {
+			$inputtype = 'text';
+		}
 
-		//Slightly limit the length of the database prefix to avoid
-		//having to cut down the databases names later on
+		//Slightly limit the length of the database prefix to avoid
+		//having to cut down the databases names later on
 		if ($form_field_name=='dbPrefixForm') {
-			$maxlength = '15';
-		} else {
-			$maxlength = MAX_FORM_FIELD_LENGTH;
-		}
-
-		echo '<td><input type="'.$inputtype.'" size="'.DATABASE_FORM_FIELD_DISPLAY_LENGTH.'" maxlength="'.$maxlength.'" name="'.$form_field_name.'" id="'.$form_field_name.'" value="'.htmlentities($parameter_value).'" />'."</td>\n";
-		echo "<td>$extra_notice</td>\n";
-	}
-	echo "</tr>\n";
-}
-
-/**
- * Displays step 3 - a form where the user can enter the installation settings
- * regarding the databases - login and password, names, prefixes, single
- * or multiple databases, tracking or not...
- */
-function display_database_settings_form($installType, $dbHostForm, $dbUsernameForm, $dbPassForm, $dbPrefixForm, $enableTrackingForm, $singleDbForm, $dbNameForm, $dbStatsForm, $dbScormForm, $dbUserForm)
-{
-	if($installType == 'update')
-	{
-		global $_configuration, $update_from_version_6;
-		if(in_array($_POST['old_version'],$update_from_version_6))
-		{
-	        $dbHostForm=get_config_param('dbHost');
-            $dbUsernameForm=get_config_param('dbLogin');
-            $dbPassForm=get_config_param('dbPass');
-            $dbPrefixForm=get_config_param('dbNamePrefix');
-            $enableTrackingForm=get_config_param('is_trackingEnabled');
-            $singleDbForm=get_config_param('singleDbEnabled');
-            $dbNameForm=get_config_param('mainDbName');
-            $dbStatsForm=get_config_param('statsDbName');
-            $dbScormForm=get_config_param('scormDbName');
-            $dbUserForm=get_config_param('user_personal_database');
-            $dbScormExists=true;
-		}
-		else
-		{
-			$dbHostForm=$_configuration['db_host'];
-			$dbUsernameForm=$_configuration['db_user'];
-			$dbPassForm=$_configuration['db_password'];
-			$dbPrefixForm=$_configuration['db_prefix'];
-			$enableTrackingForm=$_configuration['tracking_enabled'];
-			$singleDbForm=$_configuration['single_database'];
-			$dbNameForm=$_configuration['main_database'];
-			$dbStatsForm=$_configuration['statistics_database'];
-			$dbScormForm=$_configuration['scorm_database'];
-			$dbUserForm=$_configuration['user_personal_database'];
-
-			$dbScormExists=true;
-		}
-
-		if(empty($dbScormForm))
-		{
-			if($singleDbForm)
-			{
-				$dbScormForm=$dbNameForm;
-			}
-			else
-			{
-				$dbScormForm=$dbPrefixForm.'scorm';
-
-				$dbScormExists=false;
-			}
-		}
-		if(empty($dbUserForm))
-		{
-			if($singleDbForm)
-			{
-				$dbUserForm=$dbNameForm;
-			}
-			else
-			{
-				$dbUserForm=$dbPrefixForm.'dokeos_user';
-			}
-		}
-		echo "<h2>" . display_step_sequence() .get_lang("DBSetting") . "</h2>";
-		echo get_lang("DBSettingUpgradeIntro");
-	}else{
-		if(empty($dbPrefixForm)) //make sure there is a default value for db prefix
-		{
-			$dbPrefixForm = 'dokeos_';
-		}
-		echo "<h2>" . display_step_sequence() .get_lang("DBSetting") . "</h2>";
-		echo get_lang("DBSettingIntro");
-	}
-
-	?>
-	<br /><br />
-	</td>
-	</tr>
-	<tr>
-	<td>
-	<table width="100%">
-	<tr>
-	  <td width="40%"><?php echo get_lang('DBHost'); ?> </td>
-
-	  <?php if($installType == 'update'): ?>
-	  <td width="30%"><input type="hidden" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /><?php echo $dbHostForm; ?></td>
-	  <td width="30%">&nbsp;</td>
-	  <?php else: ?>
-	  <td width="30%"><input type="text" size="25" maxlength="50" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /></td>
-	  <td width="30%"><?php echo get_lang('EG').' localhost'; ?></td>
-	  <?php endif; ?>
-
-	</tr>
-	<?php
-	//database user username
-	$example_login = get_lang('EG').' root';
-	display_database_parameter($installType, get_lang('DBLogin'), 'dbUsernameForm', $dbUsernameForm, $example_login);
-	//database user password
-	$example_password = get_lang('EG').' '.api_generate_password();
-	display_database_parameter($installType, get_lang('DBPassword'), 'dbPassForm', $dbPassForm, $example_password);
-	//database prefix
-	display_database_parameter($installType, get_lang('DbPrefixForm'), 'dbPrefixForm', $dbPrefixForm, get_lang('DbPrefixCom'));
-	//fields for the four standard Dokeos databases
-	echo '<tr><td colspan="3"><a href="" onclick="javascript: show_hide_option();return false;" id="optionalparameters"><img style="vertical-align:middle;" src="../img/div_show.gif" alt="show-hide" /> '.get_lang('OptionalParameters','').'</a></td></tr>';
-	display_database_parameter($installType, get_lang('MainDB'), 'dbNameForm', $dbNameForm, '&nbsp;',null,'id="optional_param1" style="display:none;"');
-	display_database_parameter($installType, get_lang('StatDB'), 'dbStatsForm', $dbStatsForm, '&nbsp;',null,'id="optional_param2" style="display:none;"');
-	if($installType == 'update' && in_array($_POST['old_version'],$update_from_version_6))
-	{
-		display_database_parameter($installType, get_lang('ScormDB'), 'dbScormForm', $dbScormForm, '&nbsp;',null,'id="optional_param3" style="display:none;"');
-	}
-	display_database_parameter($installType, get_lang('UserDB'), 'dbUserForm', $dbUserForm, '&nbsp;',null,'id="optional_param4" style="display:none;"');
-	?>
-	<tr id="optional_param5" style="display:none;">
-	  <td><?php echo get_lang('EnableTracking'); ?> </td>
-
-	  <?php if($installType == 'update'): ?>
-	  <td><input type="hidden" name="enableTrackingForm" value="<?php echo $enableTrackingForm; ?>" /><?php echo $enableTrackingForm? get_lang('Yes') : get_lang('No'); ?></td>
-	  <?php else: ?>
-	  <td>
-		<input class="checkbox" type="radio" name="enableTrackingForm" value="1" id="enableTracking1" <?php echo $enableTrackingForm?'checked="checked" ':''; ?>/> <label for="enableTracking1"><?php echo get_lang('Yes'); ?></label>
-		<input class="checkbox" type="radio" name="enableTrackingForm" value="0" id="enableTracking0" <?php echo $enableTrackingForm?'':'checked="checked" '; ?>/> <label for="enableTracking0"><?php echo get_lang('No'); ?></label>
-	  </td>
-	  <?php endif; ?>
-
-	  <td>&nbsp;</td>
-	</tr>
-	<tr id="optional_param6" style="display:none;">
-	  <td><?php echo get_lang('SingleDb'); ?> </td>
-
-	  <?php if($installType == 'update'): ?>
-	  <td><input type="hidden" name="singleDbForm" value="<?php echo $singleDbForm; ?>" /><?php echo $singleDbForm? get_lang('One') : get_lang('Several'); ?></td>
-	  <?php else: ?>
-	  <td>
-		<input class="checkbox" type="radio" name="singleDbForm" value="1" id="singleDb1" <?php echo $singleDbForm?'checked="checked" ':''; ?> onclick="show_hide_tracking_and_user_db(this.id);" /> <label for="singleDb1"><?php echo get_lang('One'); ?></label>
-		<input class="checkbox" type="radio" name="singleDbForm" value="0" id="singleDb0" <?php echo $singleDbForm?'':'checked="checked" '; ?> onclick="show_hide_tracking_and_user_db(this.id);" /> <label for="singleDb0"><?php echo get_lang('Several'); ?></label>
-	  </td>
-	  <?php endif; ?>
-
-	  <td>&nbsp;</td>
-	</tr>
-	</div>
-	<tr>
-		<td><button type="submit" class="login" name="step3" value="<?php echo get_lang('CheckDatabaseConnection'); ?>" ><?php echo get_lang('CheckDatabaseConnection'); ?></button></td>
-		<?php $dbConnect = test_db_connect ($dbHostForm, $dbUsernameForm, $dbPassForm, $singleDbForm, $dbPrefixForm);
-		if($dbConnect==1): ?>
-		<td colspan="2">
-			<div class="confirmation-message">
-				<!--<div  style="float:left; margin-right:10px;">
-				<img src="../img/message_confirmation.png" alt="Confirmation" />
-				</div>-->
-				<!--<div style="float:left;">-->
-				MySQL host info: <?php echo mysql_get_host_info(); ?><br />
-				MySQL server version: <?php echo mysql_get_server_info(); ?><br />
-				MySQL protocol version: <?php echo mysql_get_proto_info(); ?>
-				<!--</div>-->
-				<div style="clear:both;"></div>
-			</div>
-		</td>
-		<?php else: ?>
-		<td colspan="2">
-			<div style="float:left;" class="error-message">
-				<!--<div  style="float:left; margin-right:10px;">
-				<img src="../img/message_error.png" alt="Error" />
-				</div>-->
-				<div style="float:left;">
-				<strong>MySQL error: <?php echo mysql_errno(); ?></strong><br />
-				<?php echo mysql_error().'<br/>'; ?>
-				<strong><?php echo get_lang('Details').': '. get_lang('FailedConectionDatabase'); ?></strong><br />
-				</div>
-			</div>
-		</td>
-		<?php endif; ?>
-	</tr>
-	<tr>
-	  <td><button type="submit" name="step2" class="back" value="&lt; <?php echo get_lang('Previous'); ?>" ><?php echo get_lang('Previous'); ?></button></td>
-	  <td>&nbsp;</td>
-	  <td align="right"><input type="hidden" name="is_executable" id="is_executable" value="-" /><button type="submit" class="next" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" /><?php echo get_lang('Next'); ?></button></td>
-	</tr>
-	</table>
-	<?php
-}
-
-/**
-* Displays a parameter in a table row.
-* Used by the display_configuration_settings_form function.
-*/
-function display_configuration_parameter($install_type, $parameter_name, $form_field_name, $parameter_value, $display_when_update = 'true')
-{
-	global $charset;
-
-	echo "<tr>\n";
-	echo "<td>$parameter_name&nbsp;&nbsp;</td>\n";
-	if ($install_type == INSTALL_TYPE_UPDATE && $display_when_update)
-	{
-		echo '<td><input type="hidden" name="'.$form_field_name.'" value="'.api_htmlentities($parameter_value, ENT_QUOTES, $charset).'" />'.$parameter_value."</td>\n";
-	}
-	else
-	{
-		echo '<td><input type="text" size="'.FORM_FIELD_DISPLAY_LENGTH.'" maxlength="'.MAX_FORM_FIELD_LENGTH.'" name="'.$form_field_name.'" value="'.api_htmlentities($parameter_value, ENT_QUOTES, $charset).'" />'."</td>\n";
-	}
-	echo "</tr>\n";
-}
-
-/**
- * Displays step 4 of the installation - configuration settings about Dokeos itself.
- */
-function display_configuration_settings_form($installType, $urlForm, $languageForm, $emailForm, $adminFirstName, $adminLastName, $adminPhoneForm, $campusForm, $institutionForm, $institutionUrlForm, $encryptPassForm, $allowSelfReg, $allowSelfRegProf, $loginForm, $passForm)
-{
-	global $charset;
-
-	if($installType != 'update' && empty($languageForm))
-	{
-		$languageForm = $_SESSION['install_language'];
-	}
-
-	echo "<h2>" . display_step_sequence() . get_lang("CfgSetting") . "</h2>";
-	echo '<p>'.get_lang('ConfigSettingsInfo').' <b>main/inc/conf/configuration.php</b></p>';
-
-	echo "</td></tr>\n<tr><td>";
-	echo "<table width=\"100%\">";
-
-	//First parameter: language
-	echo "<tr>\n";
-	echo '<td>'.get_lang('MainLang')."&nbsp;&nbsp;</td>\n";
-	if($installType == 'update')
+			$maxlength = '15';
+		} else {
+			$maxlength = MAX_FORM_FIELD_LENGTH;
+		}
+
+		echo '<td><input type="'.$inputtype.'" size="'.DATABASE_FORM_FIELD_DISPLAY_LENGTH.'" maxlength="'.$maxlength.'" name="'.$form_field_name.'" id="'.$form_field_name.'" value="'.htmlentities($parameter_value).'" />'."</td>\n";
+		echo "<td>$extra_notice</td>\n";
+	}
+	echo "</tr>\n";
+}
+
+/**
+ * Displays step 3 - a form where the user can enter the installation settings
+ * regarding the databases - login and password, names, prefixes, single
+ * or multiple databases, tracking or not...
+ */
+function display_database_settings_form($installType, $dbHostForm, $dbUsernameForm, $dbPassForm, $dbPrefixForm, $enableTrackingForm, $singleDbForm, $dbNameForm, $dbStatsForm, $dbScormForm, $dbUserForm)
+{
+	if($installType == 'update')
 	{
-		echo '<td><input type="hidden" name="languageForm" value="'.api_htmlentities($languageForm, ENT_QUOTES, $charset).'" />'.$languageForm."</td>\n";
-	}
-	else // new installation
-	{
+		global $_configuration, $update_from_version_6;
+		if(in_array($_POST['old_version'],$update_from_version_6))
+		{
+	        $dbHostForm=get_config_param('dbHost');
+            $dbUsernameForm=get_config_param('dbLogin');
+            $dbPassForm=get_config_param('dbPass');
+            $dbPrefixForm=get_config_param('dbNamePrefix');
+            $enableTrackingForm=get_config_param('is_trackingEnabled');
+            $singleDbForm=get_config_param('singleDbEnabled');
+            $dbNameForm=get_config_param('mainDbName');
+            $dbStatsForm=get_config_param('statsDbName');
+            $dbScormForm=get_config_param('scormDbName');
+            $dbUserForm=get_config_param('user_personal_database');
+            $dbScormExists=true;
+		}
+		else
+		{
+			$dbHostForm=$_configuration['db_host'];
+			$dbUsernameForm=$_configuration['db_user'];
+			$dbPassForm=$_configuration['db_password'];
+			$dbPrefixForm=$_configuration['db_prefix'];
+			$enableTrackingForm=$_configuration['tracking_enabled'];
+			$singleDbForm=$_configuration['single_database'];
+			$dbNameForm=$_configuration['main_database'];
+			$dbStatsForm=$_configuration['statistics_database'];
+			$dbScormForm=$_configuration['scorm_database'];
+			$dbUserForm=$_configuration['user_personal_database'];
 
-	echo '<td>';
+			$dbScormExists=true;
+		}
+
+		if(empty($dbScormForm))
+		{
+			if($singleDbForm)
+			{
+				$dbScormForm=$dbNameForm;
+			}
+			else
+			{
+				$dbScormForm=$dbPrefixForm.'scorm';
+
+				$dbScormExists=false;
+			}
+		}
+		if(empty($dbUserForm))
+		{
+			if($singleDbForm)
+			{
+				$dbUserForm=$dbNameForm;
+			}
+			else
+			{
+				$dbUserForm=$dbPrefixForm.'dokeos_user';
+			}
+		}
+		echo "<h2>" . display_step_sequence() .get_lang("DBSetting") . "</h2>";
+		echo get_lang("DBSettingUpgradeIntro");
+	}else{
+		if(empty($dbPrefixForm)) //make sure there is a default value for db prefix
+		{
+			$dbPrefixForm = 'dokeos_';
+		}
+		echo "<h2>" . display_step_sequence() .get_lang("DBSetting") . "</h2>";
+		echo get_lang("DBSettingIntro");
+	}
+
+	?>
+	<br /><br />
+	</td>
+	</tr>
+	<tr>
+	<td>
+	<table width="100%">
+	<tr>
+	  <td width="40%"><?php echo get_lang('DBHost'); ?> </td>
+
+	  <?php if($installType == 'update'): ?>
+	  <td width="30%"><input type="hidden" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /><?php echo $dbHostForm; ?></td>
+	  <td width="30%">&nbsp;</td>
+	  <?php else: ?>
+	  <td width="30%"><input type="text" size="25" maxlength="50" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /></td>
+	  <td width="30%"><?php echo get_lang('EG').' localhost'; ?></td>
+	  <?php endif; ?>
+
+	</tr>
+	<?php
+	//database user username
+	$example_login = get_lang('EG').' root';
+	display_database_parameter($installType, get_lang('DBLogin'), 'dbUsernameForm', $dbUsernameForm, $example_login);
+	//database user password
+	$example_password = get_lang('EG').' '.api_generate_password();
+	display_database_parameter($installType, get_lang('DBPassword'), 'dbPassForm', $dbPassForm, $example_password);
+	//database prefix
+	display_database_parameter($installType, get_lang('DbPrefixForm'), 'dbPrefixForm', $dbPrefixForm, get_lang('DbPrefixCom'));
+	//fields for the four standard Dokeos databases
+	echo '<tr><td colspan="3"><a href="" onclick="javascript: show_hide_option();return false;" id="optionalparameters"><img style="vertical-align:middle;" src="../img/div_show.gif" alt="show-hide" /> '.get_lang('OptionalParameters','').'</a></td></tr>';
+	display_database_parameter($installType, get_lang('MainDB'), 'dbNameForm', $dbNameForm, '&nbsp;',null,'id="optional_param1" style="display:none;"');
+	display_database_parameter($installType, get_lang('StatDB'), 'dbStatsForm', $dbStatsForm, '&nbsp;',null,'id="optional_param2" style="display:none;"');
+	if($installType == 'update' && in_array($_POST['old_version'],$update_from_version_6))
+	{
+		display_database_parameter($installType, get_lang('ScormDB'), 'dbScormForm', $dbScormForm, '&nbsp;',null,'id="optional_param3" style="display:none;"');
+	}
+	display_database_parameter($installType, get_lang('UserDB'), 'dbUserForm', $dbUserForm, '&nbsp;',null,'id="optional_param4" style="display:none;"');
+	?>
+	<tr id="optional_param5" style="display:none;">
+	  <td><?php echo get_lang('EnableTracking'); ?> </td>
+
+	  <?php if($installType == 'update'): ?>
+	  <td><input type="hidden" name="enableTrackingForm" value="<?php echo $enableTrackingForm; ?>" /><?php echo $enableTrackingForm? get_lang('Yes') : get_lang('No'); ?></td>
+	  <?php else: ?>
+	  <td>
+		<input class="checkbox" type="radio" name="enableTrackingForm" value="1" id="enableTracking1" <?php echo $enableTrackingForm?'checked="checked" ':''; ?>/> <label for="enableTracking1"><?php echo get_lang('Yes'); ?></label>
+		<input class="checkbox" type="radio" name="enableTrackingForm" value="0" id="enableTracking0" <?php echo $enableTrackingForm?'':'checked="checked" '; ?>/> <label for="enableTracking0"><?php echo get_lang('No'); ?></label>
+	  </td>
+	  <?php endif; ?>
+
+	  <td>&nbsp;</td>
+	</tr>
+	<tr id="optional_param6" style="display:none;">
+	  <td><?php echo get_lang('SingleDb'); ?> </td>
+
+	  <?php if($installType == 'update'): ?>
+	  <td><input type="hidden" name="singleDbForm" value="<?php echo $singleDbForm; ?>" /><?php echo $singleDbForm? get_lang('One') : get_lang('Several'); ?></td>
+	  <?php else: ?>
+	  <td>
+		<input class="checkbox" type="radio" name="singleDbForm" value="1" id="singleDb1" <?php echo $singleDbForm?'checked="checked" ':''; ?> onclick="show_hide_tracking_and_user_db(this.id);" /> <label for="singleDb1"><?php echo get_lang('One'); ?></label>
+		<input class="checkbox" type="radio" name="singleDbForm" value="0" id="singleDb0" <?php echo $singleDbForm?'':'checked="checked" '; ?> onclick="show_hide_tracking_and_user_db(this.id);" /> <label for="singleDb0"><?php echo get_lang('Several'); ?></label>
+	  </td>
+	  <?php endif; ?>
+
+	  <td>&nbsp;</td>
+	</tr>
+	</div>
+	<tr>
+		<td><button type="submit" class="login" name="step3" value="<?php echo get_lang('CheckDatabaseConnection'); ?>" ><?php echo get_lang('CheckDatabaseConnection'); ?></button></td>
+		<?php $dbConnect = test_db_connect ($dbHostForm, $dbUsernameForm, $dbPassForm, $singleDbForm, $dbPrefixForm);
+		if($dbConnect==1): ?>
+		<td colspan="2">
+			<div class="confirmation-message">
+				<!--<div  style="float:left; margin-right:10px;">
+				<img src="../img/message_confirmation.png" alt="Confirmation" />
+				</div>-->
+				<!--<div style="float:left;">-->
+				MySQL host info: <?php echo mysql_get_host_info(); ?><br />
+				MySQL server version: <?php echo mysql_get_server_info(); ?><br />
+				MySQL protocol version: <?php echo mysql_get_proto_info(); ?>
+				<!--</div>-->
+				<div style="clear:both;"></div>
+			</div>
+		</td>
+		<?php else: ?>
+		<td colspan="2">
+			<div style="float:left;" class="error-message">
+				<!--<div  style="float:left; margin-right:10px;">
+				<img src="../img/message_error.png" alt="Error" />
+				</div>-->
+				<div style="float:left;">
+				<strong>MySQL error: <?php echo mysql_errno(); ?></strong><br />
+				<?php echo mysql_error().'<br/>'; ?>
+				<strong><?php echo get_lang('Details').': '. get_lang('FailedConectionDatabase'); ?></strong><br />
+				</div>
+			</div>
+		</td>
+		<?php endif; ?>
+	</tr>
+	<tr>
+	  <td><button type="submit" name="step2" class="back" value="&lt; <?php echo get_lang('Previous'); ?>" ><?php echo get_lang('Previous'); ?></button></td>
+	  <td>&nbsp;</td>
+	  <td align="right"><input type="hidden" name="is_executable" id="is_executable" value="-" /><button type="submit" class="next" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" /><?php echo get_lang('Next'); ?></button></td>
+	</tr>
+	</table>
+	<?php
+}
+
+/**
+* Displays a parameter in a table row.
+* Used by the display_configuration_settings_form function.
+*/
+function display_configuration_parameter($install_type, $parameter_name, $form_field_name, $parameter_value, $display_when_update = 'true')
+{
+	global $charset;
+
+	echo "<tr>\n";
+	echo "<td>$parameter_name&nbsp;&nbsp;</td>\n";
+	if ($install_type == INSTALL_TYPE_UPDATE && $display_when_update)
+	{
+		echo '<td><input type="hidden" name="'.$form_field_name.'" value="'.api_htmlentities($parameter_value, ENT_QUOTES, $charset).'" />'.$parameter_value."</td>\n";
+	}
+	else
+	{
+		echo '<td><input type="text" size="'.FORM_FIELD_DISPLAY_LENGTH.'" maxlength="'.MAX_FORM_FIELD_LENGTH.'" name="'.$form_field_name.'" value="'.api_htmlentities($parameter_value, ENT_QUOTES, $charset).'" />'."</td>\n";
+	}
+	echo "</tr>\n";
+}
+
+/**
+ * Displays step 4 of the installation - configuration settings about Dokeos itself.
+ */
+function display_configuration_settings_form($installType, $urlForm, $languageForm, $emailForm, $adminFirstName, $adminLastName, $adminPhoneForm, $campusForm, $institutionForm, $institutionUrlForm, $encryptPassForm, $allowSelfReg, $allowSelfRegProf, $loginForm, $passForm)
+{
+	global $charset;
+
+	if($installType != 'update' && empty($languageForm))
+	{
+		$languageForm = $_SESSION['install_language'];
+	}
+
+	echo "<h2>" . display_step_sequence() . get_lang("CfgSetting") . "</h2>";
+	echo '<p>'.get_lang('ConfigSettingsInfo').' <b>main/inc/conf/configuration.php</b></p>';
+
+	echo "</td></tr>\n<tr><td>";
+	echo "<table width=\"100%\">";
+
+	//First parameter: language
+	echo "<tr>\n";
+	echo '<td>'.get_lang('MainLang')."&nbsp;&nbsp;</td>\n";
+	if($installType == 'update')
+	{
+		echo '<td><input type="hidden" name="languageForm" value="'.api_htmlentities($languageForm, ENT_QUOTES, $charset).'" />'.$languageForm."</td>\n";
+	}
+	else // new installation
+	{
 
-	$array_lang = array('asturian','english','italian','french','slovenian','spanish');
-
-	////Only display Language have 90% +
+	echo '<td>';
+
+	$array_lang = array('asturian','english','italian','french','slovenian','spanish');
+
+	////Only display Language have 90% +
 	echo "\t\t<select name=\"languageForm\">\n";
 
-	foreach ($array_lang as $key => $value)	{
-		echo '<option value="'.$value.'"';
-		if($value == $languageForm) echo ' selected="selected"';
-		echo ">$value</option>\n";
-	}
-
-	echo "\t\t</select>\n";
-
-	//Display all language
-	/*echo "<select name=\"languageForm\">\n";
-		$dirname='../lang/';
-
-		if ($dir=@opendir($dirname)) {
-			$lang_files = array();
-				while (($file = readdir($dir)) !== false) {
-					if($file != '.' && $file != '..' && $file != 'CVS' && $file != '.svn' && is_dir($dirname.$file)){
-						array_push($lang_files, $file);
-					}
-				}
-			closedir($dir);
-		}
-		sort($lang_files);
-
-
-		foreach ($lang_files as $file) {
-			echo '<option value="'.$file.'"';
-				if($file == $languageForm) echo ' selected="selected"';
-				echo ">$file</option>\n";
-		}
-
-
-		echo '</select>';*/
-		echo "</td>\n";
-	}
-	echo "</tr>\n";
-
-	//Second parameter: Dokeos URL
-	echo "<tr>\n";
-	echo '<td>'.get_lang('DokeosURL').' (<font color="red">'.get_lang('ThisFieldIsRequired')."</font>)&nbsp;&nbsp;</td>\n";
-
-	if($installType == 'update') echo '<td>'.api_htmlentities($urlForm, ENT_QUOTES, $charset)."</td>\n";
-	else echo '<td><input type="text" size="40" maxlength="100" name="urlForm" value="'.api_htmlentities($urlForm, ENT_QUOTES, $charset).'" />'."</td>\n";
-
-	echo "</tr>\n";
-
-	//Parameter 3: administrator's email
-	display_configuration_parameter($installType, get_lang("AdminEmail"), "emailForm", $emailForm);
-
-	//Parameters 4 and 5: administrator's names
-	if (api_is_western_name_order()) {
-    display_configuration_parameter($installType, get_lang("AdminFirstName"), "adminFirstName", $adminFirstName);
-	display_configuration_parameter($installType, get_lang("AdminLastName"), "adminLastName", $adminLastName);
-	} else {
-		display_configuration_parameter($installType, get_lang("AdminLastName"), "adminLastName", $adminLastName);
-		display_configuration_parameter($installType, get_lang("AdminFirstName"), "adminFirstName", $adminFirstName);
-	}
-
-	//Parameter 6: administrator's telephone
-	display_configuration_parameter($installType, get_lang("AdminPhone"), "adminPhoneForm", $adminPhoneForm);
-
-	//Parameter 7: administrator's login
-	display_configuration_parameter($installType, get_lang("AdminLogin"), "loginForm", $loginForm, ($installType == 'update' ? true : false));
-
-	//Parameter 8: administrator's password
-	if($installType != 'update')
-		display_configuration_parameter($installType, get_lang("AdminPass"), "passForm", $passForm, false);
-
-	//Parameter 9: campus name
-	display_configuration_parameter($installType, get_lang("CampusName"), "campusForm", $campusForm);
-
-	//Parameter 10: institute (short) name
-	display_configuration_parameter($installType, get_lang("InstituteShortName"), "institutionForm", $institutionForm);
-
-	//Parameter 11: institute (short) name
-	display_configuration_parameter($installType, get_lang("InstituteURL"), "institutionUrlForm", $institutionUrlForm);
-
-	/*
-	 //old method
-	  	<tr>
-	  <td><?php echo get_lang("EncryptUserPass"); ?> :</td>
-
-	  <?php if($installType == 'update'): ?>
-	  <td><input type="hidden" name="encryptPassForm" value="<?php echo $encryptPassForm; ?>" /><?php echo $encryptPassForm? get_lang("Yes") : get_lang("No"); ?></td>
-	  <?php else: ?>
-	  <td>
-		<input class="checkbox" type="radio" name="encryptPassForm" value="1" id="encryptPass1" <?php echo $encryptPassForm?'checked="checked" ':''; ?>/> <label for="encryptPass1"><?php echo get_lang("Yes"); ?></label>
-		<input class="checkbox" type="radio" name="encryptPassForm" value="0" id="encryptPass0" <?php echo $encryptPassForm?'':'checked="checked" '; ?>/> <label for="encryptPass0"><?php echo get_lang("No"); ?></label>
-	  </td>
-	  <?php endif; ?>
-	</tr>
-
-	 */
-
-	?>
-	<tr>
-	  <td><?php echo get_lang("EncryptMethodUserPass"); ?> :</td>
-
-	  <?php if($installType == 'update'): ?>
-	  <td><input type="hidden" name="encryptPassForm" value="<?php echo $encryptPassForm; ?>" /><?php  echo $encryptPassForm; ?></td>
-	  <?php else: ?>
-	  <td>
-		<input class="checkbox" type="radio" name="encryptPassForm" value="md5" id="encryptPass0" <?php echo $encryptPassForm?'checked="checked" ':''; ?>/> <label for="encryptPass0"><?php echo "md5"; ?></label>
-		<input class="checkbox" type="radio" name="encryptPassForm" value="sha1" id="encryptPass1" <?php echo $encryptPassForm?'':'checked="checked" '; ?>/> <label for="encryptPass1"><?php echo "sha1"; ?></label>
-		<input class="checkbox" type="radio" name="encryptPassForm" value="none" id="encryptPass2" <?php echo $encryptPassForm?'':'checked="checked" '; ?>/> <label for="encryptPass2"><?php echo get_lang("None"); ?></label>
-	  </td>
-	  <?php endif; ?>
-	</tr>
-
-
-
-
-
-	<tr>
-	  <td><?php echo get_lang("AllowSelfReg"); ?> :</td>
-
-	  <?php if($installType == 'update'): ?>
-	  <td><input type="hidden" name="allowSelfReg" value="<?php echo $allowSelfReg; ?>" /><?php echo $allowSelfReg? get_lang("Yes") : get_lang("No"); ?></td>
-	  <?php else: ?>
-	  <td>
-		<input class="checkbox" type="radio" name="allowSelfReg" value="1" id="allowSelfReg1" <?php echo $allowSelfReg?'checked="checked" ':''; ?>/> <label for="allowSelfReg1"><?php echo get_lang("Yes").' '.get_lang("Recommended"); ?></label>
-		<input class="checkbox" type="radio" name="allowSelfReg" value="0" id="allowSelfReg0" <?php echo $allowSelfReg?'':'checked="checked" '; ?>/> <label for="allowSelfReg0"><?php echo get_lang("No"); ?></label>
-	  </td>
-	  <?php endif; ?>
-
-	</tr>
-	<tr>
-	  <td><?php echo get_lang("AllowSelfRegProf"); ?> :</td>
-
-	  <?php if($installType == 'update'): ?>
-	  <td><input type="hidden" name="allowSelfRegProf" value="<?php echo $allowSelfRegProf; ?>" /><?php echo $allowSelfRegProf? get_lang("Yes") : get_lang("No"); ?></td>
-	  <?php else: ?>
-	  <td>
-		<input class="checkbox" type="radio" name="allowSelfRegProf" value="1" id="allowSelfRegProf1" <?php echo $allowSelfRegProf?'checked="checked" ':''; ?>/> <label for="allowSelfRegProf1"><?php echo get_lang("Yes"); ?></label>
-		<input class="checkbox" type="radio" name="allowSelfRegProf" value="0" id="allowSelfRegProf0" <?php echo $allowSelfRegProf?'':'checked="checked" '; ?>/> <label for="allowSelfRegProf0"><?php echo get_lang("No"); ?></label>
-	  </td>
-	  <?php endif; ?>
-
-	</tr>
-	<tr>
-	  <td><button type="submit" class="back" name="step3" value="&lt; <?php echo get_lang('Previous'); ?>" /><?php echo get_lang('Previous'); ?></button></td>
-	  <td align="right"><input type="hidden" name="is_executable" id="is_executable" value="-" /><button class="next" type="submit" name="step5" value="<?php echo get_lang('Next'); ?> &gt;" /><?php echo get_lang('Next'); ?></button></td>
-	</tr>
-	</table>
-	<?php
-}
-
-/**
-* After installation is completed (step 6), this message is displayed.
-*/
-function display_after_install_message($installType, $nbr_courses)
-{
-	?>
-	<h2><?php echo display_step_sequence() . get_lang("CfgSetting"); ?></h2>
-
-	<?php echo get_lang('FirstUseTip'); ?>
-
-	<?php if($installType == 'update' && $nbr_courses > MAX_COURSE_TRANSFER): ?>
-	<br /><br />
-	<font color="red"><b><?php echo get_lang('Warning');?> :</b> <?php printf(get_lang('YouHaveMoreThanXCourses'),MAX_COURSE_TRANSFER,MAX_COURSE_TRANSFER,'<a href="update_courses.php"><font color="red">','</font></a>');?></font>
-	<?php endif; ?>
-
-	<br /><br />
-	<?php
-	echo '<div class="warning-message">';
-	//echo '<img src="../img/message_warning.png" style="float:left; margin-right:10px;" alt="'.get_lang('Warning').'"/>';
-	echo '<b>'.get_lang('SecurityAdvice').'</b>';
-	echo ': ';
-	printf(get_lang('ToProtectYourSiteMakeXAndYReadOnly'),'main/inc/conf/configuration.php','main/install/index.php');
-	echo '</div>';
-	?>
-
-
-	</form>
-	<a class="portal" href="../../index.php"><?php echo get_lang('GoToYourNewlyCreatedPortal'); ?></a>
-	<?php
-}
-
-/**
-* In step 3. Test the connection to the DB in case of single or multy DB.
-* Return "1"if no problems, "0" if, in case of multiDB we can't create a new DB and "-1" if there is no connection.
-*/
-function test_db_connect ($dbHostForm, $dbUsernameForm, $dbPassForm, $singleDbForm, $dbPrefixForm) {
-	$dbConnect = -1;
-	if ($singleDbForm == 1) {
-		if(@mysql_connect($dbHostForm, $dbUsernameForm, $dbPassForm) !== false) {
-			$dbConnect = 1;
-		} else {
-			$dbConnect = -1;
-		}
-	} elseif ($singleDbForm == 0) {
-		$res=@mysql_connect($dbHostForm, $dbUsernameForm, $dbPassForm);
-		if ($res===false) {
-			return $res;
-		}
-		if ($res !== false) {
-			// The Dokeos system has not been designed to use special SQL modes that were introduced since MySQL 5
-			@mysql_query("set session sql_mode='';");
-
-			$multipleDbCheck = @mysql_query("CREATE DATABASE ".$dbPrefixForm."test_dokeos_connection");
-			if ($multipleDbCheck !== false) {
-				$multipleDbCheck = @mysql_query("DROP DATABASE IF EXISTS ".$dbPrefixForm."test_dokeos_connection");
-				if ($multipleDbCheck !== false) {
-					$dbConnect = 1;
-				} else {
-					$dbConnect = 0;
-				}
-			} else {
-				$dbConnect = 0;
-			}
-		} else {
-			$dbConnect = -1;
-		}
-	}
-	return($dbConnect); //return "1"if no problems, "0" if, in case of multiDB we can't create a new DB and "-1" if there is no connection.
-}
-?>
+	foreach ($array_lang as $key => $value)	{
+		echo '<option value="'.$value.'"';
+		if($value == $languageForm) echo ' selected="selected"';
+		echo ">$value</option>\n";
+	}
+
+	echo "\t\t</select>\n";
+
+	//Display all language
+	/*echo "<select name=\"languageForm\">\n";
+		$dirname='../lang/';
+
+		if ($dir=@opendir($dirname)) {
+			$lang_files = array();
+				while (($file = readdir($dir)) !== false) {
+					if($file != '.' && $file != '..' && $file != 'CVS' && $file != '.svn' && is_dir($dirname.$file)){
+						array_push($lang_files, $file);
+					}
+				}
+			closedir($dir);
+		}
+		sort($lang_files);
+
+
+		foreach ($lang_files as $file) {
+			echo '<option value="'.$file.'"';
+				if($file == $languageForm) echo ' selected="selected"';
+				echo ">$file</option>\n";
+		}
+
+
+		echo '</select>';*/
+		echo "</td>\n";
+	}
+	echo "</tr>\n";
+
+	//Second parameter: Dokeos URL
+	echo "<tr>\n";
+	echo '<td>'.get_lang('DokeosURL').' (<font color="red">'.get_lang('ThisFieldIsRequired')."</font>)&nbsp;&nbsp;</td>\n";
+
+	if($installType == 'update') echo '<td>'.api_htmlentities($urlForm, ENT_QUOTES, $charset)."</td>\n";
+	else echo '<td><input type="text" size="40" maxlength="100" name="urlForm" value="'.api_htmlentities($urlForm, ENT_QUOTES, $charset).'" />'."</td>\n";
+
+	echo "</tr>\n";
+
+	//Parameter 3: administrator's email
+	display_configuration_parameter($installType, get_lang("AdminEmail"), "emailForm", $emailForm);
+
+	//Parameters 4 and 5: administrator's names
+	if (api_is_western_name_order()) {
+    display_configuration_parameter($installType, get_lang("AdminFirstName"), "adminFirstName", $adminFirstName);
+	display_configuration_parameter($installType, get_lang("AdminLastName"), "adminLastName", $adminLastName);
+	} else {
+		display_configuration_parameter($installType, get_lang("AdminLastName"), "adminLastName", $adminLastName);
+		display_configuration_parameter($installType, get_lang("AdminFirstName"), "adminFirstName", $adminFirstName);
+	}
+
+	//Parameter 6: administrator's telephone
+	display_configuration_parameter($installType, get_lang("AdminPhone"), "adminPhoneForm", $adminPhoneForm);
+
+	//Parameter 7: administrator's login
+	display_configuration_parameter($installType, get_lang("AdminLogin"), "loginForm", $loginForm, ($installType == 'update' ? true : false));
+
+	//Parameter 8: administrator's password
+	if($installType != 'update')
+		display_configuration_parameter($installType, get_lang("AdminPass"), "passForm", $passForm, false);
+
+	//Parameter 9: campus name
+	display_configuration_parameter($installType, get_lang("CampusName"), "campusForm", $campusForm);
+
+	//Parameter 10: institute (short) name
+	display_configuration_parameter($installType, get_lang("InstituteShortName"), "institutionForm", $institutionForm);
+
+	//Parameter 11: institute (short) name
+	display_configuration_parameter($installType, get_lang("InstituteURL"), "institutionUrlForm", $institutionUrlForm);
+
+	/*
+	 //old method
+	  	<tr>
+	  <td><?php echo get_lang("EncryptUserPass"); ?> :</td>
+
+	  <?php if($installType == 'update'): ?>
+	  <td><input type="hidden" name="encryptPassForm" value="<?php echo $encryptPassForm; ?>" /><?php echo $encryptPassForm? get_lang("Yes") : get_lang("No"); ?></td>
+	  <?php else: ?>
+	  <td>
+		<input class="checkbox" type="radio" name="encryptPassForm" value="1" id="encryptPass1" <?php echo $encryptPassForm?'checked="checked" ':''; ?>/> <label for="encryptPass1"><?php echo get_lang("Yes"); ?></label>
+		<input class="checkbox" type="radio" name="encryptPassForm" value="0" id="encryptPass0" <?php echo $encryptPassForm?'':'checked="checked" '; ?>/> <label for="encryptPass0"><?php echo get_lang("No"); ?></label>
+	  </td>
+	  <?php endif; ?>
+	</tr>
+
+	 */
+
+	?>
+	<tr>
+	  <td><?php echo get_lang("EncryptMethodUserPass"); ?> :</td>
+
+	  <?php if($installType == 'update'): ?>
+	  <td><input type="hidden" name="encryptPassForm" value="<?php echo $encryptPassForm; ?>" /><?php  echo $encryptPassForm; ?></td>
+	  <?php else: ?>
+	  <td>
+		<input class="checkbox" type="radio" name="encryptPassForm" value="md5" id="encryptPass0" <?php echo $encryptPassForm?'checked="checked" ':''; ?>/> <label for="encryptPass0"><?php echo "md5"; ?></label>
+		<input class="checkbox" type="radio" name="encryptPassForm" value="sha1" id="encryptPass1" <?php echo $encryptPassForm?'':'checked="checked" '; ?>/> <label for="encryptPass1"><?php echo "sha1"; ?></label>
+		<input class="checkbox" type="radio" name="encryptPassForm" value="none" id="encryptPass2" <?php echo $encryptPassForm?'':'checked="checked" '; ?>/> <label for="encryptPass2"><?php echo get_lang("None"); ?></label>
+	  </td>
+	  <?php endif; ?>
+	</tr>
+
+
+
+
+
+	<tr>
+	  <td><?php echo get_lang("AllowSelfReg"); ?> :</td>
+
+	  <?php if($installType == 'update'): ?>
+	  <td><input type="hidden" name="allowSelfReg" value="<?php echo $allowSelfReg; ?>" /><?php echo $allowSelfReg? get_lang("Yes") : get_lang("No"); ?></td>
+	  <?php else: ?>
+	  <td>
+		<input class="checkbox" type="radio" name="allowSelfReg" value="1" id="allowSelfReg1" <?php echo $allowSelfReg?'checked="checked" ':''; ?>/> <label for="allowSelfReg1"><?php echo get_lang("Yes").' '.get_lang("Recommended"); ?></label>
+		<input class="checkbox" type="radio" name="allowSelfReg" value="0" id="allowSelfReg0" <?php echo $allowSelfReg?'':'checked="checked" '; ?>/> <label for="allowSelfReg0"><?php echo get_lang("No"); ?></label>
+	  </td>
+	  <?php endif; ?>
+
+	</tr>
+	<tr>
+	  <td><?php echo get_lang("AllowSelfRegProf"); ?> :</td>
+
+	  <?php if($installType == 'update'): ?>
+	  <td><input type="hidden" name="allowSelfRegProf" value="<?php echo $allowSelfRegProf; ?>" /><?php echo $allowSelfRegProf? get_lang("Yes") : get_lang("No"); ?></td>
+	  <?php else: ?>
+	  <td>
+		<input class="checkbox" type="radio" name="allowSelfRegProf" value="1" id="allowSelfRegProf1" <?php echo $allowSelfRegProf?'checked="checked" ':''; ?>/> <label for="allowSelfRegProf1"><?php echo get_lang("Yes"); ?></label>
+		<input class="checkbox" type="radio" name="allowSelfRegProf" value="0" id="allowSelfRegProf0" <?php echo $allowSelfRegProf?'':'checked="checked" '; ?>/> <label for="allowSelfRegProf0"><?php echo get_lang("No"); ?></label>
+	  </td>
+	  <?php endif; ?>
+
+	</tr>
+	<tr>
+	  <td><button type="submit" class="back" name="step3" value="&lt; <?php echo get_lang('Previous'); ?>" /><?php echo get_lang('Previous'); ?></button></td>
+	  <td align="right"><input type="hidden" name="is_executable" id="is_executable" value="-" /><button class="next" type="submit" name="step5" value="<?php echo get_lang('Next'); ?> &gt;" /><?php echo get_lang('Next'); ?></button></td>
+	</tr>
+	</table>
+	<?php
+}
+
+/**
+* After installation is completed (step 6), this message is displayed.
+*/
+function display_after_install_message($installType, $nbr_courses)
+{
+	?>
+	<h2><?php echo display_step_sequence() . get_lang("CfgSetting"); ?></h2>
+
+	<?php echo get_lang('FirstUseTip'); ?>
+
+	<?php if($installType == 'update' && $nbr_courses > MAX_COURSE_TRANSFER): ?>
+	<br /><br />
+	<font color="red"><b><?php echo get_lang('Warning');?> :</b> <?php printf(get_lang('YouHaveMoreThanXCourses'),MAX_COURSE_TRANSFER,MAX_COURSE_TRANSFER,'<a href="update_courses.php"><font color="red">','</font></a>');?></font>
+	<?php endif; ?>
+
+	<br /><br />
+	<?php
+	echo '<div class="warning-message">';
+	//echo '<img src="../img/message_warning.png" style="float:left; margin-right:10px;" alt="'.get_lang('Warning').'"/>';
+	echo '<b>'.get_lang('SecurityAdvice').'</b>';
+	echo ': ';
+	printf(get_lang('ToProtectYourSiteMakeXAndYReadOnly'),'main/inc/conf/configuration.php','main/install/index.php');
+	echo '</div>';
+	?>
+
+
+	</form>
+	<a class="portal" href="../../index.php"><?php echo get_lang('GoToYourNewlyCreatedPortal'); ?></a>
+	<?php
+}
+
+/**
+* In step 3. Test the connection to the DB in case of single or multy DB.
+* Return "1"if no problems, "0" if, in case of multiDB we can't create a new DB and "-1" if there is no connection.
+*/
+function test_db_connect ($dbHostForm, $dbUsernameForm, $dbPassForm, $singleDbForm, $dbPrefixForm) {
+	$dbConnect = -1;
+	if ($singleDbForm == 1) {
+		if(@mysql_connect($dbHostForm, $dbUsernameForm, $dbPassForm) !== false) {
+			$dbConnect = 1;
+		} else {
+			$dbConnect = -1;
+		}
+	} elseif ($singleDbForm == 0) {
+		$res=@mysql_connect($dbHostForm, $dbUsernameForm, $dbPassForm);
+		if ($res===false) {
+			return $res;
+		}
+		if ($res !== false) {
+			// The Dokeos system has not been designed to use special SQL modes that were introduced since MySQL 5
+			@mysql_query("set session sql_mode='';");
+
+			$multipleDbCheck = @mysql_query("CREATE DATABASE ".$dbPrefixForm."test_dokeos_connection");
+			if ($multipleDbCheck !== false) {
+				$multipleDbCheck = @mysql_query("DROP DATABASE IF EXISTS ".$dbPrefixForm."test_dokeos_connection");
+				if ($multipleDbCheck !== false) {
+					$dbConnect = 1;
+				} else {
+					$dbConnect = 0;
+				}
+			} else {
+				$dbConnect = 0;
+			}
+		} else {
+			$dbConnect = -1;
+		}
+	}
+	return($dbConnect); //return "1"if no problems, "0" if, in case of multiDB we can't create a new DB and "-1" if there is no connection.
+}
+?>

+ 74 - 74
main/install/update-files-1.8.6-1.8.6.1.inc.php

@@ -1,83 +1,83 @@
 <?php
-/* See license terms in /dokeos_license.txt */
-/**
-==============================================================================
-* Updates the Dokeos files from version 1.8.6 to version 1.8.6.1
-* This script operates only in the case of an update, and only to change the
-* active version number (and other things that might need a change) in the
-* current configuration file.
-* As of 1.8.6, the Dokeos version has been added to configuration.php to
-* allow for edition (inc/conf is one of the directories that needs write
-* permissions on upgrade).
-* Being in configuration.php, it benefits from the configuration.dist.php
-* advantages that a new version doesn't overwrite it, thus letting the old
+/* See license terms in /dokeos_license.txt */
+/**
+==============================================================================
+* Updates the Dokeos files from version 1.8.6 to version 1.8.6.1
+* This script operates only in the case of an update, and only to change the
+* active version number (and other things that might need a change) in the
+* current configuration file.
+* As of 1.8.6, the Dokeos version has been added to configuration.php to
+* allow for edition (inc/conf is one of the directories that needs write
+* permissions on upgrade).
+* Being in configuration.php, it benefits from the configuration.dist.php
+* advantages that a new version doesn't overwrite it, thus letting the old
 * version be available until the end of the installation.
-* @package dokeos.install
-==============================================================================
-*/
-require_once("../inc/lib/main_api.lib.php");
-require_once("../inc/lib/fileUpload.lib.php");
-require_once('../inc/lib/database.lib.php');
-
-if (defined('DOKEOS_INSTALL') || defined('DOKEOS_COURSE_UPDATE'))
-{
-	// Edit the Dokeos config file
-	$file = file('../inc/conf/configuration.php');
-	$fh = fopen('../inc/conf/configuration.php','w');
-	$found_version = false;
-	$found_stable = false;
-	foreach($file as $line)
-	{
-		$ignore = false;
-		if(stristr($line,'$_configuration[\'dokeos_version\']'))
-		{
-			$found_version = true;
-			$line = '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n";
-		}
-		elseif(stristr($line,'$_configuration[\'dokeos_stable\']'))
-		{
-			$found_stable = true;
-			$line = '$_configuration[\'dokeos_stable\'] = '.($new_version_stable?'true':'false').';'."\r\n";
-		}
-		elseif(stristr($line,'$userPasswordCrypted'))
+* @package dokeos.install
+==============================================================================
+*/
+require_once("../inc/lib/main_api.lib.php");
+require_once("../inc/lib/fileUpload.lib.php");
+require_once('../inc/lib/database.lib.php');
+
+if (defined('DOKEOS_INSTALL') || defined('DOKEOS_COURSE_UPDATE'))
+{
+	// Edit the Dokeos config file
+	$file = file('../inc/conf/configuration.php');
+	$fh = fopen('../inc/conf/configuration.php','w');
+	$found_version = false;
+	$found_stable = false;
+	foreach($file as $line)
+	{
+		$ignore = false;
+		if(stristr($line,'$_configuration[\'dokeos_version\']'))
+		{
+			$found_version = true;
+			$line = '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n";
+		}
+		elseif(stristr($line,'$_configuration[\'dokeos_stable\']'))
+		{
+			$found_stable = true;
+			$line = '$_configuration[\'dokeos_stable\'] = '.($new_version_stable?'true':'false').';'."\r\n";
+		}
+		elseif(stristr($line,'$userPasswordCrypted'))
+		{
+			$line = '$userPasswordCrypted 									= \''.($userPasswordCrypted).'\';'."\r\n";
+		}
+		elseif(stristr($line,'?>'))
+		{
+			//ignore the line
+			$ignore = true;
+		}
+		if(!$ignore)
 		{
-			$line = '$userPasswordCrypted 									= \''.($userPasswordCrypted).'\';'."\r\n";
-		}
-		elseif(stristr($line,'?>'))
-		{
-			//ignore the line
-			$ignore = true;
-		}
-		if(!$ignore)
-		{
-			fwrite($fh,$line);
-		}
-	}
-	if(!$found_version)
-	{
-		fwrite($fh,'$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n");
-	}
-	if(!$found_stable)
-	{
+			fwrite($fh,$line);
+		}
+	}
+	if(!$found_version)
+	{
+		fwrite($fh,'$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n");
+	}
+	if(!$found_stable)
+	{
 		fwrite($fh,'$_configuration[\'dokeos_stable\'] = '.($new_version_stable?'true':'false').';'."\r\n");
-	}
-	fwrite($fh,'?>');
+	}
+	fwrite($fh,'?>');
 	fclose($fh);
 
 
-	$perm = api_get_setting('permissions_for_new_directories');
-	$perm = octdec(!empty($perm)?$perm:'0770');
-	$old_umask = umask(0);
+	$perm = api_get_setting('permissions_for_new_directories');
+	$perm = octdec(!empty($perm)?$perm:'0770');
+	$old_umask = umask(0);
 
-	////create a specific directory for global thumbails
-	//home > default_platform_document > template_thumb
-	if(!is_dir($pathForm.'home/default_platform_document/template_thumb')){
-		mkdir($pathForm.'home/default_platform_document/template_thumb',$perm);
-	}
+	////create a specific directory for global thumbails
+	//home > default_platform_document > template_thumb
+	if(!is_dir($pathForm.'home/default_platform_document/template_thumb')){
+		mkdir($pathForm.'home/default_platform_document/template_thumb',$perm);
+	}
 
-}
-else
-{
-	echo 'You are not allowed here !';
-}
-?>
+}
+else
+{
+	echo 'You are not allowed here !';
+}
+?>

+ 925 - 925
main/install/upgrade.php

@@ -1,933 +1,933 @@
-<?php // $Id: upgrade.php 22577 2009-08-03 04:31:24Z yannoo $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-* In this file we're working on a well-organised upgrade script to
+<?php // $Id: upgrade.php 22577 2009-08-03 04:31:24Z yannoo $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+* In this file we're working on a well-organised upgrade script to
 * upgrade directly from Dokeos 1.6.x to Dokeos 1.8.3
-*
-* For this upgrade we assume there is an old_dokeos directory and the new
+*
+* For this upgrade we assume there is an old_dokeos directory and the new
 * software is in a new_dokeos directory. While we're busy developing we
-* work in this one  - large - separate file so not to disturb the other
-* existing classes - the existing code remains working.
-*
-* This script uses PEAR QuickForm and QuickFormController classes.
-*
-* First version
-* - ask for old version path
-* - check version (1.6.x or 1.8.x, no others supported at the moment)
-* - get settings from old version
-* - perform necessary upgrade functions based on version
-
-* Future improvements
-* - ask user if she agrees to detected version (chance to cancel)
-* - ability to do in-place upgrade
-* - ability to let old databases remain and clone them for new install so
-* Dokeos admins can have old and new version running side by side
-*
-* @package dokeos.install
-==============================================================================
-*/
-/*
-* ABOUT DETECTING OLDER VERSIONS
-* Dokeos versions 1.6.x and 1.8.x have an installedVersion.inc.php file.
-* In 1.6.x they have a parameter $platformVersion,
-* in 1.8.x a parameter $dokeos_version.
-* The function get_installed_version($old_installation_path, $parameter)
-* can be used to detect version numbers.
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
+* work in this one  - large - separate file so not to disturb the other
+* existing classes - the existing code remains working.
+*
+* This script uses PEAR QuickForm and QuickFormController classes.
+*
+* First version
+* - ask for old version path
+* - check version (1.6.x or 1.8.x, no others supported at the moment)
+* - get settings from old version
+* - perform necessary upgrade functions based on version
+
+* Future improvements
+* - ask user if she agrees to detected version (chance to cancel)
+* - ability to do in-place upgrade
+* - ability to let old databases remain and clone them for new install so
+* Dokeos admins can have old and new version running side by side
+*
+* @package dokeos.install
+==============================================================================
+*/
+/*
+* ABOUT DETECTING OLDER VERSIONS
+* Dokeos versions 1.6.x and 1.8.x have an installedVersion.inc.php file.
+* In 1.6.x they have a parameter $platformVersion,
+* in 1.8.x a parameter $dokeos_version.
+* The function get_installed_version($old_installation_path, $parameter)
+* can be used to detect version numbers.
 */
-session_start();
-
-ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.'../inc/lib/pear');
-//echo ini_get('include_path'); //DEBUG
-require_once 'HTML/QuickForm/Controller.php';
-require_once 'HTML/QuickForm/Rule.php';
-require_once 'HTML/QuickForm/Action/Display.php';
-
-require('../inc/installedVersion.inc.php');
-require('../inc/lib/main_api.lib.php');
-
-require('../lang/english/trad4all.inc.php');
-require('../lang/english/install.inc.php');
-require_once('install_upgrade.lib.php');
-require_once('upgrade_lib.php');
-
-define('DOKEOS_INSTALL',1);
-define('MAX_COURSE_TRANSFER',100);
-define('INSTALL_TYPE_UPDATE', 'update');
-define('FORM_FIELD_DISPLAY_LENGTH', 40);
-define('DATABASE_FORM_FIELD_DISPLAY_LENGTH', 25);
-define('MAX_FORM_FIELD_LENGTH', 50);
-define('DEFAULT_LANGUAGE', 'english');
-
-//error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
-error_reporting(E_ALL);
-
-@set_time_limit(0);
-
-if(function_exists('ini_set'))
-{
-	ini_set('memory_limit',-1);
-	ini_set('max_execution_time',0);
-}
-
-$update_from_version=array('1.6','1.6.1','1.6.2','1.6.3','1.6.4','1.6.5','1.8.0','1.8.1','1.8.2');
-$update_from_16_version = array('1.6','1.6.1','1.6.2','1.6.3','1.6.4','1.6.5');
-$update_from_18_version = array('1.8.0','1.8.1','1.8.2');
-
-
-/*
-==============================================================================
-		CLASSES
-==============================================================================
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
 */
-
-/**
- * Page in the install wizard to select the language which will be used during
- * the installation process.
- */
-class Page_Language extends HTML_QuickForm_Page
-{
-	function get_title()
-	{
-		return get_lang('WelcomeToDokeosInstaller');
-	}
-	function get_info()
-	{
-		return 'Please select the language you\'d like to use while installing:';
-	}
-	function buildForm()
-	{
-		$this->_formBuilt = true;
-		$this->addElement('select', 'install_language', get_lang('InstallationLanguage'), get_language_folder_list());
-		$buttons[0] = & HTML_QuickForm :: createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
-		$this->addGroup($buttons, 'buttons', '', '&nbsp;', false);
-		$this->setDefaultAction('next');
-	}
-}
-
-/**
- * Class for requirements page
- * This checks and informs about some requirements for installing Dokeos:
- * - necessary and optional extensions
- * - folders which have to be writable
- */
-class Page_Requirements extends HTML_QuickForm_Page
-{
-	/**
-	* this function checks if a php extension exists or not
-	*
-	* @param string  $extentionName  name of the php extension to be checked
-	* @param boolean  $echoWhenOk  true => show ok when the extension exists
-	* @author Christophe Gesche
-	*/
-	function check_extension($extentionName)
-	{
-		if (extension_loaded($extentionName))
-		{
-			return '<li>'.$extentionName.' - ok</li>';
-		}
-		else
-		{
-			return '<li><b>'.$extentionName.'</b> <font color="red">is missing (Dokeos can work without)</font> (<a href="http://www.php.net/'.$extentionName.'" target="_blank">'.$extentionName.'</a>)</li>';
-		}
-	}
-	function get_not_writable_folders()
-	{
-		$writable_folders = array ('../inc/conf', '../upload', '../../archive', '../../courses', '../../home');
-		$not_writable = array ();
-		$perm = api_get_setting('permissions_for_new_directories');
-		$perm = octdec(!empty($perm)?$perm:'0770');
-		foreach ($writable_folders as $index => $folder)
-		{
-			if (!is_writable($folder) && !@ chmod($folder, $perm))
-			{
-				$not_writable[] = $folder;
-			}
-		}
-		return $not_writable;
-	}
-	function get_title()
-	{
-		return get_lang("Requirements");
-	}
-	function get_info()
-	{
-		$not_writable = $this->get_not_writable_folders();
-
-		if (count($not_writable) > 0)
-		{
-			$info[] = '<div style="margin:20px;padding:10px;width: 50%;color:#FF6600;border:2px solid #FF6600;">';
-			$info[] = 'Some files or folders don\'t have writing permission. To be able to install Dokeos you should first change their permissions (using CHMOD). Please read the <a href="../../installation_guide.html" target="blank">installation guide</a>.';
-			$info[] = '<ul>';
-			foreach ($not_writable as $index => $folder)
-			{
-				$info[] = '<li>'.$folder.'</li>';
-			}
-			$info[] = '</ul>';
-			$info[] = '</div>';
-			$this->disableNext = true;
-		}
-		elseif (file_exists('../inc/conf/claro_main.conf.php'))
-		{
-			$info[] = '<div style="margin:20px;padding:10px;width: 50%;color:#FF6600;border:2px solid #FF6600;text-align:center;">';
-			$info[] = get_lang("WarningExistingDokeosInstallationDetected");
-			$info[] = '</div>';
-		}
-		$info[] = '<b>'.get_lang("ReadThoroughly").'</b>';
-		$info[] = '<br />';
-		$info[] = get_lang("DokeosNeedFollowingOnServer");
-		$info[] = "<ul>";
-		$info[] = "<li>Webserver with PHP 5.x";
-		$info[] = '<ul>';
-		$info[] = $this->check_extension('standard');
-		$info[] = $this->check_extension('session');
-		$info[] = $this->check_extension('mysql');
-		$info[] = $this->check_extension('zlib');
-		$info[] = $this->check_extension('pcre');
-		$info[] = '</ul></li>';
-		$info[] = "<li>MySQL + login/password allowing to access and create at least one database</li>";
-		$info[] = "<li>Write access to web directory where Dokeos files have been put</li>";
-		$info[] = "</ul>";
-		$info[] = get_lang('MoreDetails').", <a href=\"../../installation_guide.html\" target=\"blank\">read the installation guide</a>.";
-		return implode("\n",$info);
-	}
-	function buildForm()
-	{
-		global $updateFromVersion;
-		$this->_formBuilt = true;
-		$this->addElement('radio', 'installation_type', get_lang('InstallType'), get_lang('NewInstall'), 'new');
-		$update_group[0] = & HTML_QuickForm :: createElement('radio', 'installation_type', null, 'Update from Dokeos '.implode('|', $updateFromVersion).'', 'update');
-		//$this->addGroup($update_group, 'update_group', '', '&nbsp;', false);
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
-		$not_writable = $this->get_not_writable_folders();
-		if (count($not_writable) > 0)
-		{
-			$el = $prevnext[1];
-			$el->updateAttributes('disabled="disabled"');
-		}
-		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
-		$this->setDefaultAction('next');
-	}
-}
-
-/**
- * Page in the install wizard to select the location of the old Dokeos installation.
- */
-class Page_LocationOldVersion extends HTML_QuickForm_Page
-{
-	function get_title()
-	{
-		return 'Old version root path';
-	}
-	function get_info()
-	{
-		return 'Give location of your old Dokeos installation ';
-	}
-	function buildForm()
-	{
-		$this->_formBuilt = true;
-		$this->addElement('text', 'old_version_path', 'Old version root path');
-		$this->applyFilter('old_version_path', 'trim');
-		$this->addRule('old_version_path', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addRule('old_version_path', get_lang('BadUpdatePath'), 'callback', 'check_update_path');
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
-		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
-		$this->setDefaultAction('next');
-	}
-}
-
-/**
- * Class for license page
- * Displays the GNU GPL license that has to be accepted to install Dokeos.
- */
-class Page_License extends HTML_QuickForm_Page
-{
-	function get_title()
-	{
-		return get_lang('Licence');
-	}
-	function get_info()
-	{
-		return get_lang('DokeosLicenseInfo');
-	}
-	function buildForm()
-	{
-		$this->_formBuilt = true;
-		$this->addElement('textarea', 'license', get_lang('Licence'), array ('cols' => 80, 'rows' => 20, 'disabled' => 'disabled', 'style'=>'background-color: white;'));
-		$this->addElement('checkbox','license_accept','',get_lang('IAccept'));
-		$this->addRule('license_accept',get_lang('ThisFieldIsRequired'),'required');
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
-		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
-		$this->setDefaultAction('next');
-	}
-}
-
-/**
- * Class for database settings page
- * Displays a form where the user can enter the installation settings
- * regarding the databases - login and password, names, prefixes, single
- * or multiple databases, tracking or not...
- */
-class Page_DatabaseSettings extends HTML_QuickForm_Page
-{
-	function get_title()
-	{
-		return get_lang('DBSetting');
-	}
-	function get_info()
-	{
-		return get_lang('DBSettingIntro');
-	}
-	function buildForm()
-	{
-		$this->_formBuilt = true;
-		$this->addElement('text', 'database_host', get_lang("DBHost"), array ('size' => '40'));
-		$this->addRule('database_host', 'ThisFieldIsRequired', 'required');
-		$this->addElement('text', 'database_username', get_lang("DBLogin"), array ('size' => '40'));
-		$this->addElement('password', 'database_password', get_lang("DBPassword"), array ('size' => '40'));
-		$this->addRule(array('database_host','database_username','database_password'),get_lang('CouldNotConnectToDatabase'),new ValidateDatabaseConnection());
-		$this->addElement('text', 'database_prefix', get_lang("DbPrefixForm"), array ('size' => '40'));
-		$this->addElement('text', 'database_main_db', get_lang("MainDB"), array ('size' => '40'));
-		$this->addRule('database_main_db', 'ThisFieldIsRequired', 'required');
-		$this->addElement('text', 'database_tracking', get_lang("StatDB"), array ('size' => '40'));
-		$this->addRule('database_tracking', 'ThisFieldIsRequired', 'required');
-		$this->addElement('text', 'database_scorm', get_lang("ScormDB"), array ('size' => '40'));
-		$this->addRule('database_scorm', 'ThisFieldIsRequired', 'required');
-		$this->addElement('text', 'database_user', get_lang("UserDB"), array ('size' => '40'));
-		$this->addRule('database_user', 'ThisFieldIsRequired', 'required');
-		//$this->addElement('text', 'database_repository', get_lang("RepositoryDatabase"), array ('size' => '40'));
-		//$this->addRule('database_repository', 'ThisFieldIsRequired', 'required');
-		//$this->addElement('text', 'database_weblcms', get_lang("WeblcmsDatabase"), array ('size' => '40'));
-		//$this->addRule('database_weblcms', 'ThisFieldIsRequired', 'required');
-		//$this->addElement('text', 'database_personal_calendar', get_lang("PersonalCalendarDatabase"), array ('size' => '40'));
-		//$this->addRule('database_personal_calendar', 'ThisFieldIsRequired', 'required');
-		//$this->addElement('text', 'database_personal_messenger', get_lang("PersonalMessageDatabase"), array ('size' => '40'));
-		//$this->addRule('database_personal_messenger', 'ThisFieldIsRequired', 'required');
-		//$this->addElement('text', 'database_profiler', get_lang("ProfilerDatabase"), array ('size' => '40'));
-		//$this->addRule('database_profiler', 'ThisFieldIsRequired', 'required');
-
-		$enable_tracking[] = & $this->createElement('radio', 'enable_tracking', null, get_lang("Yes"), 1);
-		$enable_tracking[] = & $this->createElement('radio', 'enable_tracking', null, get_lang("No"), 0);
-		$this->addGroup($enable_tracking, 'tracking', get_lang("EnableTracking"), '&nbsp;', false);
-		$several_db[] = & $this->createElement('radio', 'database_single', null, get_lang("One"),1);
-		$several_db[] = & $this->createElement('radio', 'database_single', null, get_lang("Several"),0);
-		$this->addGroup($several_db, 'db', get_lang("SingleDb"), '&nbsp;', false);
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
-		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
-		$this->setDefaultAction('next');
-	}
-}
-class ValidateDatabaseConnection extends HTML_QuickForm_Rule
-{
-	public function validate($parameters)
-	{
-		$db_host = $parameters[0];
-		$db_user = $parameters[1];
-		$db_password = $parameters[2];
-		if(mysql_connect($db_host,$db_user,$db_password))
-		{
-			return true;
-		}
-		return false;
-	}
-}
-
-/**
- * Page in the install wizard in which some config settings are asked to the
- * user.
- */
-class Page_ConfigSettings extends HTML_QuickForm_Page
-{
-	function get_title()
-	{
-		return get_lang('CfgSetting');
-	}
-	function get_info()
-	{
-		return get_lang('ConfigSettingsInfo');
-	}
-	function buildForm()
-	{
-		$this->_formBuilt = true;
-		$languages = array ();
-		$languages['dutch'] = 'dutch';
-		$this->addElement('select', 'platform_language', get_lang("MainLang"), get_language_folder_list());
-		$this->addElement('text', 'platform_url', get_lang("DokeosURL"), array ('size' => '40'));
-		$this->addRule('platform_url', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addElement('text', 'admin_email', get_lang("AdminEmail"), array ('size' => '40'));
-		$this->addRule('admin_email', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addRule('admin_email', get_lang('WrongEmail'), 'email');
-		$this->addElement('text', 'admin_lastname', get_lang("AdminLastName"), array ('size' => '40'));
-		$this->addRule('admin_lastname', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addElement('text', 'admin_firstname', get_lang("AdminFirstName"), array ('size' => '40'));
-		$this->addRule('admin_firstname', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addElement('text', 'admin_phone', get_lang("AdminPhone"), array ('size' => '40'));
-		$this->addElement('text', 'admin_username', get_lang("AdminLogin"), array ('size' => '40'));
-		$this->addRule('admin_username', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addElement('text', 'admin_password', get_lang("AdminPass"), array ('size' => '40'));
-		$this->addRule('admin_password', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addElement('text', 'platform_name', get_lang("CampusName"), array ('size' => '40'));
-		$this->addRule('platform_name', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addElement('text', 'organization_name', get_lang("InstituteShortName"), array ('size' => '40'));
-		$this->addRule('organization_name', get_lang('ThisFieldIsRequired'), 'required');
-		$this->addElement('text', 'organization_url', get_lang("InstituteURL"), array ('size' => '40'));
-		$this->addRule('organization_url', get_lang('ThisFieldIsRequired'), 'required');
-		$encrypt[] = & $this->createElement('radio', 'encrypt_password', null, get_lang('Yes'), 1);
-		$encrypt[] = & $this->createElement('radio', 'encrypt_password', null, get_lang('No'), 0);
-		$this->addGroup($encrypt, 'tracking', get_lang("EncryptUserPass"), '&nbsp;', false);
-		$self_reg[] = & $this->createElement('radio', 'self_reg', null, get_lang('Yes'), 1);
-		$self_reg[] = & $this->createElement('radio', 'self_reg', null, get_lang('No'), 0);
-		$this->addGroup($self_reg, 'tracking', get_lang("AllowSelfReg"), '&nbsp;', false);
-		$self_reg_teacher[] = & $this->createElement('radio', 'self_reg_teacher', null, get_lang('Yes'), 1);
-		$self_reg_teacher[] = & $this->createElement('radio', 'self_reg_teacher', null, get_lang('No'), 0);
-		$this->addGroup($self_reg_teacher, 'tracking', get_lang("AllowSelfRegProf"), '&nbsp;', false);
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
-		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
-		$this->setDefaultAction('next');
-	}
-}
-
-/**
- * Page in the install wizard in which a final overview of all settings is
- * displayed.
- */
-class Page_ConfirmSettings extends HTML_QuickForm_Page
-{
-	function get_title()
-	{
-		return get_lang('LastCheck');
-	}
-	function get_info()
-	{
-		return 'Here are the values you entered
-				<br />
-				<strong>Print this page to remember your password and other settings</strong>';
-
-	}
-	function buildForm()
-	{
-		$wizard = $this->controller;
-		$values = $wizard->exportValues();
-		$this->addElement('static', 'confirm_platform_language', get_lang("MainLang"), $values['platform_language']);
-		$this->addElement('static', 'confirm_platform_url', get_lang("DokeosURL"), $values['platform_url']);
-		$this->addElement('static', 'confirm_admin_email', get_lang("AdminEmail"), $values['admin_email']);
-		$this->addElement('static', 'confirm_admin_lastname', get_lang("AdminLastName"), $values['admin_lastname']);
-		$this->addElement('static', 'confirm_admin_firstname', get_lang("AdminFirstName"), $values['admin_firstname']);
-		$this->addElement('static', 'confirm_admin_phone', get_lang("AdminPhone"), $values['admin_phone']);
-		$this->addElement('static', 'confirm_admin_username', get_lang("AdminLogin"), $values['admin_username']);
-		$this->addElement('static', 'confirm_admin_password', get_lang("AdminPass"), $values['admin_password']);
-		$this->addElement('static', 'confirm_platform_name', get_lang("CampusName"), $values['platform_name']);
-		$this->addElement('static', 'confirm_organization_name', get_lang("InstituteShortName"), $values['organization_name']);
-		$this->addElement('static', 'confirm_organization_url', get_lang("InstituteURL"), $values['organization_url']);
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
-		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
-		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
-		$this->setDefaultAction('next');
-	}
-}
-
-
-/**
- * Class to render a page in the install wizard.
- */
-class ActionDisplay extends HTML_QuickForm_Action_Display
-{
-	/**
-	 * Displays the HTML-code of a page in the wizard
-	 * @param HTML_Quickform_Page $page The page to display.
-	 */
-	function _renderForm(& $current_page)
-	{
-		global $charset;
-
-		global $dokeos_version, $installType, $updateFromVersion;
-		$renderer = & $current_page->defaultRenderer();
-		$current_page->setRequiredNote('<font color="#FF0000">*</font> '.get_lang('ThisFieldIsRequired'));
-		$element_template = "\n\t<tr>\n\t\t<td valign=\"top\"><!-- BEGIN required --><span style=\"color: #ff0000\">*</span> <!-- END required -->{label}</td>\n\t\t<td valign=\"top\" align=\"left\"><!-- BEGIN error --><span style=\"color: #ff0000;font-size:x-small;margin:2px;\">{error}</span><br /><!-- END error -->\t{element}</td>\n\t</tr>";
-		$renderer->setElementTemplate($element_template);
-		$header_template = "\n\t<tr>\n\t\t<td valign=\"top\" colspan=\"2\">{header}</td>\n\t</tr>";
-		$renderer->setHeaderTemplate($header_template);
-		HTML_QuickForm :: setRequiredNote('<font color="red">*</font> <small>'.get_lang('ThisFieldIsRequired').'</small>');
-		$current_page->accept($renderer);
-?>
-		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
-		<head>
-		<title>-- Dokeos - upgrade to version <?php echo $dokeos_version; ?></title>
-		<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset; ?>" />
-		<link rel="stylesheet" href="../css/dokeos_blue/default.css" type="text/css"/>
-		</head>
-		<body dir="<?php echo get_lang('text_dir'); ?>">
-		<div id="header1">
-			Dokeos - upgrade to version <?php echo $dokeos_version; ?><?php if($installType == 'new') echo ' - New installation'; else if($installType == 'update') echo ' - Update from Dokeos '.implode('|',$updateFromVersion); ?>
-		</div>
-		<div style="float: left; background-color:#EFEFEF;margin-right: 20px;padding: 10px;">
-			<img src="../img/bluelogo.gif" alt="logo"/>
-			<?php
-
-		$all_pages = $current_page->controller->_pages;
-		$total_number_of_pages = count($all_pages);
-		$current_page_number = 0;
-		$page_number = 0;
-		echo '<ol>';
-		foreach($all_pages as $index => $page)
-		{
-			$page_number++;
-			if($page->get_title() == $current_page->get_title())
-			{
-				$current_page_number = $page_number;
-				echo '<li style="font-weight: bold;">'.$page->get_title().'</li>';
-			}
-			else
-			{
-				echo '<li>'.$page->get_title().'</li>';
-			}
-		}
-		echo '</ol>';
-		echo '</div>';
-		echo '<div style="margin: 10px;">';
-		echo '<h2>'.get_lang('Step').' '.$current_page_number.' '.get_lang('of').' '.$total_number_of_pages.' &ndash; '.$current_page->get_title().'</h2>';
-		echo '<div>';
-		echo $current_page->get_info();
-		echo '</div>';
-		echo $renderer->toHtml();
-		?>
-        </div>
-        <div style="clear:both;"></div>
-        <div id="footer">
-        &copy; <?php echo $dokeos_version; ?>
-        </div>
-		</body>
-		</html>
-		<?php
-	}
-}
-
-/**
-* Class for form processing
-* Here happens the actual installation action after collecting
-* all the required data.
-*/
-class ActionProcess extends HTML_QuickForm_Action
-{
-	function perform(& $page, $actionName)
-	{
-		global $charset;
-
-		global $dokeos_version, $installType, $updateFromVersion;
-		$values = $page->controller->exportValues();
-		?>
-		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
-		<head>
-		<title>-- Dokeos installation -- version <?php echo $dokeos_version; ?></title>
-		<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset; ?>" />
-		<link rel="stylesheet" href="../css/dokeos_blue/default.css" type="text/css"/>
-		</head>
-		<body dir="<?php echo get_lang('text_dir'); ?>">
-		<div style="background-color:#4171B5;color:white;font-size:x-large;">
-			Dokeos installation - version <?php echo $dokeos_version; ?><?php if($installType == 'new') echo ' - New installation'; else if($installType == 'update') echo ' - Update from Dokeos '.implode('|',$updateFromVersion); ?>
-		</div>
-		<div style="margin:50px;">
-			<img src="../img/bluelogo.gif" alt="logo" align="right"/>
-		<?php
-		echo '<pre>';
-
-		global $repository_database;
-		global $weblcms_database;
-		global $personal_calendar_database;
-		global $user_database;
-		global $personal_messenger_database;
-		global $profiler_database;
-
-		$repository_database = $values['database_repository'];
-		$weblcms_database = $values['database_weblcms'];
-		$personal_calendar_database = $values['database_personal_calendar'];
-		$user_database = $values['database_user'];
-		$personal_messenger_database = $values['database_personal_messenger'];
-		$profiler_database = $values['database_profiler'];
-
-		/*full_database_install($values);
-		full_file_install($values);
-		create_admin_in_user_table($values);
-		create_default_categories_in_weblcms();*/
-		echo "<p>Performing upgrade to latest version....</p>";
-
-		//upgrade_16x_to_180($values);
-
-		echo '</pre>';
-		$page->controller->container(true);
-		?>
-		<a class="portal" href="../../index.php"><?php echo get_lang('GoToYourNewlyCreatedPortal'); ?></a>
-        </div>
-		</body>
-		</html>
-		<?php
-	}
-}
-
-
-/*
-==============================================================================
-		FUNCTIONS
-==============================================================================
+session_start();
+
+ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.'../inc/lib/pear');
+//echo ini_get('include_path'); //DEBUG
+require_once 'HTML/QuickForm/Controller.php';
+require_once 'HTML/QuickForm/Rule.php';
+require_once 'HTML/QuickForm/Action/Display.php';
+
+require('../inc/installedVersion.inc.php');
+require('../inc/lib/main_api.lib.php');
+
+require('../lang/english/trad4all.inc.php');
+require('../lang/english/install.inc.php');
+require_once('install_upgrade.lib.php');
+require_once('upgrade_lib.php');
+
+define('DOKEOS_INSTALL',1);
+define('MAX_COURSE_TRANSFER',100);
+define('INSTALL_TYPE_UPDATE', 'update');
+define('FORM_FIELD_DISPLAY_LENGTH', 40);
+define('DATABASE_FORM_FIELD_DISPLAY_LENGTH', 25);
+define('MAX_FORM_FIELD_LENGTH', 50);
+define('DEFAULT_LANGUAGE', 'english');
+
+//error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
+error_reporting(E_ALL);
+
+@set_time_limit(0);
+
+if(function_exists('ini_set'))
+{
+	ini_set('memory_limit',-1);
+	ini_set('max_execution_time',0);
+}
+
+$update_from_version=array('1.6','1.6.1','1.6.2','1.6.3','1.6.4','1.6.5','1.8.0','1.8.1','1.8.2');
+$update_from_16_version = array('1.6','1.6.1','1.6.2','1.6.3','1.6.4','1.6.5');
+$update_from_18_version = array('1.8.0','1.8.1','1.8.2');
+
+
+/*
+==============================================================================
+		CLASSES
+==============================================================================
+*/
+
+/**
+ * Page in the install wizard to select the language which will be used during
+ * the installation process.
+ */
+class Page_Language extends HTML_QuickForm_Page
+{
+	function get_title()
+	{
+		return get_lang('WelcomeToDokeosInstaller');
+	}
+	function get_info()
+	{
+		return 'Please select the language you\'d like to use while installing:';
+	}
+	function buildForm()
+	{
+		$this->_formBuilt = true;
+		$this->addElement('select', 'install_language', get_lang('InstallationLanguage'), get_language_folder_list());
+		$buttons[0] = & HTML_QuickForm :: createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
+		$this->addGroup($buttons, 'buttons', '', '&nbsp;', false);
+		$this->setDefaultAction('next');
+	}
+}
+
+/**
+ * Class for requirements page
+ * This checks and informs about some requirements for installing Dokeos:
+ * - necessary and optional extensions
+ * - folders which have to be writable
+ */
+class Page_Requirements extends HTML_QuickForm_Page
+{
+	/**
+	* this function checks if a php extension exists or not
+	*
+	* @param string  $extentionName  name of the php extension to be checked
+	* @param boolean  $echoWhenOk  true => show ok when the extension exists
+	* @author Christophe Gesche
+	*/
+	function check_extension($extentionName)
+	{
+		if (extension_loaded($extentionName))
+		{
+			return '<li>'.$extentionName.' - ok</li>';
+		}
+		else
+		{
+			return '<li><b>'.$extentionName.'</b> <font color="red">is missing (Dokeos can work without)</font> (<a href="http://www.php.net/'.$extentionName.'" target="_blank">'.$extentionName.'</a>)</li>';
+		}
+	}
+	function get_not_writable_folders()
+	{
+		$writable_folders = array ('../inc/conf', '../upload', '../../archive', '../../courses', '../../home');
+		$not_writable = array ();
+		$perm = api_get_setting('permissions_for_new_directories');
+		$perm = octdec(!empty($perm)?$perm:'0770');
+		foreach ($writable_folders as $index => $folder)
+		{
+			if (!is_writable($folder) && !@ chmod($folder, $perm))
+			{
+				$not_writable[] = $folder;
+			}
+		}
+		return $not_writable;
+	}
+	function get_title()
+	{
+		return get_lang("Requirements");
+	}
+	function get_info()
+	{
+		$not_writable = $this->get_not_writable_folders();
+
+		if (count($not_writable) > 0)
+		{
+			$info[] = '<div style="margin:20px;padding:10px;width: 50%;color:#FF6600;border:2px solid #FF6600;">';
+			$info[] = 'Some files or folders don\'t have writing permission. To be able to install Dokeos you should first change their permissions (using CHMOD). Please read the <a href="../../installation_guide.html" target="blank">installation guide</a>.';
+			$info[] = '<ul>';
+			foreach ($not_writable as $index => $folder)
+			{
+				$info[] = '<li>'.$folder.'</li>';
+			}
+			$info[] = '</ul>';
+			$info[] = '</div>';
+			$this->disableNext = true;
+		}
+		elseif (file_exists('../inc/conf/claro_main.conf.php'))
+		{
+			$info[] = '<div style="margin:20px;padding:10px;width: 50%;color:#FF6600;border:2px solid #FF6600;text-align:center;">';
+			$info[] = get_lang("WarningExistingDokeosInstallationDetected");
+			$info[] = '</div>';
+		}
+		$info[] = '<b>'.get_lang("ReadThoroughly").'</b>';
+		$info[] = '<br />';
+		$info[] = get_lang("DokeosNeedFollowingOnServer");
+		$info[] = "<ul>";
+		$info[] = "<li>Webserver with PHP 5.x";
+		$info[] = '<ul>';
+		$info[] = $this->check_extension('standard');
+		$info[] = $this->check_extension('session');
+		$info[] = $this->check_extension('mysql');
+		$info[] = $this->check_extension('zlib');
+		$info[] = $this->check_extension('pcre');
+		$info[] = '</ul></li>';
+		$info[] = "<li>MySQL + login/password allowing to access and create at least one database</li>";
+		$info[] = "<li>Write access to web directory where Dokeos files have been put</li>";
+		$info[] = "</ul>";
+		$info[] = get_lang('MoreDetails').", <a href=\"../../installation_guide.html\" target=\"blank\">read the installation guide</a>.";
+		return implode("\n",$info);
+	}
+	function buildForm()
+	{
+		global $updateFromVersion;
+		$this->_formBuilt = true;
+		$this->addElement('radio', 'installation_type', get_lang('InstallType'), get_lang('NewInstall'), 'new');
+		$update_group[0] = & HTML_QuickForm :: createElement('radio', 'installation_type', null, 'Update from Dokeos '.implode('|', $updateFromVersion).'', 'update');
+		//$this->addGroup($update_group, 'update_group', '', '&nbsp;', false);
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
+		$not_writable = $this->get_not_writable_folders();
+		if (count($not_writable) > 0)
+		{
+			$el = $prevnext[1];
+			$el->updateAttributes('disabled="disabled"');
+		}
+		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
+		$this->setDefaultAction('next');
+	}
+}
+
+/**
+ * Page in the install wizard to select the location of the old Dokeos installation.
+ */
+class Page_LocationOldVersion extends HTML_QuickForm_Page
+{
+	function get_title()
+	{
+		return 'Old version root path';
+	}
+	function get_info()
+	{
+		return 'Give location of your old Dokeos installation ';
+	}
+	function buildForm()
+	{
+		$this->_formBuilt = true;
+		$this->addElement('text', 'old_version_path', 'Old version root path');
+		$this->applyFilter('old_version_path', 'trim');
+		$this->addRule('old_version_path', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addRule('old_version_path', get_lang('BadUpdatePath'), 'callback', 'check_update_path');
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
+		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
+		$this->setDefaultAction('next');
+	}
+}
+
+/**
+ * Class for license page
+ * Displays the GNU GPL license that has to be accepted to install Dokeos.
+ */
+class Page_License extends HTML_QuickForm_Page
+{
+	function get_title()
+	{
+		return get_lang('Licence');
+	}
+	function get_info()
+	{
+		return get_lang('DokeosLicenseInfo');
+	}
+	function buildForm()
+	{
+		$this->_formBuilt = true;
+		$this->addElement('textarea', 'license', get_lang('Licence'), array ('cols' => 80, 'rows' => 20, 'disabled' => 'disabled', 'style'=>'background-color: white;'));
+		$this->addElement('checkbox','license_accept','',get_lang('IAccept'));
+		$this->addRule('license_accept',get_lang('ThisFieldIsRequired'),'required');
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
+		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
+		$this->setDefaultAction('next');
+	}
+}
+
+/**
+ * Class for database settings page
+ * Displays a form where the user can enter the installation settings
+ * regarding the databases - login and password, names, prefixes, single
+ * or multiple databases, tracking or not...
+ */
+class Page_DatabaseSettings extends HTML_QuickForm_Page
+{
+	function get_title()
+	{
+		return get_lang('DBSetting');
+	}
+	function get_info()
+	{
+		return get_lang('DBSettingIntro');
+	}
+	function buildForm()
+	{
+		$this->_formBuilt = true;
+		$this->addElement('text', 'database_host', get_lang("DBHost"), array ('size' => '40'));
+		$this->addRule('database_host', 'ThisFieldIsRequired', 'required');
+		$this->addElement('text', 'database_username', get_lang("DBLogin"), array ('size' => '40'));
+		$this->addElement('password', 'database_password', get_lang("DBPassword"), array ('size' => '40'));
+		$this->addRule(array('database_host','database_username','database_password'),get_lang('CouldNotConnectToDatabase'),new ValidateDatabaseConnection());
+		$this->addElement('text', 'database_prefix', get_lang("DbPrefixForm"), array ('size' => '40'));
+		$this->addElement('text', 'database_main_db', get_lang("MainDB"), array ('size' => '40'));
+		$this->addRule('database_main_db', 'ThisFieldIsRequired', 'required');
+		$this->addElement('text', 'database_tracking', get_lang("StatDB"), array ('size' => '40'));
+		$this->addRule('database_tracking', 'ThisFieldIsRequired', 'required');
+		$this->addElement('text', 'database_scorm', get_lang("ScormDB"), array ('size' => '40'));
+		$this->addRule('database_scorm', 'ThisFieldIsRequired', 'required');
+		$this->addElement('text', 'database_user', get_lang("UserDB"), array ('size' => '40'));
+		$this->addRule('database_user', 'ThisFieldIsRequired', 'required');
+		//$this->addElement('text', 'database_repository', get_lang("RepositoryDatabase"), array ('size' => '40'));
+		//$this->addRule('database_repository', 'ThisFieldIsRequired', 'required');
+		//$this->addElement('text', 'database_weblcms', get_lang("WeblcmsDatabase"), array ('size' => '40'));
+		//$this->addRule('database_weblcms', 'ThisFieldIsRequired', 'required');
+		//$this->addElement('text', 'database_personal_calendar', get_lang("PersonalCalendarDatabase"), array ('size' => '40'));
+		//$this->addRule('database_personal_calendar', 'ThisFieldIsRequired', 'required');
+		//$this->addElement('text', 'database_personal_messenger', get_lang("PersonalMessageDatabase"), array ('size' => '40'));
+		//$this->addRule('database_personal_messenger', 'ThisFieldIsRequired', 'required');
+		//$this->addElement('text', 'database_profiler', get_lang("ProfilerDatabase"), array ('size' => '40'));
+		//$this->addRule('database_profiler', 'ThisFieldIsRequired', 'required');
+
+		$enable_tracking[] = & $this->createElement('radio', 'enable_tracking', null, get_lang("Yes"), 1);
+		$enable_tracking[] = & $this->createElement('radio', 'enable_tracking', null, get_lang("No"), 0);
+		$this->addGroup($enable_tracking, 'tracking', get_lang("EnableTracking"), '&nbsp;', false);
+		$several_db[] = & $this->createElement('radio', 'database_single', null, get_lang("One"),1);
+		$several_db[] = & $this->createElement('radio', 'database_single', null, get_lang("Several"),0);
+		$this->addGroup($several_db, 'db', get_lang("SingleDb"), '&nbsp;', false);
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
+		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
+		$this->setDefaultAction('next');
+	}
+}
+class ValidateDatabaseConnection extends HTML_QuickForm_Rule
+{
+	public function validate($parameters)
+	{
+		$db_host = $parameters[0];
+		$db_user = $parameters[1];
+		$db_password = $parameters[2];
+		if(mysql_connect($db_host,$db_user,$db_password))
+		{
+			return true;
+		}
+		return false;
+	}
+}
+
+/**
+ * Page in the install wizard in which some config settings are asked to the
+ * user.
+ */
+class Page_ConfigSettings extends HTML_QuickForm_Page
+{
+	function get_title()
+	{
+		return get_lang('CfgSetting');
+	}
+	function get_info()
+	{
+		return get_lang('ConfigSettingsInfo');
+	}
+	function buildForm()
+	{
+		$this->_formBuilt = true;
+		$languages = array ();
+		$languages['dutch'] = 'dutch';
+		$this->addElement('select', 'platform_language', get_lang("MainLang"), get_language_folder_list());
+		$this->addElement('text', 'platform_url', get_lang("DokeosURL"), array ('size' => '40'));
+		$this->addRule('platform_url', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addElement('text', 'admin_email', get_lang("AdminEmail"), array ('size' => '40'));
+		$this->addRule('admin_email', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addRule('admin_email', get_lang('WrongEmail'), 'email');
+		$this->addElement('text', 'admin_lastname', get_lang("AdminLastName"), array ('size' => '40'));
+		$this->addRule('admin_lastname', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addElement('text', 'admin_firstname', get_lang("AdminFirstName"), array ('size' => '40'));
+		$this->addRule('admin_firstname', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addElement('text', 'admin_phone', get_lang("AdminPhone"), array ('size' => '40'));
+		$this->addElement('text', 'admin_username', get_lang("AdminLogin"), array ('size' => '40'));
+		$this->addRule('admin_username', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addElement('text', 'admin_password', get_lang("AdminPass"), array ('size' => '40'));
+		$this->addRule('admin_password', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addElement('text', 'platform_name', get_lang("CampusName"), array ('size' => '40'));
+		$this->addRule('platform_name', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addElement('text', 'organization_name', get_lang("InstituteShortName"), array ('size' => '40'));
+		$this->addRule('organization_name', get_lang('ThisFieldIsRequired'), 'required');
+		$this->addElement('text', 'organization_url', get_lang("InstituteURL"), array ('size' => '40'));
+		$this->addRule('organization_url', get_lang('ThisFieldIsRequired'), 'required');
+		$encrypt[] = & $this->createElement('radio', 'encrypt_password', null, get_lang('Yes'), 1);
+		$encrypt[] = & $this->createElement('radio', 'encrypt_password', null, get_lang('No'), 0);
+		$this->addGroup($encrypt, 'tracking', get_lang("EncryptUserPass"), '&nbsp;', false);
+		$self_reg[] = & $this->createElement('radio', 'self_reg', null, get_lang('Yes'), 1);
+		$self_reg[] = & $this->createElement('radio', 'self_reg', null, get_lang('No'), 0);
+		$this->addGroup($self_reg, 'tracking', get_lang("AllowSelfReg"), '&nbsp;', false);
+		$self_reg_teacher[] = & $this->createElement('radio', 'self_reg_teacher', null, get_lang('Yes'), 1);
+		$self_reg_teacher[] = & $this->createElement('radio', 'self_reg_teacher', null, get_lang('No'), 0);
+		$this->addGroup($self_reg_teacher, 'tracking', get_lang("AllowSelfRegProf"), '&nbsp;', false);
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
+		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
+		$this->setDefaultAction('next');
+	}
+}
+
+/**
+ * Page in the install wizard in which a final overview of all settings is
+ * displayed.
+ */
+class Page_ConfirmSettings extends HTML_QuickForm_Page
+{
+	function get_title()
+	{
+		return get_lang('LastCheck');
+	}
+	function get_info()
+	{
+		return 'Here are the values you entered
+				<br />
+				<strong>Print this page to remember your password and other settings</strong>';
+
+	}
+	function buildForm()
+	{
+		$wizard = $this->controller;
+		$values = $wizard->exportValues();
+		$this->addElement('static', 'confirm_platform_language', get_lang("MainLang"), $values['platform_language']);
+		$this->addElement('static', 'confirm_platform_url', get_lang("DokeosURL"), $values['platform_url']);
+		$this->addElement('static', 'confirm_admin_email', get_lang("AdminEmail"), $values['admin_email']);
+		$this->addElement('static', 'confirm_admin_lastname', get_lang("AdminLastName"), $values['admin_lastname']);
+		$this->addElement('static', 'confirm_admin_firstname', get_lang("AdminFirstName"), $values['admin_firstname']);
+		$this->addElement('static', 'confirm_admin_phone', get_lang("AdminPhone"), $values['admin_phone']);
+		$this->addElement('static', 'confirm_admin_username', get_lang("AdminLogin"), $values['admin_username']);
+		$this->addElement('static', 'confirm_admin_password', get_lang("AdminPass"), $values['admin_password']);
+		$this->addElement('static', 'confirm_platform_name', get_lang("CampusName"), $values['platform_name']);
+		$this->addElement('static', 'confirm_organization_name', get_lang("InstituteShortName"), $values['organization_name']);
+		$this->addElement('static', 'confirm_organization_url', get_lang("InstituteURL"), $values['organization_url']);
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('back'), '<< '.get_lang('Previous'));
+		$prevnext[] = & $this->createElement('submit', $this->getButtonName('next'), get_lang('Next').' >>');
+		$this->addGroup($prevnext, 'buttons', '', '&nbsp;', false);
+		$this->setDefaultAction('next');
+	}
+}
+
+
+/**
+ * Class to render a page in the install wizard.
+ */
+class ActionDisplay extends HTML_QuickForm_Action_Display
+{
+	/**
+	 * Displays the HTML-code of a page in the wizard
+	 * @param HTML_Quickform_Page $page The page to display.
+	 */
+	function _renderForm(& $current_page)
+	{
+		global $charset;
+
+		global $dokeos_version, $installType, $updateFromVersion;
+		$renderer = & $current_page->defaultRenderer();
+		$current_page->setRequiredNote('<font color="#FF0000">*</font> '.get_lang('ThisFieldIsRequired'));
+		$element_template = "\n\t<tr>\n\t\t<td valign=\"top\"><!-- BEGIN required --><span style=\"color: #ff0000\">*</span> <!-- END required -->{label}</td>\n\t\t<td valign=\"top\" align=\"left\"><!-- BEGIN error --><span style=\"color: #ff0000;font-size:x-small;margin:2px;\">{error}</span><br /><!-- END error -->\t{element}</td>\n\t</tr>";
+		$renderer->setElementTemplate($element_template);
+		$header_template = "\n\t<tr>\n\t\t<td valign=\"top\" colspan=\"2\">{header}</td>\n\t</tr>";
+		$renderer->setHeaderTemplate($header_template);
+		HTML_QuickForm :: setRequiredNote('<font color="red">*</font> <small>'.get_lang('ThisFieldIsRequired').'</small>');
+		$current_page->accept($renderer);
+?>
+		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+		<head>
+		<title>-- Dokeos - upgrade to version <?php echo $dokeos_version; ?></title>
+		<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset; ?>" />
+		<link rel="stylesheet" href="../css/dokeos_blue/default.css" type="text/css"/>
+		</head>
+		<body dir="<?php echo get_lang('text_dir'); ?>">
+		<div id="header1">
+			Dokeos - upgrade to version <?php echo $dokeos_version; ?><?php if($installType == 'new') echo ' - New installation'; else if($installType == 'update') echo ' - Update from Dokeos '.implode('|',$updateFromVersion); ?>
+		</div>
+		<div style="float: left; background-color:#EFEFEF;margin-right: 20px;padding: 10px;">
+			<img src="../img/bluelogo.gif" alt="logo"/>
+			<?php
+
+		$all_pages = $current_page->controller->_pages;
+		$total_number_of_pages = count($all_pages);
+		$current_page_number = 0;
+		$page_number = 0;
+		echo '<ol>';
+		foreach($all_pages as $index => $page)
+		{
+			$page_number++;
+			if($page->get_title() == $current_page->get_title())
+			{
+				$current_page_number = $page_number;
+				echo '<li style="font-weight: bold;">'.$page->get_title().'</li>';
+			}
+			else
+			{
+				echo '<li>'.$page->get_title().'</li>';
+			}
+		}
+		echo '</ol>';
+		echo '</div>';
+		echo '<div style="margin: 10px;">';
+		echo '<h2>'.get_lang('Step').' '.$current_page_number.' '.get_lang('of').' '.$total_number_of_pages.' &ndash; '.$current_page->get_title().'</h2>';
+		echo '<div>';
+		echo $current_page->get_info();
+		echo '</div>';
+		echo $renderer->toHtml();
+		?>
+        </div>
+        <div style="clear:both;"></div>
+        <div id="footer">
+        &copy; <?php echo $dokeos_version; ?>
+        </div>
+		</body>
+		</html>
+		<?php
+	}
+}
+
+/**
+* Class for form processing
+* Here happens the actual installation action after collecting
+* all the required data.
 */
-
-function display_upgrade_header($text_dir, $dokeos_version, $install_type, $update_from_version)
-{
-	?>
-	<!DOCTYPE html
-		PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-	<html xmlns="http://www.w3.org/1999/xhtml">
-	<head>
-		<title>&mdash; <?php echo get_lang('DokeosInstallation').' &mdash; '.get_lang('Version_').' '.$dokeos_version; ?></title>
-		<style type="text/css" media="screen, projection">
-			/*<![CDATA[*/
-			@import "../css/dokeos_blue/default.css";
-			/*]]>*/
-		</style>
-	<?php if(!empty($charset)){ ?>
-		<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset ?>" />
-	<?php } ?>
-	</head>
-	<body dir="<?php echo $text_dir ?>">
-
-	<div id="header">
-		<div id="header1"><?php echo get_lang('DokeosInstallation').' &mdash; '.get_lang('Version_').' '.$dokeos_version; ?><?php if($install_type == 'new') echo ' &ndash; '.get_lang('NewInstallation'); else if($install_type == 'update') echo ' &ndash; '.get_lang('UpdateFromDokeosVersion').implode('|',$update_from_version); ?></div>
-		<div class="clear"></div>
-		<div id="header2">&nbsp;</div>
-		<div id="header3">&nbsp;</div>
-	</div>
-	<?php
-}
-
-/**
-*	Return a list of language directories.
-*	@todo function does not belong here, move to code library,
-*	also see infocours.php which contains similar function
-*/
-function get_language_folder_list()
-{
-	$dirname = dirname(__FILE__).'/../lang';
-	if ($dirname[strlen($dirname) - 1] != '/')
-		$dirname .= '/';
-	$handle = opendir($dirname);
-	while ($entries = readdir($handle))
-	{
-		if ($entries == '.' || $entries == '..' || $entries == '.svn')
-			continue;
-		if (is_dir($dirname.$entries))
-		{
-			$language_list[$entries] = api_ucfirst($entries);
-		}
-	}
-	closedir($handle);
-	asort($language_list);
-	return $language_list;
-}
-
-
-function display_installation_overview()
-{
-	echo '<div id="installation_steps">';
-	echo '<img src="../img/bluelogo.gif" hspace="10" vspace="10" alt="Dokeos logo" />';
-	echo '<ol>';
-	echo '<li ' . step_active('1') . '> ' . get_lang('InstallationLanguage') . '</li>';
-	echo '<li ' . step_active('2') . '> ' . get_lang('Requirements') . '</li>';
-	echo '<li ' . step_active('3') . '> ' . get_lang('Licence') . '</li>';
-	echo '<li ' . step_active('4') . '> ' . get_lang('DBSetting') . '</li>';
-	echo '<li ' . step_active('5') . '> ' . get_lang('CfgSetting') . '</li>';
-	echo '<li ' . step_active('6') . '> ' . get_lang('PrintOverview') . '</li>';
-	echo '<li ' . step_active('7') . '> ' . get_lang('Installing') . '</li>';
-	echo '</ol>';
-	echo '</div>';
-}
-
-/**
- * This function prints class=active_step $current_step=$param
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- */
-function step_active($this_step)
-{
-	global $current_active_step;
-	if ($current_active_step == $this_step)
-	{
-		return ' class="current_step" ';
-	}
-}
-
-// Rule to check update path
-function check_update_path($path)
-{
-	global $update_from_version;
-	// Make sure path has a trailing /
-	$path = substr($path,-1) != '/' ? $path.'/' : $path;
-	// Check the path
-	if (file_exists($path))
-	{
-		//search for 1.6.x installation
-		$version = get_installed_version($path, 'platformVersion');
-
-		//search for 1.8.x installation
-		//if (! isset($version) || $version == '')
-		//{
-		//   $version = get_installed_version($path, 'dokeos_version');
-		//}
-
-		if (in_array($version, $update_from_version))
-		{
-			return true;
-		}
-		else
-		{
-			return false;
-		}
-	}
-	return false;
-}
-
-/**
- * This function returns the installed version of
- * the older installation to upgrade by checking the
- * claroline/inc/installedVersion.inc.php file.
- */
-function get_installed_version($old_installation_path, $parameter)
-{
-	if( file_exists($old_installation_path.'claroline/inc/installedVersion.inc.php') )
-	{
-		$version_info_file = 'claroline/inc/installedVersion.inc.php';
-	}
-	// with include_once inside a function, variables aren't remembered for later use
-	include($old_installation_path.$version_info_file);
-	if (isset($$parameter))
-	{
-		return $$parameter;
-	}
-}
-
-/**
- * This function returns a the value of a parameter from the configuration file
- * of a previous installation.
- *
- * IMPORTANT
- * - Before Dokeos 1.8 the main code folder was called 'claroline'. Since Dokeos 1.8
+class ActionProcess extends HTML_QuickForm_Action
+{
+	function perform(& $page, $actionName)
+	{
+		global $charset;
+
+		global $dokeos_version, $installType, $updateFromVersion;
+		$values = $page->controller->exportValues();
+		?>
+		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+		<head>
+		<title>-- Dokeos installation -- version <?php echo $dokeos_version; ?></title>
+		<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset; ?>" />
+		<link rel="stylesheet" href="../css/dokeos_blue/default.css" type="text/css"/>
+		</head>
+		<body dir="<?php echo get_lang('text_dir'); ?>">
+		<div style="background-color:#4171B5;color:white;font-size:x-large;">
+			Dokeos installation - version <?php echo $dokeos_version; ?><?php if($installType == 'new') echo ' - New installation'; else if($installType == 'update') echo ' - Update from Dokeos '.implode('|',$updateFromVersion); ?>
+		</div>
+		<div style="margin:50px;">
+			<img src="../img/bluelogo.gif" alt="logo" align="right"/>
+		<?php
+		echo '<pre>';
+
+		global $repository_database;
+		global $weblcms_database;
+		global $personal_calendar_database;
+		global $user_database;
+		global $personal_messenger_database;
+		global $profiler_database;
+
+		$repository_database = $values['database_repository'];
+		$weblcms_database = $values['database_weblcms'];
+		$personal_calendar_database = $values['database_personal_calendar'];
+		$user_database = $values['database_user'];
+		$personal_messenger_database = $values['database_personal_messenger'];
+		$profiler_database = $values['database_profiler'];
+
+		/*full_database_install($values);
+		full_file_install($values);
+		create_admin_in_user_table($values);
+		create_default_categories_in_weblcms();*/
+		echo "<p>Performing upgrade to latest version....</p>";
+
+		//upgrade_16x_to_180($values);
+
+		echo '</pre>';
+		$page->controller->container(true);
+		?>
+		<a class="portal" href="../../index.php"><?php echo get_lang('GoToYourNewlyCreatedPortal'); ?></a>
+        </div>
+		</body>
+		</html>
+		<?php
+	}
+}
+
+
+/*
+==============================================================================
+		FUNCTIONS
+==============================================================================
+*/
+
+function display_upgrade_header($text_dir, $dokeos_version, $install_type, $update_from_version)
+{
+	?>
+	<!DOCTYPE html
+		PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+	<html xmlns="http://www.w3.org/1999/xhtml">
+	<head>
+		<title>&mdash; <?php echo get_lang('DokeosInstallation').' &mdash; '.get_lang('Version_').' '.$dokeos_version; ?></title>
+		<style type="text/css" media="screen, projection">
+			/*<![CDATA[*/
+			@import "../css/dokeos_blue/default.css";
+			/*]]>*/
+		</style>
+	<?php if(!empty($charset)){ ?>
+		<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $charset ?>" />
+	<?php } ?>
+	</head>
+	<body dir="<?php echo $text_dir ?>">
+
+	<div id="header">
+		<div id="header1"><?php echo get_lang('DokeosInstallation').' &mdash; '.get_lang('Version_').' '.$dokeos_version; ?><?php if($install_type == 'new') echo ' &ndash; '.get_lang('NewInstallation'); else if($install_type == 'update') echo ' &ndash; '.get_lang('UpdateFromDokeosVersion').implode('|',$update_from_version); ?></div>
+		<div class="clear"></div>
+		<div id="header2">&nbsp;</div>
+		<div id="header3">&nbsp;</div>
+	</div>
+	<?php
+}
+
+/**
+*	Return a list of language directories.
+*	@todo function does not belong here, move to code library,
+*	also see infocours.php which contains similar function
+*/
+function get_language_folder_list()
+{
+	$dirname = dirname(__FILE__).'/../lang';
+	if ($dirname[strlen($dirname) - 1] != '/')
+		$dirname .= '/';
+	$handle = opendir($dirname);
+	while ($entries = readdir($handle))
+	{
+		if ($entries == '.' || $entries == '..' || $entries == '.svn')
+			continue;
+		if (is_dir($dirname.$entries))
+		{
+			$language_list[$entries] = api_ucfirst($entries);
+		}
+	}
+	closedir($handle);
+	asort($language_list);
+	return $language_list;
+}
+
+
+function display_installation_overview()
+{
+	echo '<div id="installation_steps">';
+	echo '<img src="../img/bluelogo.gif" hspace="10" vspace="10" alt="Dokeos logo" />';
+	echo '<ol>';
+	echo '<li ' . step_active('1') . '> ' . get_lang('InstallationLanguage') . '</li>';
+	echo '<li ' . step_active('2') . '> ' . get_lang('Requirements') . '</li>';
+	echo '<li ' . step_active('3') . '> ' . get_lang('Licence') . '</li>';
+	echo '<li ' . step_active('4') . '> ' . get_lang('DBSetting') . '</li>';
+	echo '<li ' . step_active('5') . '> ' . get_lang('CfgSetting') . '</li>';
+	echo '<li ' . step_active('6') . '> ' . get_lang('PrintOverview') . '</li>';
+	echo '<li ' . step_active('7') . '> ' . get_lang('Installing') . '</li>';
+	echo '</ol>';
+	echo '</div>';
+}
+
+/**
+ * This function prints class=active_step $current_step=$param
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+ */
+function step_active($this_step)
+{
+	global $current_active_step;
+	if ($current_active_step == $this_step)
+	{
+		return ' class="current_step" ';
+	}
+}
+
+// Rule to check update path
+function check_update_path($path)
+{
+	global $update_from_version;
+	// Make sure path has a trailing /
+	$path = substr($path,-1) != '/' ? $path.'/' : $path;
+	// Check the path
+	if (file_exists($path))
+	{
+		//search for 1.6.x installation
+		$version = get_installed_version($path, 'platformVersion');
+
+		//search for 1.8.x installation
+		//if (! isset($version) || $version == '')
+		//{
+		//   $version = get_installed_version($path, 'dokeos_version');
+		//}
+
+		if (in_array($version, $update_from_version))
+		{
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}
+	return false;
+}
+
+/**
+ * This function returns the installed version of
+ * the older installation to upgrade by checking the
+ * claroline/inc/installedVersion.inc.php file.
+ */
+function get_installed_version($old_installation_path, $parameter)
+{
+	if( file_exists($old_installation_path.'claroline/inc/installedVersion.inc.php') )
+	{
+		$version_info_file = 'claroline/inc/installedVersion.inc.php';
+	}
+	// with include_once inside a function, variables aren't remembered for later use
+	include($old_installation_path.$version_info_file);
+	if (isset($$parameter))
+	{
+		return $$parameter;
+	}
+}
+
+/**
+ * This function returns a the value of a parameter from the configuration file
+ * of a previous installation.
+ *
+ * IMPORTANT
+ * - Before Dokeos 1.8 the main code folder was called 'claroline'. Since Dokeos 1.8
  * this folder is called 'main' -> we have to make a difference based on previous
- * version.
+ * version.
  * - The version may be in the config file or in the installedVersion file...
- *
- * WARNING - this function relies heavily on global variables $updateFromConfigFile
- * and $configFile, and also changes these globals. This can be rewritten.
- *
- * @param string  $param  the parameter which the value is returned for
- * @return  string  the value of the parameter
- * @author Olivier Brouckaert
- */
-function get_config_param($param,$path)
-{
-	global $configFile, $updateFromConfigFile;
-
-	if (empty ($updateFromConfigFile))
-	{
-		if (file_exists($path.'claroline/include/config.inc.php'))
-		{
-			$updateFromConfigFile = 'claroline/include/config.inc.php';
-		}
-		elseif (file_exists($path.'claroline/inc/conf/claro_main.conf.php'))
-		{
-			$updateFromConfigFile = 'claroline/inc/conf/claro_main.conf.php';
-		}
-		else
-		{
-			return;
-		}
-	}
-
-	//echo "reading from file $path$updateFromConfigFile, which exists...";
-
-	if (is_array($configFile) && isset ($configFile[$param]))
-	{
-		return $configFile[$param];
-	}
-	elseif (file_exists($path.$updateFromConfigFile))
-	{
-		$configFile = array ();
-
-		$temp = file($path.$updateFromConfigFile);
-
-		$val = '';
-
-		foreach ($temp as $enreg)
-		{
-			if (strstr($enreg, '='))
-			{
-				$enreg = explode('=', $enreg);
-
-				if ($enreg[0][0] == '$')
-				{
-					list ($enreg[1]) = explode(' //', $enreg[1]);
-
-					$enreg[0] = trim(str_replace('$', '', $enreg[0]));
-					$enreg[1] = str_replace('\"', '"', ereg_replace('(^"|"$)', '', substr(trim($enreg[1]), 0, -1)));
-
-					if (strtolower($enreg[1]) == 'true')
-					{
-						$enreg[1] = 1;
-					}
-					if (strtolower($enreg[1]) == 'false')
-					{
-						$enreg[1] = 0;
-					}
-					else
-					{
-						$implode_string = ' ';
-
-						if (!strstr($enreg[1], '." ".') && strstr($enreg[1], '.$'))
-						{
-							$enreg[1] = str_replace('.$', '." ".$', $enreg[1]);
-							$implode_string = '';
-						}
-
-						$tmp = explode('." ".', $enreg[1]);
-
-						foreach ($tmp as $tmp_key => $tmp_val)
-						{
-							if (eregi('^\$[a-z_][a-z0-9_]*$', $tmp_val))
-							{
-								$tmp[$tmp_key] = get_config_param(str_replace('$', '', $tmp_val), $path);
-							}
-						}
-
-						$enreg[1] = implode($implode_string, $tmp);
-					}
-
-					$configFile[$enreg[0]] = $enreg[1];
-
-					if ($enreg[0] == $param)
-					{
-						$val = $enreg[1];
-					}
-				}
-			}
-		}
-
-		return $val;
-	}
-}
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
+ *
+ * WARNING - this function relies heavily on global variables $updateFromConfigFile
+ * and $configFile, and also changes these globals. This can be rewritten.
+ *
+ * @param string  $param  the parameter which the value is returned for
+ * @return  string  the value of the parameter
+ * @author Olivier Brouckaert
+ */
+function get_config_param($param,$path)
+{
+	global $configFile, $updateFromConfigFile;
+
+	if (empty ($updateFromConfigFile))
+	{
+		if (file_exists($path.'claroline/include/config.inc.php'))
+		{
+			$updateFromConfigFile = 'claroline/include/config.inc.php';
+		}
+		elseif (file_exists($path.'claroline/inc/conf/claro_main.conf.php'))
+		{
+			$updateFromConfigFile = 'claroline/inc/conf/claro_main.conf.php';
+		}
+		else
+		{
+			return;
+		}
+	}
+
+	//echo "reading from file $path$updateFromConfigFile, which exists...";
+
+	if (is_array($configFile) && isset ($configFile[$param]))
+	{
+		return $configFile[$param];
+	}
+	elseif (file_exists($path.$updateFromConfigFile))
+	{
+		$configFile = array ();
+
+		$temp = file($path.$updateFromConfigFile);
+
+		$val = '';
+
+		foreach ($temp as $enreg)
+		{
+			if (strstr($enreg, '='))
+			{
+				$enreg = explode('=', $enreg);
+
+				if ($enreg[0][0] == '$')
+				{
+					list ($enreg[1]) = explode(' //', $enreg[1]);
+
+					$enreg[0] = trim(str_replace('$', '', $enreg[0]));
+					$enreg[1] = str_replace('\"', '"', ereg_replace('(^"|"$)', '', substr(trim($enreg[1]), 0, -1)));
+
+					if (strtolower($enreg[1]) == 'true')
+					{
+						$enreg[1] = 1;
+					}
+					if (strtolower($enreg[1]) == 'false')
+					{
+						$enreg[1] = 0;
+					}
+					else
+					{
+						$implode_string = ' ';
+
+						if (!strstr($enreg[1], '." ".') && strstr($enreg[1], '.$'))
+						{
+							$enreg[1] = str_replace('.$', '." ".$', $enreg[1]);
+							$implode_string = '';
+						}
+
+						$tmp = explode('." ".', $enreg[1]);
+
+						foreach ($tmp as $tmp_key => $tmp_val)
+						{
+							if (eregi('^\$[a-z_][a-z0-9_]*$', $tmp_val))
+							{
+								$tmp[$tmp_key] = get_config_param(str_replace('$', '', $tmp_val), $path);
+							}
+						}
+
+						$enreg[1] = implode($implode_string, $tmp);
+					}
+
+					$configFile[$enreg[0]] = $enreg[1];
+
+					if ($enreg[0] == $param)
+					{
+						$val = $enreg[1];
+					}
+				}
+			}
+		}
+
+		return $val;
+	}
+}
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
 */
-global $current_active_step;
-$current_active_step = '1';
-$install_type = 'update';
-//display_upgrade_header($text_dir, $dokeos_version, $install_type, $update_from_version);
-//display_installation_overview();
-
-// Create a new wizard
-$wizard = & new HTML_QuickForm_Controller('regWizard', true);
-
-//Add pages to wizard - path to follow for upgrade
-//$wizard->addPage(new Page_Language('page_language'));
-//$wizard->addPage(new Page_Requirements('page_requirements'));
-$wizard->addPage(new Page_LocationOldVersion('page_location_old_version'));
-$values = $wizard->exportValues();
-if( isset($values['old_version_path']) && $values['old_version_path'] != '/var/www/html/old_version/' )
-{
-	$path = $values['old_version_path'];
-	$defaults['platform_language'] = get_config_param('platformLanguage',$path);
-	$defaults['platform_url'] = 'http://'.$_SERVER['HTTP_HOST'].$urlAppendPath.'/';
-	//to keep debug output readable:
-	//$defaults['license'] = 'GNU GPL v2';
-	//actual license:
-	$defaults['license'] = implode("\n", file('../../documentation/license.txt'));
-	$defaults['database_host'] = get_config_param('dbHost',$path);
-	$defaults['database_main_db'] = get_config_param('mainDbName',$path);
-	$defaults['database_tracking'] = get_config_param('statsDbName',$path);
-	$defaults['database_scorm'] = get_config_param('scormDbName',$path);
-	$defaults['database_user'] = get_config_param('user_personal_database',$path);
-	//$defaults['database_repository'] = 'dokeos_repository';
-	//$defaults['database_weblcms'] = 'dokeos_weblcms';
-	$defaults['database_username'] = get_config_param('dbLogin',$path);
-	$defaults['database_password'] = get_config_param('dbPass',$path);
-	$defaults['database_prefix'] = get_config_param('dbNamePrefix',$path);
-	$defaults['enable_tracking'] = get_config_param('is_trackingEnabled',$path);
-	$defaults['database_single'] = get_config_param('singleDbEnabled',$path);
-	$defaults['admin_lastname'] = 'Doe';
-	$defaults['admin_firstname'] = mt_rand(0,1)?'John':'Jane';
-	$defaults['admin_email'] = get_config_param('emailAdministrator',$path);
-	$defaults['admin_username'] = 'admin';
-	$defaults['admin_password'] = api_generate_password();
-	$defaults['admin_phone'] = get_config_param('administrator["phone"]',$path);
-	$defaults['platform_name'] = get_config_param('siteName',$path);
-	$defaults['encrypt_password'] = 1;
-	$defaults['organization_name'] = get_config_param('institution["name"]',$path);
-	$defaults['organization_url'] = get_config_param('institution["url"]',$path);
-	if (get_config_param('userPasswordCrypted',$path)==1) {
-		$defaults['encrypt_password'] = 'md5';
-	} elseif (get_config_param('userPasswordCrypted',$path)==0){
-		$defaults['encrypt_password'] = 'none';
-	}
-	//$defaults['encrypt_password'] = get_config_param('userPasswordCrypted',$path);
-	$defaults['self_reg'] = get_config_param('allowSelfReg',$path);
-}
-else
-{
-	//old version path not correct yet
-}
-
-$wizard->addPage(new Page_License('page_license'));
-$wizard->addPage(new Page_DatabaseSettings('page_databasesettings'));
-$wizard->addPage(new Page_ConfigSettings('page_configsettings'));
-$wizard->addPage(new Page_ConfirmSettings('page_confirmsettings'));
-
-$defaults['install_language'] = 'english';
-//$defaults['old_version_path'] = '/var/www/html/old_version/';
-$defaults['old_version_path'] = '';
-
-// Set the default values
-$wizard->setDefaults($defaults);
-
-// Add the process action to the wizard
-$wizard->addAction('process', new ActionProcess());
-
-// Add the display action to the wizard
-$wizard->addAction('display', new ActionDisplay());
-
-// Set the installation language
-$install_language = $wizard->exportValue('page_language', 'install_language');
-require_once ('../lang/english/trad4all.inc.php');
-require_once ('../lang/english/install.inc.php');
-include_once ("../lang/$install_language/trad4all.inc.php");
-include_once ("../lang/$install_language/install.inc.php");
-
-// Set default platform language to the selected install language
-$defaults['platform_language'] = $install_language;
-$wizard->setDefaults($defaults);
-
-// Start the wizard
-$wizard->run();
-
-// Set the installation language
-$install_language = $wizard->exportValue('page_language', 'install_language');
-require_once ('../lang/english/trad4all.inc.php');
-require_once ('../lang/english/install.inc.php');
-include_once ("../lang/$install_language/trad4all.inc.php");
-include_once ("../lang/$install_language/install.inc.php");
-
-//$values = $wizard->exportValues();
-
-?>
+global $current_active_step;
+$current_active_step = '1';
+$install_type = 'update';
+//display_upgrade_header($text_dir, $dokeos_version, $install_type, $update_from_version);
+//display_installation_overview();
+
+// Create a new wizard
+$wizard = & new HTML_QuickForm_Controller('regWizard', true);
+
+//Add pages to wizard - path to follow for upgrade
+//$wizard->addPage(new Page_Language('page_language'));
+//$wizard->addPage(new Page_Requirements('page_requirements'));
+$wizard->addPage(new Page_LocationOldVersion('page_location_old_version'));
+$values = $wizard->exportValues();
+if( isset($values['old_version_path']) && $values['old_version_path'] != '/var/www/html/old_version/' )
+{
+	$path = $values['old_version_path'];
+	$defaults['platform_language'] = get_config_param('platformLanguage',$path);
+	$defaults['platform_url'] = 'http://'.$_SERVER['HTTP_HOST'].$urlAppendPath.'/';
+	//to keep debug output readable:
+	//$defaults['license'] = 'GNU GPL v2';
+	//actual license:
+	$defaults['license'] = implode("\n", file('../../documentation/license.txt'));
+	$defaults['database_host'] = get_config_param('dbHost',$path);
+	$defaults['database_main_db'] = get_config_param('mainDbName',$path);
+	$defaults['database_tracking'] = get_config_param('statsDbName',$path);
+	$defaults['database_scorm'] = get_config_param('scormDbName',$path);
+	$defaults['database_user'] = get_config_param('user_personal_database',$path);
+	//$defaults['database_repository'] = 'dokeos_repository';
+	//$defaults['database_weblcms'] = 'dokeos_weblcms';
+	$defaults['database_username'] = get_config_param('dbLogin',$path);
+	$defaults['database_password'] = get_config_param('dbPass',$path);
+	$defaults['database_prefix'] = get_config_param('dbNamePrefix',$path);
+	$defaults['enable_tracking'] = get_config_param('is_trackingEnabled',$path);
+	$defaults['database_single'] = get_config_param('singleDbEnabled',$path);
+	$defaults['admin_lastname'] = 'Doe';
+	$defaults['admin_firstname'] = mt_rand(0,1)?'John':'Jane';
+	$defaults['admin_email'] = get_config_param('emailAdministrator',$path);
+	$defaults['admin_username'] = 'admin';
+	$defaults['admin_password'] = api_generate_password();
+	$defaults['admin_phone'] = get_config_param('administrator["phone"]',$path);
+	$defaults['platform_name'] = get_config_param('siteName',$path);
+	$defaults['encrypt_password'] = 1;
+	$defaults['organization_name'] = get_config_param('institution["name"]',$path);
+	$defaults['organization_url'] = get_config_param('institution["url"]',$path);
+	if (get_config_param('userPasswordCrypted',$path)==1) {
+		$defaults['encrypt_password'] = 'md5';
+	} elseif (get_config_param('userPasswordCrypted',$path)==0){
+		$defaults['encrypt_password'] = 'none';
+	}
+	//$defaults['encrypt_password'] = get_config_param('userPasswordCrypted',$path);
+	$defaults['self_reg'] = get_config_param('allowSelfReg',$path);
+}
+else
+{
+	//old version path not correct yet
+}
+
+$wizard->addPage(new Page_License('page_license'));
+$wizard->addPage(new Page_DatabaseSettings('page_databasesettings'));
+$wizard->addPage(new Page_ConfigSettings('page_configsettings'));
+$wizard->addPage(new Page_ConfirmSettings('page_confirmsettings'));
+
+$defaults['install_language'] = 'english';
+//$defaults['old_version_path'] = '/var/www/html/old_version/';
+$defaults['old_version_path'] = '';
+
+// Set the default values
+$wizard->setDefaults($defaults);
+
+// Add the process action to the wizard
+$wizard->addAction('process', new ActionProcess());
+
+// Add the display action to the wizard
+$wizard->addAction('display', new ActionDisplay());
+
+// Set the installation language
+$install_language = $wizard->exportValue('page_language', 'install_language');
+require_once ('../lang/english/trad4all.inc.php');
+require_once ('../lang/english/install.inc.php');
+include_once ("../lang/$install_language/trad4all.inc.php");
+include_once ("../lang/$install_language/install.inc.php");
+
+// Set default platform language to the selected install language
+$defaults['platform_language'] = $install_language;
+$wizard->setDefaults($defaults);
+
+// Start the wizard
+$wizard->run();
+
+// Set the installation language
+$install_language = $wizard->exportValue('page_language', 'install_language');
+require_once ('../lang/english/trad4all.inc.php');
+require_once ('../lang/english/install.inc.php');
+include_once ("../lang/$install_language/trad4all.inc.php");
+include_once ("../lang/$install_language/install.inc.php");
+
+//$values = $wizard->exportValues();
+
+?>

+ 388 - 388
main/messages/message.class.php

@@ -1,466 +1,466 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2009 Dokeos SPRL
-	Copyright (c) Julio Montoya <gugli100@gmail.com>
-
-	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
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2009 Dokeos SPRL
+	Copyright (c) Julio Montoya <gugli100@gmail.com>
+
+	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 api_get_path(LIBRARY_PATH).'/main_api.lib.php';
+require_once api_get_path(LIBRARY_PATH).'/online.inc.php';
 
-==============================================================================
-*/
-require_once api_get_path(LIBRARY_PATH).'/main_api.lib.php';
-require_once api_get_path(LIBRARY_PATH).'/online.inc.php';
-
 class MessageManager
 {
-	function MessageManager() {
+	function MessageManager() {
 
-	}
-	public static function get_online_user_list($current_user_id) {
-		$min=30;
-		global $_configuration;
-		$userlist = WhoIsOnline($current_user_id,$_configuration['statistics_database'],$min);
-		foreach($userlist as $row) {
-			$receiver_id = $row[0];
-			$online_user_list[$receiver_id] = GetFullUserName($receiver_id).($current_user_id==$receiver_id?("&nbsp;(".get_lang('Myself').")"):(""));
-		}
-		return $online_user_list;
-	}
+	}
+	public static function get_online_user_list($current_user_id) {
+		$min=30;
+		global $_configuration;
+		$userlist = WhoIsOnline($current_user_id,$_configuration['statistics_database'],$min);
+		foreach($userlist as $row) {
+			$receiver_id = $row[0];
+			$online_user_list[$receiver_id] = GetFullUserName($receiver_id).($current_user_id==$receiver_id?("&nbsp;(".get_lang('Myself').")"):(""));
+		}
+		return $online_user_list;
+	}
 
-	/**
-	* Displays info stating that the message is sent successfully.
-	*/
-	public static function display_success_message($uid) {
-			global $charset;
-		if ($_SESSION['social_exist']===true) {
+	/**
+	* Displays info stating that the message is sent successfully.
+	*/
+	public static function display_success_message($uid) {
+			global $charset;
+		if ($_SESSION['social_exist']===true) {
 			$redirect="#remote-tab-2";
-			if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
-				$success=get_lang('MessageSentTo').
-				"&nbsp;<b>".
-				GetFullUserName($uid).
-				"</b>";
-			}else {
-				$success=get_lang('MessageSentTo').
-				"&nbsp;<b>".
-				GetFullUserName($uid).
+			if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
+				$success=get_lang('MessageSentTo').
+				"&nbsp;<b>".
+				GetFullUserName($uid).
+				"</b>";
+			}else {
+				$success=get_lang('MessageSentTo').
+				"&nbsp;<b>".
+				GetFullUserName($uid).
 				"</b>";
 			}
-		} else {
-				$success=get_lang('MessageSentTo').
-				"&nbsp;<b>".
-				GetFullUserName($uid).
-				"</b>";
-		}
-		Display::display_confirmation_message(api_xml_http_response_encode($success), false);
-	}
+		} else {
+				$success=get_lang('MessageSentTo').
+				"&nbsp;<b>".
+				GetFullUserName($uid).
+				"</b>";
+		}
+		Display::display_confirmation_message(api_xml_http_response_encode($success), false);
+	}
 
-	/**
-	* Displays the wysiwyg html editor.
-	*/
-	public static function display_html_editor_area($name, $resp) {
-		api_disp_html_area($name, get_lang('TypeYourMessage'), '', '', null, array('ToolbarSet' => 'Messages', 'Width' => '95%', 'Height' => '250'));
-	}
+	/**
+	* Displays the wysiwyg html editor.
+	*/
+	public static function display_html_editor_area($name, $resp) {
+		api_disp_html_area($name, get_lang('TypeYourMessage'), '', '', null, array('ToolbarSet' => 'Messages', 'Width' => '95%', 'Height' => '250'));
+	}
 
-	/**
-	* Get the new messages for the current user from the database.
-	*/
-	public static function get_new_messages() {
+	/**
+	* Get the new messages for the current user from the database.
+	*/
+	public static function get_new_messages() {
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		if (!api_get_user_id()) {
-			return false;
-		}
+		if (!api_get_user_id()) {
+			return false;
+		}
 		$i=0;
-		$query = "SELECT * FROM $table_message WHERE user_receiver_id=".api_get_user_id()." AND msg_status=1";
-		$result = Database::query($query,__FILE__,__LINE__);
-		$i = Database::num_rows($result);
-		return $i;
-	}
+		$query = "SELECT * FROM $table_message WHERE user_receiver_id=".api_get_user_id()." AND msg_status=1";
+		$result = Database::query($query,__FILE__,__LINE__);
+		$i = Database::num_rows($result);
+		return $i;
+	}
 
-	/**
-	* Get the list of user_ids of users who are online.
-	*/
-	public static function users_connected_by_id() {
-		global $_configuration, $_user;
-		$minute=30;
-		$user_connect = WhoIsOnline($_user['user_id'],$_configuration['statistics_database'],$minute);
-		for ($i=0; $i<count($user_connect); $i++) {
-			$user_id_list[$i]=$user_connect[$i][0];
-		}
-		return $user_id_list;
-	}
+	/**
+	* Get the list of user_ids of users who are online.
+	*/
+	public static function users_connected_by_id() {
+		global $_configuration, $_user;
+		$minute=30;
+		$user_connect = WhoIsOnline($_user['user_id'],$_configuration['statistics_database'],$minute);
+		for ($i=0; $i<count($user_connect); $i++) {
+			$user_id_list[$i]=$user_connect[$i][0];
+		}
+		return $user_id_list;
+	}
 
-	/**
-	 * Gets the total number of messages, used for the inbox sortable table
-	 */
-	public static function get_number_of_messages () {
+	/**
+	 * Gets the total number of messages, used for the inbox sortable table
+	 */
+	public static function get_number_of_messages () {
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$sql_query = "SELECT COUNT(*) as number_messages FROM $table_message WHERE msg_status IN (0,1) AND user_receiver_id=".api_get_user_id();
-		$sql_result = Database::query($sql_query,__FILE__,__LINE__);
-		$result = Database::fetch_array($sql_result);
-		return $result['number_messages'];
-	}
+		$sql_query = "SELECT COUNT(*) as number_messages FROM $table_message WHERE msg_status IN (0,1) AND user_receiver_id=".api_get_user_id();
+		$sql_result = Database::query($sql_query,__FILE__,__LINE__);
+		$result = Database::fetch_array($sql_result);
+		return $result['number_messages'];
+	}
 
-	/**
-	 * Gets information about some messages, used for the inbox sortable table
-	 * @param int $from
-	 * @param int $number_of_items
-	 * @param string $direction
-	 */
-	public static function get_message_data ($from, $number_of_items, $column, $direction) {
-		global $charset;
-		$from = intval($from);
-		$number_of_items = intval($number_of_items);
-		$column = intval($column);
-		if (!in_array($direction, array('ASC', 'DESC')))
+	/**
+	 * Gets information about some messages, used for the inbox sortable table
+	 * @param int $from
+	 * @param int $number_of_items
+	 * @param string $direction
+	 */
+	public static function get_message_data ($from, $number_of_items, $column, $direction) {
+		global $charset;
+		$from = intval($from);
+		$number_of_items = intval($number_of_items);
+		$column = intval($column);
+		if (!in_array($direction, array('ASC', 'DESC')))
 			$direction = 'ASC';
 
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$request=api_is_xml_http_request();
-		$sql_query = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, msg_status as col4 FROM $table_message " .
-					 "WHERE user_receiver_id=".api_get_user_id()." AND msg_status IN (0,1)" .
-					 "ORDER BY send_date desc, col$column $direction LIMIT $from,$number_of_items";
-		$sql_result = Database::query($sql_query,__FILE__,__LINE__);
-		$i = 0;
-		$message_list = array ();
-		while ($result = Database::fetch_row($sql_result)) {
-			if ($request===true) {
+		$request=api_is_xml_http_request();
+		$sql_query = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, msg_status as col4 FROM $table_message " .
+					 "WHERE user_receiver_id=".api_get_user_id()." AND msg_status IN (0,1)" .
+					 "ORDER BY send_date desc, col$column $direction LIMIT $from,$number_of_items";
+		$sql_result = Database::query($sql_query,__FILE__,__LINE__);
+		$i = 0;
+		$message_list = array ();
+		while ($result = Database::fetch_row($sql_result)) {
+			if ($request===true) {
 				$message[0] = '<input type="checkbox" value='.$result[0].' name="id[]">';
-			 } else {
+			 } else {
 				$message[0] = ($result[0]);
-			 }
+			 }
 
-			if ($request===true) {
-				if($result[4]==0)
+			if ($request===true) {
+				if($result[4]==0)
             	{
-					$message[1] = Display::return_icon('mail_open.png',get_lang('AlreadyReadMessage'));//Message already read
-				}
-				else
-				{
+					$message[1] = Display::return_icon('mail_open.png',get_lang('AlreadyReadMessage'));//Message already read
+				}
+				else
+				{
 					$message[1] = Display::return_icon('mail.png',get_lang('UnReadMessage'));//Message without reading
-				}
+				}
 
-				$message[2] = '<a onclick="get_action_url_and_show_messages(1,'.$result[0].')" href="javascript:void(0)">'.GetFullUserName($result[1]).'</a>';
-				$message[3] = '<a onclick="get_action_url_and_show_messages(1,'.$result[0].')" href="javascript:void(0)">'.str_replace("\\","",$result[2]).'</a>';
-				$message[5] = '<a onclick="reply_to_messages(\'show\','.$result[0].',\'\')" href="javascript:void(0)">'.Display::return_icon('message_reply.png',get_lang('ReplyToMessage')).'</a>'.
-						  '&nbsp;&nbsp;<a onclick="delete_one_message('.$result[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',get_lang('DeleteMessage')).'</a>';
-			} else {
-				$message[2] = '<a href="view_message.php?id='.$result[0].'">'.GetFullUserName(($result[1])).'</a>';;
-				$message[3] = '<a href="view_message.php?id='.$result[0].'">'.$result[2].'</a>';
-				$message[5] = '<a href="new_message.php?re_id='.$result[0].'">'.Display::return_icon('message_reply.png',get_lang('ReplyToMessage')).'</a>'.
+				$message[2] = '<a onclick="get_action_url_and_show_messages(1,'.$result[0].')" href="javascript:void(0)">'.GetFullUserName($result[1]).'</a>';
+				$message[3] = '<a onclick="get_action_url_and_show_messages(1,'.$result[0].')" href="javascript:void(0)">'.str_replace("\\","",$result[2]).'</a>';
+				$message[5] = '<a onclick="reply_to_messages(\'show\','.$result[0].',\'\')" href="javascript:void(0)">'.Display::return_icon('message_reply.png',get_lang('ReplyToMessage')).'</a>'.
+						  '&nbsp;&nbsp;<a onclick="delete_one_message('.$result[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',get_lang('DeleteMessage')).'</a>';
+			} else {
+				$message[2] = '<a href="view_message.php?id='.$result[0].'">'.GetFullUserName(($result[1])).'</a>';;
+				$message[3] = '<a href="view_message.php?id='.$result[0].'">'.$result[2].'</a>';
+				$message[5] = '<a href="new_message.php?re_id='.$result[0].'">'.Display::return_icon('message_reply.png',get_lang('ReplyToMessage')).'</a>'.
 						  '&nbsp;&nbsp;<a delete_one_message('.$result[0].') href="#inbox.php?action=deleteone&id='.$result[0].'">'.Display::return_icon('message_delete.png',get_lang('DeleteMessage')).'</a>';
-			}
-			$message[4] = ($result[3]); //date stays the same
-			foreach($message as $key => $value) {
-				$message[$key] = api_xml_http_response_encode($value);
-			}
-			$message_list[] = $message;
+			}
+			$message[4] = ($result[3]); //date stays the same
+			foreach($message as $key => $value) {
+				$message[$key] = api_xml_http_response_encode($value);
+			}
+			$message_list[] = $message;
 
-			$i++;
-		}
-		return $message_list;
-	}
+			$i++;
+		}
+		return $message_list;
+	}
 
-	 public static function send_message ($receiver_user_id, $title, $content) {
-        global $charset;
-        if (is_numeric($receiver_user_id)) {
-			$table_message = Database::get_main_table(TABLE_MESSAGE);
-	        $title = api_convert_encoding($title,$charset,'UTF-8');
-	        $content = api_convert_encoding($content,$charset,'UTF-8');
-			//message in inbox
-			$sql = "SELECT COUNT(*) as count FROM $table_message WHERE user_sender_id = ".api_get_user_id()." AND user_receiver_id='".Database::escape_string($receiver_user_id)."' AND title = '".Database::escape_string($title)."' AND content ='".Database::escape_string($content)."' ";
-			$res_exist = Database::query($sql,__FILE__,__LINE__);
-			$row_exist = Database::fetch_array($res_exist,'ASSOC');
+	 public static function send_message ($receiver_user_id, $title, $content) {
+        global $charset;
+        if (is_numeric($receiver_user_id)) {
+			$table_message = Database::get_main_table(TABLE_MESSAGE);
+	        $title = api_convert_encoding($title,$charset,'UTF-8');
+	        $content = api_convert_encoding($content,$charset,'UTF-8');
+			//message in inbox
+			$sql = "SELECT COUNT(*) as count FROM $table_message WHERE user_sender_id = ".api_get_user_id()." AND user_receiver_id='".Database::escape_string($receiver_user_id)."' AND title = '".Database::escape_string($title)."' AND content ='".Database::escape_string($content)."' ";
+			$res_exist = Database::query($sql,__FILE__,__LINE__);
+			$row_exist = Database::fetch_array($res_exist,'ASSOC');
 			if ($row_exist['count'] ==0) {
-				$query = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ".
-						 " VALUES (".
-				 		 "'".api_get_user_id()."', '".Database::escape_string($receiver_user_id)."', '1', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'".
-				 		 ")";
-				//message in outbox
-				$sql = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ".
-						 " VALUES (".
-				 		 "'".api_get_user_id()."', '".Database::escape_string($receiver_user_id)."', '4', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'".
-				 		 ")";
-				$rs = Database::query($sql,__FILE__,__LINE__);
-				$result = Database::query($query,__FILE__,__LINE__);
-				return $result;
-			}
-        } else {
-        	return false;
-        }
+				$query = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ".
+						 " VALUES (".
+				 		 "'".api_get_user_id()."', '".Database::escape_string($receiver_user_id)."', '1', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'".
+				 		 ")";
+				//message in outbox
+				$sql = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ".
+						 " VALUES (".
+				 		 "'".api_get_user_id()."', '".Database::escape_string($receiver_user_id)."', '4', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'".
+				 		 ")";
+				$rs = Database::query($sql,__FILE__,__LINE__);
+				$result = Database::query($query,__FILE__,__LINE__);
+				return $result;
+			}
+        } else {
+        	return false;
+        }
 
-		return false;
-	}
+		return false;
+	}
 
 	 public static function delete_message_by_user_receiver ($user_receiver_id,$id) {
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$id = Database::escape_string($id);
-		$sql="SELECT COUNT(*) as count FROM $table_message WHERE id=".$id." AND msg_status<>4;";
-		$rs=Database::query($sql,__FILE__,__LINE__);
-		$row=Database::fetch_array($rs,'ASSOC');
-		if ($row['count']==1) {
-			$query = "DELETE FROM $table_message " .
-			"WHERE user_receiver_id=".Database::escape_string($user_receiver_id)." AND id=".$id;
-			$result = Database::query($query,__FILE__,__LINE__);
+		$id = Database::escape_string($id);
+		$sql="SELECT COUNT(*) as count FROM $table_message WHERE id=".$id." AND msg_status<>4;";
+		$rs=Database::query($sql,__FILE__,__LINE__);
+		$row=Database::fetch_array($rs,'ASSOC');
+		if ($row['count']==1) {
+			$query = "DELETE FROM $table_message " .
+			"WHERE user_receiver_id=".Database::escape_string($user_receiver_id)." AND id=".$id;
+			$result = Database::query($query,__FILE__,__LINE__);
 			return $result;
-		} else {
-			return false;
-		}
-	}
-	/**
+		} else {
+			return false;
+		}
+	}
+	/**
 	 * Set status deleted
-	 * @author Isaac FLores Paz <isaac.flores@dokeos.com>
-	 * @param  integer
-	 * @param  integer
-	 * @return array
-	 */
-	public static function delete_message_by_user_sender ($user_sender_id,$id) {
+	 * @author Isaac FLores Paz <isaac.flores@dokeos.com>
+	 * @param  integer
+	 * @param  integer
+	 * @return array
+	 */
+	public static function delete_message_by_user_sender ($user_sender_id,$id) {
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$query = "DELETE FROM $table_message " .
+		$query = "DELETE FROM $table_message " .
 				 "WHERE user_sender_id=".Database::escape_string($user_sender_id)." AND id=".Database::escape_string($id);
-		$result = Database::query($query,__FILE__,__LINE__);
+		$result = Database::query($query,__FILE__,__LINE__);
 		return $result;
-	}
-	public static function update_message ($user_id, $id) {
+	}
+	public static function update_message ($user_id, $id) {
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$query = "UPDATE $table_message SET msg_status = '0' WHERE msg_status<>4 AND user_receiver_id=".Database::escape_string($user_id)." AND id='".Database::escape_string($id)."'";
+		$query = "UPDATE $table_message SET msg_status = '0' WHERE msg_status<>4 AND user_receiver_id=".Database::escape_string($user_id)." AND id='".Database::escape_string($id)."'";
 		$result = Database::query($query,__FILE__,__LINE__);
-	}
+	}
 
-	 public static function get_message_by_user ($user_id,$id) {
+	 public static function get_message_by_user ($user_id,$id) {
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$query = "SELECT * FROM $table_message WHERE user_receiver_id=".Database::escape_string($user_id)." AND id='".Database::escape_string($id)."'";
-		$result = Database::query($query,__FILE__,__LINE__);
-		return $row = Database::fetch_array($result);
-	}
-	/**
-	 * Gets information about if exist messages
-	 * @author Isaac FLores Paz <isaac.flores@dokeos.com>
-	 * @param  integer
-	 * @param  integer
-	 * @return boolean
-	 */
-	 public static function exist_message ($user_id, $id) {
+		$query = "SELECT * FROM $table_message WHERE user_receiver_id=".Database::escape_string($user_id)." AND id='".Database::escape_string($id)."'";
+		$result = Database::query($query,__FILE__,__LINE__);
+		return $row = Database::fetch_array($result);
+	}
+	/**
+	 * Gets information about if exist messages
+	 * @author Isaac FLores Paz <isaac.flores@dokeos.com>
+	 * @param  integer
+	 * @param  integer
+	 * @return boolean
+	 */
+	 public static function exist_message ($user_id, $id) {
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$query = "SELECT id FROM $table_message WHERE user_receiver_id=".Database::escape_string($user_id)." AND id='".Database::escape_string($id)."'";
-		$result = Database::query($query,__FILE__,__LINE__);
-		$num = Database::num_rows($result);
-		if ($num>0)
-			return true;
-		else
+		$query = "SELECT id FROM $table_message WHERE user_receiver_id=".Database::escape_string($user_id)." AND id='".Database::escape_string($id)."'";
+		$result = Database::query($query,__FILE__,__LINE__);
+		$num = Database::num_rows($result);
+		if ($num>0)
+			return true;
+		else
 			return false;
-	}
-	/**
-	 * Gets information about messages sent
+	}
+	/**
+	 * Gets information about messages sent
 	 * @author Isaac FLores Paz <isaac.flores@dokeos.com>
-	 * @param  integer
-	 * @param  integer
-	 * @param  string
-	 * @return array
-	 */
-	 public static function get_message_data_sent ($from, $number_of_items, $column, $direction) {
-	 	global $charset;
+	 * @param  integer
+	 * @param  integer
+	 * @param  string
+	 * @return array
+	 */
+	 public static function get_message_data_sent ($from, $number_of_items, $column, $direction) {
+	 	global $charset;
 
-	 	$from = intval($from);
-		$number_of_items = intval($number_of_items);
-		$column = intval($column);
-		if (!in_array($direction, array('ASC', 'DESC')))
+	 	$from = intval($from);
+		$number_of_items = intval($number_of_items);
+		$column = intval($column);
+		if (!in_array($direction, array('ASC', 'DESC')))
 			$direction = 'ASC';
 
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$request=api_is_xml_http_request();
-		$sql_query = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, user_receiver_id as col4, msg_status as col5 FROM $table_message " .
-					 "WHERE user_sender_id=".api_get_user_id()." AND msg_status=4 " .
-					 "ORDER BY col$column $direction LIMIT $from,$number_of_items";
+		$request=api_is_xml_http_request();
+		$sql_query = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, user_receiver_id as col4, msg_status as col5 FROM $table_message " .
+					 "WHERE user_sender_id=".api_get_user_id()." AND msg_status=4 " .
+					 "ORDER BY col$column $direction LIMIT $from,$number_of_items";
 
-		$sql_result = Database::query($sql_query,__FILE__,__LINE__);
-		$i = 0;
-		$message_list = array ();
-		while ($result = Database::fetch_row($sql_result)) {
-			if ($request===true) {
+		$sql_result = Database::query($sql_query,__FILE__,__LINE__);
+		$i = 0;
+		$message_list = array ();
+		while ($result = Database::fetch_row($sql_result)) {
+			if ($request===true) {
 				$message[0] = '<input type="checkbox" value='.$result[0].' name="out[]">';
-			 } else {
+			 } else {
 				$message[0] = ($result[0]);
-			 }
+			 }
 
-			if ($request===true) {
-			   if ($result[5]==4)
-			   {
-			   		$message[1] = Display::return_icon('mail_send.png',get_lang('MessageSent'));//Message Sent
-			   }
-				$message[2] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.GetFullUserName($result[4]).'</a>';
-				$message[3] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.str_replace("\\","",$result[2]).'</a>';
-				$message[5] = '&nbsp;&nbsp;<a onclick="delete_one_message_outbox('.$result[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',get_lang('DeleteMessage')).'</a>';
-			} else {
-				$message[2] = '<a onclick="show_sent_message ('.$result[0].')" href="#../messages/view_message.php?id_send='.$result[0].'">'.GetFullUserName($result[4]).'</a>';
-				$message[3] = '<a onclick="show_sent_message ('.$result[0].')" href="#../messages/view_message.php?id_send='.$result[0].'">'.$result[2].'</a>';
-				$message[5] = '<a href="new_message.php?re_id='.$result[0].'">'.Display::return_icon('message_reply.png',get_lang('ReplyToMessage')).'</a>'.
-						  '&nbsp;&nbsp;<a href="outbox.php?action=deleteone&id='.$result[0].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmDeleteMessage')))."'".')) return false;">'.Display::return_icon('message_delete.png',get_lang('DeleteMessage')).'</a>';
-			}
-			$message[4] = $result[3]; //date stays the same
-			foreach($message as $key => $value) {
-				$message[$key] = api_xml_http_response_encode($value);
-			}
-			$message_list[] = $message;
-			$i++;
-		}
-		return $message_list;
-	}
-	/**
-	 * Gets information about number messages sent
-	 * @author Isaac FLores Paz <isaac.flores@dokeos.com>
-	 * @param void
-	 * @return integer
-	 */
-	 public static function get_number_of_messages_sent () {
+			if ($request===true) {
+			   if ($result[5]==4)
+			   {
+			   		$message[1] = Display::return_icon('mail_send.png',get_lang('MessageSent'));//Message Sent
+			   }
+				$message[2] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.GetFullUserName($result[4]).'</a>';
+				$message[3] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.str_replace("\\","",$result[2]).'</a>';
+				$message[5] = '&nbsp;&nbsp;<a onclick="delete_one_message_outbox('.$result[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',get_lang('DeleteMessage')).'</a>';
+			} else {
+				$message[2] = '<a onclick="show_sent_message ('.$result[0].')" href="#../messages/view_message.php?id_send='.$result[0].'">'.GetFullUserName($result[4]).'</a>';
+				$message[3] = '<a onclick="show_sent_message ('.$result[0].')" href="#../messages/view_message.php?id_send='.$result[0].'">'.$result[2].'</a>';
+				$message[5] = '<a href="new_message.php?re_id='.$result[0].'">'.Display::return_icon('message_reply.png',get_lang('ReplyToMessage')).'</a>'.
+						  '&nbsp;&nbsp;<a href="outbox.php?action=deleteone&id='.$result[0].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmDeleteMessage')))."'".')) return false;">'.Display::return_icon('message_delete.png',get_lang('DeleteMessage')).'</a>';
+			}
+			$message[4] = $result[3]; //date stays the same
+			foreach($message as $key => $value) {
+				$message[$key] = api_xml_http_response_encode($value);
+			}
+			$message_list[] = $message;
+			$i++;
+		}
+		return $message_list;
+	}
+	/**
+	 * Gets information about number messages sent
+	 * @author Isaac FLores Paz <isaac.flores@dokeos.com>
+	 * @param void
+	 * @return integer
+	 */
+	 public static function get_number_of_messages_sent () {
+		$table_message = Database::get_main_table(TABLE_MESSAGE);
+		$sql_query = "SELECT COUNT(*) as number_messages FROM $table_message WHERE msg_status=4 AND user_sender_id=".api_get_user_id();
+		$sql_result = Database::query($sql_query,__FILE__,__LINE__);
+		$result = Database::fetch_array($sql_result);
+		return $result['number_messages'];
+	}
+	public static function show_message_box () {
+		global $charset;
 		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		$sql_query = "SELECT COUNT(*) as number_messages FROM $table_message WHERE msg_status=4 AND user_sender_id=".api_get_user_id();
-		$sql_result = Database::query($sql_query,__FILE__,__LINE__);
-		$result = Database::fetch_array($sql_result);
-		return $result['number_messages'];
-	}
-	public static function show_message_box () {
-		global $charset;
-		$table_message = Database::get_main_table(TABLE_MESSAGE);
 		if (isset($_GET['id_send']) && is_numeric($_GET['id_send'])) {
-			$query = "SELECT * FROM $table_message WHERE user_sender_id=".api_get_user_id()." AND id=".Database::escape_string($_GET['id_send'])." AND msg_status=4;";
-			$result = Database::query($query,__FILE__,__LINE__);
-		    $path='outbox.php';
-		} else {
-			if (is_numeric($_GET['id'])) {
-				$query = "UPDATE $table_message SET msg_status = '0' WHERE user_receiver_id=".api_get_user_id()." AND id='".Database::escape_string($_GET['id'])."';";
-				$result = Database::query($query,__FILE__,__LINE__);
-				$query = "SELECT * FROM $table_message WHERE msg_status<>4 AND user_receiver_id=".api_get_user_id()." AND id='".Database::escape_string($_GET['id'])."';";
-				$result = Database::query($query,__FILE__,__LINE__);
-			}
-			$path='inbox.php';
-		}
-		$row = Database::fetch_array($result);
-		$user_con = self::users_connected_by_id();
-		$band=0;
-		$reply='';
-		for ($i=0;$i<count($user_con);$i++)
-			if ($row[1]==$user_con[$i])
+			$query = "SELECT * FROM $table_message WHERE user_sender_id=".api_get_user_id()." AND id=".Database::escape_string($_GET['id_send'])." AND msg_status=4;";
+			$result = Database::query($query,__FILE__,__LINE__);
+		    $path='outbox.php';
+		} else {
+			if (is_numeric($_GET['id'])) {
+				$query = "UPDATE $table_message SET msg_status = '0' WHERE user_receiver_id=".api_get_user_id()." AND id='".Database::escape_string($_GET['id'])."';";
+				$result = Database::query($query,__FILE__,__LINE__);
+				$query = "SELECT * FROM $table_message WHERE msg_status<>4 AND user_receiver_id=".api_get_user_id()." AND id='".Database::escape_string($_GET['id'])."';";
+				$result = Database::query($query,__FILE__,__LINE__);
+			}
+			$path='inbox.php';
+		}
+		$row = Database::fetch_array($result);
+		$user_con = self::users_connected_by_id();
+		$band=0;
+		$reply='';
+		for ($i=0;$i<count($user_con);$i++)
+			if ($row[1]==$user_con[$i])
 				$band=1;
-		if ($band==1 && !isset($_GET['id_send'])) {
-			if (is_numeric($_GET['id'])) {
-				$reply = '<a onclick="reply_to_messages(\'show\','.Security::remove_XSS($_GET['id']).',\'\')" href="javascript:void(0)">'.Display::return_icon('message_reply.png',api_xml_http_response_encode(get_lang('ReplyToMessage'))).api_xml_http_response_encode(get_lang('ReplyToMessage')).'</a>';
-			}
-		}
-		echo '<div class=actions>';
-		echo '<a onclick="close_div_show(\'div_content_messages\')" href="javascript:void(0)">'.Display::return_icon('folder_up.gif',api_xml_http_response_encode(get_lang('BackToInbox'))).api_xml_http_response_encode(get_lang('BackToInbox')).'</a>';
+		if ($band==1 && !isset($_GET['id_send'])) {
+			if (is_numeric($_GET['id'])) {
+				$reply = '<a onclick="reply_to_messages(\'show\','.Security::remove_XSS($_GET['id']).',\'\')" href="javascript:void(0)">'.Display::return_icon('message_reply.png',api_xml_http_response_encode(get_lang('ReplyToMessage'))).api_xml_http_response_encode(get_lang('ReplyToMessage')).'</a>';
+			}
+		}
+		echo '<div class=actions>';
+		echo '<a onclick="close_div_show(\'div_content_messages\')" href="javascript:void(0)">'.Display::return_icon('folder_up.gif',api_xml_http_response_encode(get_lang('BackToInbox'))).api_xml_http_response_encode(get_lang('BackToInbox')).'</a>';
 		echo $reply;
-		echo '<a onclick="delete_one_message('.$row[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',api_xml_http_response_encode(get_lang('DeleteMessage'))).''.api_xml_http_response_encode(get_lang('DeleteMessage')).'</a>';
-		echo '</div><br />';
-		echo '
-		<table class="message_view_table" >
-		    <TR>
-		      <TD width=10>&nbsp; </TD>
-		      <TD vAlign=top width="100%">
+		echo '<a onclick="delete_one_message('.$row[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',api_xml_http_response_encode(get_lang('DeleteMessage'))).''.api_xml_http_response_encode(get_lang('DeleteMessage')).'</a>';
+		echo '</div><br />';
+		echo '
+		<table class="message_view_table" >
+		    <TR>
+		      <TD width=10>&nbsp; </TD>
+		      <TD vAlign=top width="100%">
 		      	<TABLE>
-		            <TR>
+		            <TR>
 		              <TD width="100%">
-		                    <TR> <h1>'.str_replace("\\","",api_xml_http_response_encode($row[5])).'</h1></TR>
+		                    <TR> <h1>'.str_replace("\\","",api_xml_http_response_encode($row[5])).'</h1></TR>
 		              </TD>
 		              <TR>
-		              	<TD>'.api_xml_http_response_encode(get_lang('From').'&nbsp;<b>'.GetFullUserName($row[1]).'</b> '.api_strtolower(get_lang('To')).'&nbsp;  <b>'.GetFullUserName($row[2])).'</b> </TD>
+		              	<TD>'.api_xml_http_response_encode(get_lang('From').'&nbsp;<b>'.GetFullUserName($row[1]).'</b> '.api_strtolower(get_lang('To')).'&nbsp;  <b>'.GetFullUserName($row[2])).'</b> </TD>
 		              </TR>
-		              <TR>
+		              <TR>
 		              <TD >'.api_xml_http_response_encode(get_lang('Date').'&nbsp; '.$row[4]).'</TD>
 		              </TR>
 		            </TR>
 		        </TABLE>
-		        <br />
-		        <TABLE height=209 width="100%" bgColor=#ffffff>
-		          <TBODY>
-		            <TR>
-		              <TD vAlign=top>'.str_replace("\\","",api_xml_http_response_encode($row[6])).'</TD>
-		            </TR>
-		          </TBODY>
-		        </TABLE>
-		        <DIV class=HT style="PADDING-BOTTOM: 5px"> </DIV></TD>
-		      <TD width=10>&nbsp;</TD>
-		    </TR>
-		</TABLE>';
-	}
-	public static function show_message_box_sent () {
-		global $charset;
-		$table_message = Database::get_main_table(TABLE_MESSAGE);
-		if (is_numeric($_GET['id_send'])) {
+		        <br />
+		        <TABLE height=209 width="100%" bgColor=#ffffff>
+		          <TBODY>
+		            <TR>
+		              <TD vAlign=top>'.str_replace("\\","",api_xml_http_response_encode($row[6])).'</TD>
+		            </TR>
+		          </TBODY>
+		        </TABLE>
+		        <DIV class=HT style="PADDING-BOTTOM: 5px"> </DIV></TD>
+		      <TD width=10>&nbsp;</TD>
+		    </TR>
+		</TABLE>';
+	}
+	public static function show_message_box_sent () {
+		global $charset;
+		$table_message = Database::get_main_table(TABLE_MESSAGE);
+		if (is_numeric($_GET['id_send'])) {
 			$query = "SELECT * FROM $table_message WHERE user_sender_id=".api_get_user_id()." AND id=".Database::escape_string($_GET['id_send'])." AND msg_status=4;";
-			$result = Database::query($query,__FILE__,__LINE__);
-		}
-		$path='outbox.php';
+			$result = Database::query($query,__FILE__,__LINE__);
+		}
+		$path='outbox.php';
 
-		$row = Database::fetch_array($result);
-		$user_con = self::users_connected_by_id();
-		$band=0;
-		$reply='';
-		for ($i=0;$i<count($user_con);$i++)
-			if ($row[1]==$user_con[$i])
+		$row = Database::fetch_array($result);
+		$user_con = self::users_connected_by_id();
+		$band=0;
+		$reply='';
+		for ($i=0;$i<count($user_con);$i++)
+			if ($row[1]==$user_con[$i])
 				$band=1;
-		echo '<div class=actions>';
-		echo '<a onclick="close_and_open_outbox()" href="javascript:void(0)">'.Display::return_icon('folder_up.gif',api_xml_http_response_encode(get_lang('BackToOutbox'))).api_xml_http_response_encode(get_lang('BackToOutbox')).'</a>';
-		echo '<a onclick="delete_one_message_outbox('.$row[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',api_xml_http_response_encode(get_lang('DeleteMessage'))).api_xml_http_response_encode(get_lang('DeleteMessage')).'</a>';
-		echo '</div><br />';
-		echo '
-		<table class="message_view_table" >
-		    <TR>
-		      <TD width=10>&nbsp; </TD>
-		      <TD vAlign=top width="100%">
+		echo '<div class=actions>';
+		echo '<a onclick="close_and_open_outbox()" href="javascript:void(0)">'.Display::return_icon('folder_up.gif',api_xml_http_response_encode(get_lang('BackToOutbox'))).api_xml_http_response_encode(get_lang('BackToOutbox')).'</a>';
+		echo '<a onclick="delete_one_message_outbox('.$row[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',api_xml_http_response_encode(get_lang('DeleteMessage'))).api_xml_http_response_encode(get_lang('DeleteMessage')).'</a>';
+		echo '</div><br />';
+		echo '
+		<table class="message_view_table" >
+		    <TR>
+		      <TD width=10>&nbsp; </TD>
+		      <TD vAlign=top width="100%">
 		      	<TABLE>
-		            <TR>
+		            <TR>
 		              <TD width="100%">
-		                    <TR> <h1>'.str_replace("\\","",api_xml_http_response_encode($row[5])).'</h1></TR>
+		                    <TR> <h1>'.str_replace("\\","",api_xml_http_response_encode($row[5])).'</h1></TR>
 		              </TD>
 		              <TR>
-		              	<TD>'.api_xml_http_response_encode(get_lang('From').'&nbsp;<b>'.GetFullUserName($row[1]).'</b> '.api_strtolower(get_lang('To')).'&nbsp;  <b>'.GetFullUserName($row[2])).'</b> </TD>
+		              	<TD>'.api_xml_http_response_encode(get_lang('From').'&nbsp;<b>'.GetFullUserName($row[1]).'</b> '.api_strtolower(get_lang('To')).'&nbsp;  <b>'.GetFullUserName($row[2])).'</b> </TD>
 		              </TR>
-		              <TR>
+		              <TR>
 		              <TD >'.api_xml_http_response_encode(get_lang('Date').'&nbsp; '.$row[4]).'</TD>
 		              </TR>
 		            </TR>
 		        </TABLE>
-		        <br />
-		        <TABLE height=209 width="100%" bgColor=#ffffff>
-		          <TBODY>
-		            <TR>
-		              <TD vAlign=top>'.str_replace("\\","",api_xml_http_response_encode($row[6])).'</TD>
-		            </TR>
-		          </TBODY>
-		        </TABLE>
-		        <DIV class=HT style="PADDING-BOTTOM: 5px"> </DIV></TD>
-		      <TD width=10>&nbsp;</TD>
-		    </TR>
-		</TABLE>';
-	}
-	/**
-	 * get user id by user email
-	 * @param string $user_email
-	 * @return int user id
-	 */
-	public static function get_user_id_by_email ($user_email) {
-		$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-		$sql='SELECT user_id FROM '.$tbl_user.' WHERE email="'.Database::escape_string($user_email).'";';
-		$rs=Database::query($sql,__FILE__,__LINE__);
-		$row=Database::fetch_array($rs,'ASSOC');
-		if (isset($row['user_id'])) {
-			return $row['user_id'];
-		} else {
-			return null;
-		}
-	}
-}
-?>
+		        <br />
+		        <TABLE height=209 width="100%" bgColor=#ffffff>
+		          <TBODY>
+		            <TR>
+		              <TD vAlign=top>'.str_replace("\\","",api_xml_http_response_encode($row[6])).'</TD>
+		            </TR>
+		          </TBODY>
+		        </TABLE>
+		        <DIV class=HT style="PADDING-BOTTOM: 5px"> </DIV></TD>
+		      <TD width=10>&nbsp;</TD>
+		    </TR>
+		</TABLE>';
+	}
+	/**
+	 * get user id by user email
+	 * @param string $user_email
+	 * @return int user id
+	 */
+	public static function get_user_id_by_email ($user_email) {
+		$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+		$sql='SELECT user_id FROM '.$tbl_user.' WHERE email="'.Database::escape_string($user_email).'";';
+		$rs=Database::query($sql,__FILE__,__LINE__);
+		$row=Database::fetch_array($rs,'ASSOC');
+		if (isset($row['user_id'])) {
+			return $row['user_id'];
+		} else {
+			return null;
+		}
+	}
+}
+?>

+ 19 - 19
main/messages/plugin.php

@@ -1,21 +1,21 @@
-<?php
-/**
- * This script is a configuration file for the messages plugin. You can use it as a master for other plugins.
- * These settings will be used in the administration interface for plugins (Dokeos configuration settings->Plugins)
+<?php
+/**
+ * This script is a configuration file for the messages plugin. You can use it as a master for other plugins.
+ * These settings will be used in the administration interface for plugins (Dokeos configuration settings->Plugins)
  * @package dokeos.plugin
- * @author Evie, Free University of Brussels
- */
-/**
+ * @author Evie, Free University of Brussels
+ */
+/**
  * Plugin details (must be present)
- */
-//the plugin title
-$plugin_info['title']='Messages';
-//the comments that go with the plugin
-$plugin_info['comment']="Private messages plugin";
-//the locations where this plugin can be shown
-$plugin_info['location']=array('loginpage_main', 'loginpage_menu', 'campushomepage_main', 'campushomepage_menu', 'mycourses_main', 'mycourses_menu', 'header', 'footer');
-//the plugin version
-$plugin_info['version']='1.1';
-//the plugin author
-$plugin_info['author']='Facultad de Matematicas, UADY (Mexico)';
-?>
+ */
+//the plugin title
+$plugin_info['title']='Messages';
+//the comments that go with the plugin
+$plugin_info['comment']="Private messages plugin";
+//the locations where this plugin can be shown
+$plugin_info['location']=array('loginpage_main', 'loginpage_menu', 'campushomepage_main', 'campushomepage_menu', 'mycourses_main', 'mycourses_menu', 'header', 'footer');
+//the plugin version
+$plugin_info['version']='1.1';
+//the plugin author
+$plugin_info['author']='Facultad de Matematicas, UADY (Mexico)';
+?>

+ 108 - 108
main/messaging/email_editor.php

@@ -1,112 +1,112 @@
-<?php // $Id$
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2006 Dokeos S.A.
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 44 rue des Palais, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
- * This script contains the code to edit and send an e-mail to one of
- * Dokeos' users.
- * It can be called from the JavaScript library email_links.lib.php which
- * overtakes the mailto: links to use the internal interface instead.
+<?php // $Id$
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2006 Dokeos S.A.
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 44 rue des Palais, B-1030 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+ * This script contains the code to edit and send an e-mail to one of
+ * Dokeos' users.
+ * It can be called from the JavaScript library email_links.lib.php which
+ * overtakes the mailto: links to use the internal interface instead.
  * @author	Yannick Warnier <ywarnier@beeznest.org>
- */
-
+ */
+
 // name of the language file that needs to be included
-$language_file = "index";
-
-require_once"../inc/global.inc.php";
-require_once"../inc/lib/usermanager.lib.php";
-if(empty($_user['user_id']))
-{
-	api_not_allowed(true);
-}
-
-//api_protect_course_script(); //not a course script, so no protection
-
-if(empty($_SESSION['origin_url'])){
-	$origin_url = $_SERVER['HTTP_REFERER'];
-	api_session_register('origin_url');
-}
-
-/* Process the form and redirect to origin */
-if(!empty($_POST['submit_email']) && !empty($_POST['email_title']) && !empty($_POST['email_text']))
-{
-	$text = Security::remove_XSS($_POST['email_text'])."\n\n---\n".get_lang('EmailSentFromDokeos')." ".api_get_path(WEB_PATH);
-	$email_administrator=Security::remove_XSS($_POST['dest']);
-	$user_id=api_get_user_id();
-	$title=Security::remove_XSS($_POST['email_title']);
+$language_file = "index";
+
+require_once"../inc/global.inc.php";
+require_once"../inc/lib/usermanager.lib.php";
+if(empty($_user['user_id']))
+{
+	api_not_allowed(true);
+}
+
+//api_protect_course_script(); //not a course script, so no protection
+
+if(empty($_SESSION['origin_url'])){
+	$origin_url = $_SERVER['HTTP_REFERER'];
+	api_session_register('origin_url');
+}
+
+/* Process the form and redirect to origin */
+if(!empty($_POST['submit_email']) && !empty($_POST['email_title']) && !empty($_POST['email_text']))
+{
+	$text = Security::remove_XSS($_POST['email_text'])."\n\n---\n".get_lang('EmailSentFromDokeos')." ".api_get_path(WEB_PATH);
+	$email_administrator=Security::remove_XSS($_POST['dest']);
+	$user_id=api_get_user_id();
+	$title=Security::remove_XSS($_POST['email_title']);
 	$content=Security::remove_XSS($_POST['email_text']);
-	if(!empty($_user['mail'])){
-		api_send_mail($email_administrator,$title,$text,"From: ".$_user['mail']."\r\n");
+	if(!empty($_user['mail'])){
+		api_send_mail($email_administrator,$title,$text,"From: ".$_user['mail']."\r\n");
 		UserManager::send_message_in_outbox ($email_administrator,$user_id,$title, $content);
-	}else{
-		api_send_mail($email_administrator,$title,$text);
-	}
-	$orig = $_SESSION['origin_url'];
-	api_session_unregister('origin_url');
-	header('location:'.$orig);
-}
-
-/* Header */
-Display::display_header(get_lang('SendEmail'));
-
-?>
-<table border="0">
-<form action="" method="POST">
-<input type="hidden" name="dest" value="<?php echo Security::remove_XSS($_REQUEST['dest']);?>" />
-	<tr>
-		<td>
-			<label for="email_address"><?php echo get_lang('EmailDestination');?></label>
-		</td>
-		<td>
-			<span id="email_address"><?php echo Security::remove_XSS($_REQUEST['dest']); ?></span>
-		</td>
-	</tr>
-	<tr>
-		<td>
-			<label for="email_title"><?php echo get_lang('EmailTitle');?></label>
-		</td>
-		<td>
-			<input name="email_title" id="email_title" value="<?php echo Security::remove_XSS($_POST['email_title']);?>" size="60"></input>
-		</td>
-	</tr>
-	<tr>
-		<td valign="top">
-			<label for="email_text"><?php echo get_lang('EmailText');?></label>
-		</td>
-		<td>
-			<?php
-			  echo '<textarea id="email_text" name="email_text" rows="10" cols="80">'.Security::remove_XSS($_POST['email_text']).'</textarea>';
-			  //htmlarea is not used otherwise we have to deal with HTML e-mail and all the related probs
-			  //api_disp_html_area('email_text',$_POST['email_text'],'250px');
-			?>
-		</td>
-	</tr>
-	<tr>
-		<td colspan="2">
-			<button class="save" type="submit" name="submit_email" value="<?php echo get_lang('SendMail');?>"><?php echo get_lang('SendMail');?></button>
-		</td>
-	</tr>
-</form>
-</table>
-
-<?
-
-/* Footer */
-Display::display_footer();
-?>
+	}else{
+		api_send_mail($email_administrator,$title,$text);
+	}
+	$orig = $_SESSION['origin_url'];
+	api_session_unregister('origin_url');
+	header('location:'.$orig);
+}
+
+/* Header */
+Display::display_header(get_lang('SendEmail'));
+
+?>
+<table border="0">
+<form action="" method="POST">
+<input type="hidden" name="dest" value="<?php echo Security::remove_XSS($_REQUEST['dest']);?>" />
+	<tr>
+		<td>
+			<label for="email_address"><?php echo get_lang('EmailDestination');?></label>
+		</td>
+		<td>
+			<span id="email_address"><?php echo Security::remove_XSS($_REQUEST['dest']); ?></span>
+		</td>
+	</tr>
+	<tr>
+		<td>
+			<label for="email_title"><?php echo get_lang('EmailTitle');?></label>
+		</td>
+		<td>
+			<input name="email_title" id="email_title" value="<?php echo Security::remove_XSS($_POST['email_title']);?>" size="60"></input>
+		</td>
+	</tr>
+	<tr>
+		<td valign="top">
+			<label for="email_text"><?php echo get_lang('EmailText');?></label>
+		</td>
+		<td>
+			<?php
+			  echo '<textarea id="email_text" name="email_text" rows="10" cols="80">'.Security::remove_XSS($_POST['email_text']).'</textarea>';
+			  //htmlarea is not used otherwise we have to deal with HTML e-mail and all the related probs
+			  //api_disp_html_area('email_text',$_POST['email_text'],'250px');
+			?>
+		</td>
+	</tr>
+	<tr>
+		<td colspan="2">
+			<button class="save" type="submit" name="submit_email" value="<?php echo get_lang('SendMail');?>"><?php echo get_lang('SendMail');?></button>
+		</td>
+	</tr>
+</form>
+</table>
+
+<?
+
+/* Footer */
+Display::display_footer();
+?>

+ 194 - 194
main/metadata/phpdig/en-language.php

@@ -1,195 +1,195 @@
-<?php
-
-//English messages for PhpDig
-//Antoine Bajolet - fr - bajolet@toiletoine.net
-//Corrections by Brien Louque
-
-//'keyword' => 'translation'
-$phpdig_mess = array (
-'one_per_line' =>'Enter one link per line',
-
-'StopSpider'   =>'Stop spider',
-'id'           =>'ID',
-'url'          =>'URL',
-'days'         =>'Days',
-'links'        =>'Links',
-'depth'        =>'Depth',
-'viewRSS'      =>'View RSS for this Page',
-'powered_by'   =>'Powered by PhpDig',
-'searchall'    =>'Search All',
-'wait'         =>'Wait... ',
-'done'         =>'Done!',
-'limit'        =>'Limit',
-'manage'       =>'Here you can manage:',
-'dayscron'     =>'- the number of <b>days</b> crontab waits to reindex (0 = ignore)',
-'links_mean'   =>'- the max number of <b>links</b> per depth per site (0 = unlimited)',
-'depth_mean'   =>'- the max search <b>depth</b> per site (0 = none, depth trumps links)',
-'max_found'    =>'Maximum links found is ((links * depth) + 1) when links is greater than zero.',
-'default_vals' =>'Default values',
-'use_vals_from' =>'Use values from',
-'table_present' =>'table if present and use<br/>default values if values absent from table?',
-'admin_msg_1'   =>'- To empty tempspider table click delete button <i>without</i> selecting a site',
-'admin_msg_2'   =>'- Search depth of zero tries to crawl just that page regardless of links per',
-'admin_msg_3'   =>'- Set links per depth to the max number of links to check at each depth',
-'admin_msg_4'   =>'- Links per depth of zero means to check for all links at each seach depth',
-'admin_msg_5'   =>'- Clean dashes removes \'-\' index pages from blue arrow listings of pages',
-'admin_panel'   =>'Admin Panel',
-
-'choose_temp'  =>'Choose a template',
-'select_site'  =>'Select a site to search',
-'restart'      =>'Restart',
-'narrow_path'  =>'Narrow Path to Search',
-'upd_sites'    =>'Update sites',
-'upd2'         =>'Update Done',
-'links_per'    =>'Links per',
-'yes'          =>'yes',
-'no'           =>'no',
-'delete'       =>'delete',
-'reindex'      =>'Re-index',
-'back'         =>'Back',
-'files'        =>'files',
-'admin'        =>'Administration',
-'warning'      =>'Warning !',
-'index_uri'    =>'Which URI would you index?',
-'spider_depth' =>'Search depth',
-'spider_warn'  =>'Please ensure that no one else is updating the same site.
-A locking mechanism will be included in a later version.',
-'site_update'  =>'Update a site or one of its branch',
-'clean'        =>'Clean',
-'t_index'      =>'index',
-'t_dic'        =>'dictionary',
-'t_stopw'      =>'common words',
-'t_dash'       =>'dashes',
-
-'update'       =>'Update',
-'exclude'      =>'Delete and exclude branch',
-'excludes'     =>'Exclude paths',
-'tree_found'   =>'Found tree',
-'update_mess'  =>'Re-index or delete a tree ',
-'update_warn'  =>'Exclude will delete indexed entries',
-'update_help'  =>'Click on the cross to delete the branch
-Click on the green sign to update it
-Click on the noway sign to exclude from future indexings',
-'branch_start' =>'Select the folder to display on the left side',
-'branch_help1' =>'Select there documents to update individually',
-'branch_help2' =>'Click on the cross to delete a document
-Click on the green sign to reindex it',
-'redepth'      =>'levels depth',
-'branch_warn'  =>'Erase is permanent',
-'to_admin'     =>'to admin interface',
-'to_update'    =>'to update interface',
-
-'search'       =>'Search',
-'results'      =>'results',
-'display'      =>'display',
-'w_begin'      =>'and operator',
-'w_whole'      =>'exact phrase',
-'w_part'       =>'or operator',
-'alt_try'      =>'Did you mean',
-
-'limit_to'     =>'limit to',
-'this_path'    =>'this path',
-'total'        =>'total',
-'seconds'      =>'seconds',
-'w_common_sing'     =>'is a very common word and was ignored.',
-'w_short_sing'      =>'is too short a word and was ignored.',
-'w_common_plur'     =>'are very common words and were ignored.',
-'w_short_plur'      =>'are too short of words and were ignored.',
-'s_results'    =>'search results',
-'previous'     =>'Previous',
-'next'         =>'Next',
-'on'           =>'on',
-
-'id_start'     =>'Site indexing',
-'id_end'       =>'Indexing complete !',
-'id_recent'    =>'Was recently indexed',
-'num_words'    =>'Num words',
-'time'         =>'time',
-'error'        =>'Error',
-'no_spider'    =>'Spider not launched',
-'no_site'      =>'No such site in database',
-'no_temp'      =>'No link in temporary table',
-'no_toindex'   =>'No content indexed',
-'double'       =>'Duplicate of an existing document',
-
-'spidering'    =>'Spidering in progress...',
-'links_more'   =>'more new links',
-'level'        =>'level',
-'links_found'  =>'links found',
-'define_ex'    =>'Define exclusions',
-'index_all'    =>'index all',
-
-'end'          =>'end',
-'no_query'     =>'Select predefined keywords (recommended) by opening the tree with the [+] button below, or type descriptive words in the inputzone, separated by a comma, or type the first letters of a keyword and use autocomplete. Empty the inputzone to re-use autocomplete',
-'pwait'        =>'Please wait',
-'statistics'   =>'Statistics',
-
-// INSTALL
-'slogan'   =>'The smallest search engine in the universe : version',
-'installation'   =>'Installation',
-'instructions' =>'Type here the MySql parameters. Specify a valid existing user who can create databases if you choose create or update.',
-'hostname'   =>'Hostname  :',
-'port'   =>'Port (none = default) :',
-'sock'   =>'Sock (none = default) :',
-'user'   =>'User :',
-'password'   =>'Password :',
-'phpdigdatabase'   =>'PhpDig database :',
-'tablesprefix'   =>'Tables prefix :',
-'instructions2'   =>'* optional. Use lowercase characters, 16 characters max.',
-'installdatabase'   =>'Install phpdig database',
-'error1'   =>'Can\'t find connexion template. ',
-'error2'   =>'Can\'t write connexion template. ',
-'error3'   =>'Can\'t find init_db.sql file. ',
-'error4'   =>'Can\'t create tables. ',
-'error5'   =>'Can\'t find all config database files. ',
-'error6'   =>'Can\'t create database.<br />Verify user\'s rights. ',
-'error7'   =>'Can\'t connect to database<br />Verify connection datas. ',
-'createdb' =>'Create database',
-'createtables' =>'Create tables only',
-'updatedb' =>'Update existing database',
-'existingdb' =>'Write only connection parameters',
-// CLEANUP_ENGINE
-'cleaningindex'   =>'Cleaning index',
-'enginenotok'   =>' index references targeted an inexistent keyword.',
-'engineok'   =>'Engine is coherent.',
-// CLEANUP_KEYWORDS
-'cleaningdictionnary'   =>'Cleaning dictionary',
-'keywordsok'   =>'All keywords are in one or more page.',
-'keywordsnotok'   =>' keywords where not in one page at least.',
-// CLEANUP_COMMON
-'cleanupcommon' =>'Cleanup common words',
-'cleanuptotal' =>'Total ',
-'cleaned' =>' cleaned.',
-'deletedfor' =>' deleted for ',
-// INDEX ADMIN
-'digthis' =>'Dig this !',
-'databasestatus' =>'DataBase status',
-'entries' =>' Entries ',
-'updateform' =>'Update form',
-'deletesite' =>'Delete site',
-// SPIDER
-'spiderresults' =>'Spider results',
-// STATISTICS
-'mostkeywords' =>'Most keywords',
-'richestpages' =>'Richest pages',
-'mostterms'    =>'Most search terms',
-'largestresults'=>'Largest results',
-'mostempty'     =>'Most searchs giving empty results',
-'lastqueries'   =>'Last search queries',
-'lastclicks'   =>'Last search clicks',
-'responsebyhour'=>'Response time by hour',
-// UPDATE
-'userpasschanged' =>'User/Password changed !',
-'uri' =>'URI : ',
-'change' =>'Change',
-'root' =>'Root',
-'pages' =>' pages',
-'locked' => 'Locked',
-'unlock' => 'Unlock site',
-'onelock' => 'A site is locked, because of spidering. You can\'t do this for now',
-// PHPDIG_FORM
-'go' =>'Go ...',
-// SEARCH_FUNCTION
-'noresults' =>'No results'
-);
+<?php
+
+//English messages for PhpDig
+//Antoine Bajolet - fr - bajolet@toiletoine.net
+//Corrections by Brien Louque
+
+//'keyword' => 'translation'
+$phpdig_mess = array (
+'one_per_line' =>'Enter one link per line',
+
+'StopSpider'   =>'Stop spider',
+'id'           =>'ID',
+'url'          =>'URL',
+'days'         =>'Days',
+'links'        =>'Links',
+'depth'        =>'Depth',
+'viewRSS'      =>'View RSS for this Page',
+'powered_by'   =>'Powered by PhpDig',
+'searchall'    =>'Search All',
+'wait'         =>'Wait... ',
+'done'         =>'Done!',
+'limit'        =>'Limit',
+'manage'       =>'Here you can manage:',
+'dayscron'     =>'- the number of <b>days</b> crontab waits to reindex (0 = ignore)',
+'links_mean'   =>'- the max number of <b>links</b> per depth per site (0 = unlimited)',
+'depth_mean'   =>'- the max search <b>depth</b> per site (0 = none, depth trumps links)',
+'max_found'    =>'Maximum links found is ((links * depth) + 1) when links is greater than zero.',
+'default_vals' =>'Default values',
+'use_vals_from' =>'Use values from',
+'table_present' =>'table if present and use<br/>default values if values absent from table?',
+'admin_msg_1'   =>'- To empty tempspider table click delete button <i>without</i> selecting a site',
+'admin_msg_2'   =>'- Search depth of zero tries to crawl just that page regardless of links per',
+'admin_msg_3'   =>'- Set links per depth to the max number of links to check at each depth',
+'admin_msg_4'   =>'- Links per depth of zero means to check for all links at each seach depth',
+'admin_msg_5'   =>'- Clean dashes removes \'-\' index pages from blue arrow listings of pages',
+'admin_panel'   =>'Admin Panel',
+
+'choose_temp'  =>'Choose a template',
+'select_site'  =>'Select a site to search',
+'restart'      =>'Restart',
+'narrow_path'  =>'Narrow Path to Search',
+'upd_sites'    =>'Update sites',
+'upd2'         =>'Update Done',
+'links_per'    =>'Links per',
+'yes'          =>'yes',
+'no'           =>'no',
+'delete'       =>'delete',
+'reindex'      =>'Re-index',
+'back'         =>'Back',
+'files'        =>'files',
+'admin'        =>'Administration',
+'warning'      =>'Warning !',
+'index_uri'    =>'Which URI would you index?',
+'spider_depth' =>'Search depth',
+'spider_warn'  =>'Please ensure that no one else is updating the same site.
+A locking mechanism will be included in a later version.',
+'site_update'  =>'Update a site or one of its branch',
+'clean'        =>'Clean',
+'t_index'      =>'index',
+'t_dic'        =>'dictionary',
+'t_stopw'      =>'common words',
+'t_dash'       =>'dashes',
+
+'update'       =>'Update',
+'exclude'      =>'Delete and exclude branch',
+'excludes'     =>'Exclude paths',
+'tree_found'   =>'Found tree',
+'update_mess'  =>'Re-index or delete a tree ',
+'update_warn'  =>'Exclude will delete indexed entries',
+'update_help'  =>'Click on the cross to delete the branch
+Click on the green sign to update it
+Click on the noway sign to exclude from future indexings',
+'branch_start' =>'Select the folder to display on the left side',
+'branch_help1' =>'Select there documents to update individually',
+'branch_help2' =>'Click on the cross to delete a document
+Click on the green sign to reindex it',
+'redepth'      =>'levels depth',
+'branch_warn'  =>'Erase is permanent',
+'to_admin'     =>'to admin interface',
+'to_update'    =>'to update interface',
+
+'search'       =>'Search',
+'results'      =>'results',
+'display'      =>'display',
+'w_begin'      =>'and operator',
+'w_whole'      =>'exact phrase',
+'w_part'       =>'or operator',
+'alt_try'      =>'Did you mean',
+
+'limit_to'     =>'limit to',
+'this_path'    =>'this path',
+'total'        =>'total',
+'seconds'      =>'seconds',
+'w_common_sing'     =>'is a very common word and was ignored.',
+'w_short_sing'      =>'is too short a word and was ignored.',
+'w_common_plur'     =>'are very common words and were ignored.',
+'w_short_plur'      =>'are too short of words and were ignored.',
+'s_results'    =>'search results',
+'previous'     =>'Previous',
+'next'         =>'Next',
+'on'           =>'on',
+
+'id_start'     =>'Site indexing',
+'id_end'       =>'Indexing complete !',
+'id_recent'    =>'Was recently indexed',
+'num_words'    =>'Num words',
+'time'         =>'time',
+'error'        =>'Error',
+'no_spider'    =>'Spider not launched',
+'no_site'      =>'No such site in database',
+'no_temp'      =>'No link in temporary table',
+'no_toindex'   =>'No content indexed',
+'double'       =>'Duplicate of an existing document',
+
+'spidering'    =>'Spidering in progress...',
+'links_more'   =>'more new links',
+'level'        =>'level',
+'links_found'  =>'links found',
+'define_ex'    =>'Define exclusions',
+'index_all'    =>'index all',
+
+'end'          =>'end',
+'no_query'     =>'Select predefined keywords (recommended) by opening the tree with the [+] button below, or type descriptive words in the inputzone, separated by a comma, or type the first letters of a keyword and use autocomplete. Empty the inputzone to re-use autocomplete',
+'pwait'        =>'Please wait',
+'statistics'   =>'Statistics',
+
+// INSTALL
+'slogan'   =>'The smallest search engine in the universe : version',
+'installation'   =>'Installation',
+'instructions' =>'Type here the MySql parameters. Specify a valid existing user who can create databases if you choose create or update.',
+'hostname'   =>'Hostname  :',
+'port'   =>'Port (none = default) :',
+'sock'   =>'Sock (none = default) :',
+'user'   =>'User :',
+'password'   =>'Password :',
+'phpdigdatabase'   =>'PhpDig database :',
+'tablesprefix'   =>'Tables prefix :',
+'instructions2'   =>'* optional. Use lowercase characters, 16 characters max.',
+'installdatabase'   =>'Install phpdig database',
+'error1'   =>'Can\'t find connexion template. ',
+'error2'   =>'Can\'t write connexion template. ',
+'error3'   =>'Can\'t find init_db.sql file. ',
+'error4'   =>'Can\'t create tables. ',
+'error5'   =>'Can\'t find all config database files. ',
+'error6'   =>'Can\'t create database.<br />Verify user\'s rights. ',
+'error7'   =>'Can\'t connect to database<br />Verify connection datas. ',
+'createdb' =>'Create database',
+'createtables' =>'Create tables only',
+'updatedb' =>'Update existing database',
+'existingdb' =>'Write only connection parameters',
+// CLEANUP_ENGINE
+'cleaningindex'   =>'Cleaning index',
+'enginenotok'   =>' index references targeted an inexistent keyword.',
+'engineok'   =>'Engine is coherent.',
+// CLEANUP_KEYWORDS
+'cleaningdictionnary'   =>'Cleaning dictionary',
+'keywordsok'   =>'All keywords are in one or more page.',
+'keywordsnotok'   =>' keywords where not in one page at least.',
+// CLEANUP_COMMON
+'cleanupcommon' =>'Cleanup common words',
+'cleanuptotal' =>'Total ',
+'cleaned' =>' cleaned.',
+'deletedfor' =>' deleted for ',
+// INDEX ADMIN
+'digthis' =>'Dig this !',
+'databasestatus' =>'DataBase status',
+'entries' =>' Entries ',
+'updateform' =>'Update form',
+'deletesite' =>'Delete site',
+// SPIDER
+'spiderresults' =>'Spider results',
+// STATISTICS
+'mostkeywords' =>'Most keywords',
+'richestpages' =>'Richest pages',
+'mostterms'    =>'Most search terms',
+'largestresults'=>'Largest results',
+'mostempty'     =>'Most searchs giving empty results',
+'lastqueries'   =>'Last search queries',
+'lastclicks'   =>'Last search clicks',
+'responsebyhour'=>'Response time by hour',
+// UPDATE
+'userpasschanged' =>'User/Password changed !',
+'uri' =>'URI : ',
+'change' =>'Change',
+'root' =>'Root',
+'pages' =>' pages',
+'locked' => 'Locked',
+'unlock' => 'Unlock site',
+'onelock' => 'A site is locked, because of spidering. You can\'t do this for now',
+// PHPDIG_FORM
+'go' =>'Go ...',
+// SEARCH_FUNCTION
+'noresults' =>'No results'
+);
 ?>

+ 323 - 323
main/mySpace/access_details.php

@@ -1,323 +1,323 @@
-<?php
-// $Id:
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-    Copyright (c) 2009 Dokeos SPRL
-    Copyright (c) 2008 Furio Petrossi
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-*	This is the tracking library for Dokeos.
-*	Include/require it in your code to use its functionality.
-*
-*	@package dokeos.library
-==============================================================================
-
-* Calculates the time spent on the course
-* @param integer $user_id the user id
-* @param string $course_code the course code
-*	Funzione scritta da Mario per testare cose
-*/
-
-// name of the language file that needs to be included
-$language_file = array ('registration', 'index', 'tracking');
-
-// including the global Dokeos file
-require '../inc/global.inc.php';
-
-// including additional libraries
-require_once api_get_path(LIBRARY_PATH).'pchart/pData.class.php';
-require_once api_get_path(LIBRARY_PATH).'pchart/pChart.class.php';
-require_once api_get_path(LIBRARY_PATH).'pchart/pCache.class.php';
-
-// the section (for the tabs)
-$this_section = "session_my_space";
-
-
-/* MAIN */
-$user_id = Security::remove_XSS($_REQUEST['student']);
-$course_code = Security::remove_XSS($_REQUEST['course']);
-
-$connections = get_connections_to_course($user_id, $course_code);
-if (api_is_xml_http_request()) {
-	$type  = Security::remove_XSS($_GET['type']);
-	$main_year = $main_month_year = $main_day = array();
-	// get last 8 days/months
-	$last_days = 8;
-	$last_months = 5;
-	for ($i = $last_days; $i >= 0; $i--) {
-		$main_day[date ('d-m-Y', mktime () - $i * 3600 * 24)] = 0;
-	}
-	for ($i = $last_months; $i >= 0; $i--) {
-		$main_month_year[date ('m-Y', mktime () - $i * 30 * 3600 * 24)] = 0;
-	}
-
-	$i = 0;
-	if (is_array($connections) && count($connections) > 0) {
-		foreach ($connections as $key => $data) {
-			//creating the main array
-			$main_month_year[date('m-Y', $data['login'])] += float_format(($data['logout'] - $data['login']) / 60, 0);
-			$main_day[date('d-m-Y', $data['login'])] += float_format(($data['logout'] - $data['login']) / 60, 0);
-			if ($i > 500) {
-				break;
-			}
-			$i++;
-		}
-
-		switch ($type) {
-			case 'day':
-				$main_date = $main_day;
-				break;
-			case 'month':
-				$main_date = $main_month_year;
-				break;
-			case 'year':
-				$main_date = $main_year;
-				break;
-		}
-
-		// the nice graphics :D
-		$labels = array_keys($main_date);
-		if (count($main_date) == 1) {
-			$labels = $labels[0];
-			$main_date = $main_date[$labels];
-		}
-
-		$data_set = new pData;
-		$data_set->AddPoint($main_date, 'Q');
-		if (count($main_date)!= 1) {
-			$data_set->AddPoint($labels, 'Date');
-		}
-		$data_set->AddAllSeries();
-		$data_set->RemoveSerie('Date');
-		$data_set->SetAbsciseLabelSerie('Date');
-		$data_set->SetYAxisName(get_lang('Minutes', ''));
-		$graph_id = api_get_user_id().'AccessDetails'.api_get_course_id();
-		$data_set->AddAllSeries();
-
-		$cache = new pCache();
-		// the graph id
-		$data = $data_set->GetData();
-
-		if ($cache->IsInCache($graph_id, $data_set->GetData())) {
-		//if (0) {
-			//if we already created the img
-			//	echo 'in cache';
-			$img_file = $cache->GetHash($graph_id, $data_set->GetData());
-		} else {
-			// if the image does not exist in the archive/ folder
-			// Initialise the graph
-			$test = new pChart(760, 230);
-
-			//which schema of color will be used
-			$quant_resources = count($data[0]) - 1;
-			// Adding the color schemma
-			$test->loadColorPalette(api_get_path(LIBRARY_PATH).'pchart/palette/default.txt');
-
-			$test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 8);
-			$test->setGraphArea(70, 30, 680, 200);
-			$test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 240, 240, 240);
-			$test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230);
-			$test->drawGraphArea(255, 255, 255, TRUE);
-			$test->drawScale($data_set->GetData(), $data_set->GetDataDescription(), SCALE_START0, 150, 150, 150, TRUE, 0, 0);
-			$test->drawGrid(4, TRUE, 230, 230, 230, 50);
-			$test->setLineStyle(2);
-			// Draw the 0 line
-			$test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 6);
-			$test->drawTreshold(0, 143, 55, 72, TRUE, TRUE);
-
-			if (count($main_date) == 1) {
-				//Draw a graph
-				echo '<strong>'.$labels.'</strong><br/>';
-				$test->drawBarGraph($data_set->GetData(), $data_set->GetDataDescription(), TRUE);
-			} else {
-				//Draw the line graph
-				$test->drawLineGraph($data_set->GetData(), $data_set->GetDataDescription());
-				$test->drawPlotGraph($data_set->GetData(), $data_set->GetDataDescription(), 3, 2, 255, 255, 255);
-			}
-
-			// Finish the graph
-			$test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 8);
-
-			$test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 10);
-			$test->drawTitle(60, 22, get_lang('AccessDetails', ''), 50, 50, 50, 585);
-
-			//------------------
-			//echo 'not in cache';
-			$cache->WriteToCache($graph_id, $data_set->GetData(), $test);
-			ob_start();
-			$test->Stroke();
-			ob_end_clean();
-			$img_file = $cache->GetHash($graph_id, $data_set->GetData());
-		}
-		echo '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file.'">';
-	} else {
-		Display::display_warning_message (get_lang('GraphicNotAvailable'));
-	}
-	exit;
-}
-
-$nameTools = get_lang('AccessDetails');
-
-//StudentDetails
-if (isset($_GET['origin']) && strcmp($_GET['origin'], 'tracking_course') === 0) {
-	$interbreadcrumb[] = array ("url" => "../tracking/courseLog.php?cidReq=".Security::remove_XSS($_GET['course'])."&amp;studentlist=true&id_session=".api_get_session_id(), "name" => get_lang("Tracking"));
-	$interbreadcrumb[] = array ("url" => "myStudents.php?student=".Security::remove_XSS($_GET['student'])."&details=true&origin=".Security::remove_XSS($_GET['origin'])."&amp;course=".Security::remove_XSS($_GET['course']).'&amp;cidReq='.Security::remove_XSS($_GET['course']), "name" => get_lang('DetailsStudentInCourse'));
-	$interbreadcrumb[] = array ("url" => "javascript: void(0);", "name" => get_lang("Details"));
-} elseif (isset($_GET['origin']) && strcmp($_GET['origin'], 'user_course') === 0) {
-	$interbreadcrumb[] = array ("url" => "../user/user.php?cidReq=".Security::remove_XSS($_GET['course']), "name" => get_lang("Users"));
-	$interbreadcrumb[] = array ("url" => "myStudents.php?student=".Security::remove_XSS($_GET['student'])."&details=true&origin=".Security::remove_XSS($_GET['origin'])."&amp;course=".Security::remove_XSS($_GET['course']).'&amp;cidReq='.Security::remove_XSS($_GET['course']), "name" => get_lang('DetailsStudentInCourse'));
-	$interbreadcrumb[] = array ("url" => "javascript: void(0);", "name" => get_lang("Details"));
-}
-
-$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
-$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery-1.1.3.1.pack.js" type="text/javascript"></script>';
-$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.history_remote.pack.js" type="text/javascript"></script>';
-$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.tabs.pack.js" type="text/javascript"></script>';
-$htmlHeadXtra[] = '<link rel="stylesheet" href="../inc/lib/javascript/jquery.tabs.css" type="text/css" media="print, projection, screen">';
-
-$htmlHeadXtra[] = '<script type="text/javascript">
-$(function() {
-	$("#container-9").tabs({ remote: true});
-});
-
-</script>';
-
-Display :: display_header('');
-$tbl_userinfo_def = Database :: get_course_table(TABLE_USER_INFO);
-$main_user_info = api_get_user_info($user_id);
-
-$result_to_print = '';
-$main_date_array = array();
-
-foreach ($connections as $key => $data) {
-	$result_to_print .= '&nbsp;&nbsp;'.date('d-m-Y (H:i:s)', $data['login']).' - '.api_time_to_hms($data['logout'] - $data['login']).'<br />'."\n";
-}
-api_display_tool_title(get_lang('DetailsStudentInCourse'));
-echo '<div class="actions">';
-echo '<strong>'.get_lang('User').': '.api_get_person_name($main_user_info['firstName'], $main_user_info['lastName']).'</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>'.get_lang('Course').': '.$course_code.'</strong></div>';
-
-?>
-<div id="container-9">
-    <ul>
-        <li><a href="access_details.php?type=day&course=<?php echo $course_code?>&student=<?php echo $user_id?>"><span> <?php echo api_ucfirst(get_lang('Day')); ?></span></a></li>
-        <li><a href="access_details.php?type=month&course=<?php echo $course_code?>&student=<?php echo $user_id?>"><span><?php echo api_ucfirst(get_lang('MinMonth')); ?></span></a></li>
-    </ul>
-    <?php echo '<div id="show"></div>'; ?>
-</div>
-<?php
-
-echo '<div id="graph"></div><br />';
-echo '<div class="actions"><strong>', get_lang('DateAndTimeOfAccess'), ' - ', get_lang('Duration'), '</strong></div><br />';
-echo $result_to_print;
-
-/* Login time against logout time
-foreach ($connections as $key => $data) {
-    echo ("<tr><td>".date("d-m-Y (H:i:s)", $data['login'])."</td><td>".date("d-m-Y (H:i:s)", $data['logout'])."</td></tr>");
-}
-*/
-/*
-foreach ($connections as $key => $data) {
-    echo ("<tr><td>".date("d-m-Y (H:i:s)", $data['login'])."</td><td>".api_time_to_hms($data['logout'] - $data['login'])."</td></tr>");
-}
-echo ("</table>");
-*/
-
-Display:: display_footer();
-
-
-/*
------------------------------------------------------------
-	Functions
------------------------------------------------------------
-*/
-
-/**
- * Gets the connections to a course as an array of login and logout time
- *
- * @param unknown_type $user_id
- * @param unknown_type $course_code
- * @return unknown
- */
-function get_connections_to_course($user_id, $course_code) {
-	// Database table definitions
-    $tbl_track_course 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
-    $tbl_main			= Database :: get_main_table(TABLE_MAIN_COURSE);
-
-    $sql_query = 'SELECT visual_code as course_code FROM '.$tbl_main.' c WHERE code="'.Database::escape_string($course_code).'";';
-    $result = Database::query($sql_query, __FILE__, __LINE__);
-    $row_query = Database::fetch_array($result, 'ASSOC');
-    $course_true = isset($row_query['course_code']) ? $row_query['course_code']: $course_code;
-
-    $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . '
-    	WHERE user_id = ' . intval($user_id) . '
-    	AND course_code="' . Database::escape_string($course_true) . '" ORDER BY login_course_date ASC';
-
-    $rs = Database::query($sql, __FILE__, __LINE__);
-    $connections = array();
-
-    while ($row = Database::fetch_array($rs)) {
-
-        $login_date = $row['login_course_date'];
-        $logout_date = $row['logout_course_date'];
-
-        $timestamp_login_date = strtotime($login_date);
-        $timestamp_logout_date = strtotime($logout_date);
-
-        $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
-    }
-    return $connections;
-}
-
-/**
- * TODO: Not used, to b deleted?
- * Enter description here...
- *
- * @param unknown_type $user_id
- * @param unknown_type $course_code
- * @param unknown_type $year
- * @param unknown_type $month
- * @param unknown_type $day
- * @return unknown
- */
-function get_connections_to_course_by_time($user_id, $course_code, $year = '', $month = '', $day = '') {
-	// Database table definitions
-    $tbl_track_course 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
-    $tbl_main				= Database :: get_main_table(TABLE_MAIN_COURSE);
-
-    $sql_query = 'SELECT visual_code as course_code FROM '.$tbl_main.' c WHERE code="'.Database :: escape_string($course_code).'";';
-    $result = Database::query($sql_query, __FILE__, __LINE__);
-    $row_query = Database::fetch_array($result,'ASSOC');
-    $course_true = isset($row_query['course_code']) ? $row_query['course_code']: $course_code;
-
-    $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . '
-    				WHERE user_id = ' . intval($user_id) . '
-    				AND course_code="' . Database::escape_string($course_true) . '"
-    				ORDER BY login_course_date DESC';
-
-    $rs = Database::query($sql, __FILE__, __LINE__);
-    $connections = array();
-    while ($row = Database::fetch_array($rs)) {
-        $login_date = $row['login_course_date'];
-        $logout_date = $row['logout_course_date'];
-        $timestamp_login_date = strtotime($login_date);
-        $timestamp_logout_date = strtotime($logout_date);
-        $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
-    }
-    return $connections;
-}
+<?php
+// $Id:
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+    Copyright (c) 2009 Dokeos SPRL
+    Copyright (c) 2008 Furio Petrossi
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+*	This is the tracking library for Dokeos.
+*	Include/require it in your code to use its functionality.
+*
+*	@package dokeos.library
+==============================================================================
+
+* Calculates the time spent on the course
+* @param integer $user_id the user id
+* @param string $course_code the course code
+*	Funzione scritta da Mario per testare cose
+*/
+
+// name of the language file that needs to be included
+$language_file = array ('registration', 'index', 'tracking');
+
+// including the global Dokeos file
+require '../inc/global.inc.php';
+
+// including additional libraries
+require_once api_get_path(LIBRARY_PATH).'pchart/pData.class.php';
+require_once api_get_path(LIBRARY_PATH).'pchart/pChart.class.php';
+require_once api_get_path(LIBRARY_PATH).'pchart/pCache.class.php';
+
+// the section (for the tabs)
+$this_section = "session_my_space";
+
+
+/* MAIN */
+$user_id = Security::remove_XSS($_REQUEST['student']);
+$course_code = Security::remove_XSS($_REQUEST['course']);
+
+$connections = get_connections_to_course($user_id, $course_code);
+if (api_is_xml_http_request()) {
+	$type  = Security::remove_XSS($_GET['type']);
+	$main_year = $main_month_year = $main_day = array();
+	// get last 8 days/months
+	$last_days = 8;
+	$last_months = 5;
+	for ($i = $last_days; $i >= 0; $i--) {
+		$main_day[date ('d-m-Y', mktime () - $i * 3600 * 24)] = 0;
+	}
+	for ($i = $last_months; $i >= 0; $i--) {
+		$main_month_year[date ('m-Y', mktime () - $i * 30 * 3600 * 24)] = 0;
+	}
+
+	$i = 0;
+	if (is_array($connections) && count($connections) > 0) {
+		foreach ($connections as $key => $data) {
+			//creating the main array
+			$main_month_year[date('m-Y', $data['login'])] += float_format(($data['logout'] - $data['login']) / 60, 0);
+			$main_day[date('d-m-Y', $data['login'])] += float_format(($data['logout'] - $data['login']) / 60, 0);
+			if ($i > 500) {
+				break;
+			}
+			$i++;
+		}
+
+		switch ($type) {
+			case 'day':
+				$main_date = $main_day;
+				break;
+			case 'month':
+				$main_date = $main_month_year;
+				break;
+			case 'year':
+				$main_date = $main_year;
+				break;
+		}
+
+		// the nice graphics :D
+		$labels = array_keys($main_date);
+		if (count($main_date) == 1) {
+			$labels = $labels[0];
+			$main_date = $main_date[$labels];
+		}
+
+		$data_set = new pData;
+		$data_set->AddPoint($main_date, 'Q');
+		if (count($main_date)!= 1) {
+			$data_set->AddPoint($labels, 'Date');
+		}
+		$data_set->AddAllSeries();
+		$data_set->RemoveSerie('Date');
+		$data_set->SetAbsciseLabelSerie('Date');
+		$data_set->SetYAxisName(get_lang('Minutes', ''));
+		$graph_id = api_get_user_id().'AccessDetails'.api_get_course_id();
+		$data_set->AddAllSeries();
+
+		$cache = new pCache();
+		// the graph id
+		$data = $data_set->GetData();
+
+		if ($cache->IsInCache($graph_id, $data_set->GetData())) {
+		//if (0) {
+			//if we already created the img
+			//	echo 'in cache';
+			$img_file = $cache->GetHash($graph_id, $data_set->GetData());
+		} else {
+			// if the image does not exist in the archive/ folder
+			// Initialise the graph
+			$test = new pChart(760, 230);
+
+			//which schema of color will be used
+			$quant_resources = count($data[0]) - 1;
+			// Adding the color schemma
+			$test->loadColorPalette(api_get_path(LIBRARY_PATH).'pchart/palette/default.txt');
+
+			$test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 8);
+			$test->setGraphArea(70, 30, 680, 200);
+			$test->drawFilledRoundedRectangle(7, 7, 693, 223, 5, 240, 240, 240);
+			$test->drawRoundedRectangle(5, 5, 695, 225, 5, 230, 230, 230);
+			$test->drawGraphArea(255, 255, 255, TRUE);
+			$test->drawScale($data_set->GetData(), $data_set->GetDataDescription(), SCALE_START0, 150, 150, 150, TRUE, 0, 0);
+			$test->drawGrid(4, TRUE, 230, 230, 230, 50);
+			$test->setLineStyle(2);
+			// Draw the 0 line
+			$test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 6);
+			$test->drawTreshold(0, 143, 55, 72, TRUE, TRUE);
+
+			if (count($main_date) == 1) {
+				//Draw a graph
+				echo '<strong>'.$labels.'</strong><br/>';
+				$test->drawBarGraph($data_set->GetData(), $data_set->GetDataDescription(), TRUE);
+			} else {
+				//Draw the line graph
+				$test->drawLineGraph($data_set->GetData(), $data_set->GetDataDescription());
+				$test->drawPlotGraph($data_set->GetData(), $data_set->GetDataDescription(), 3, 2, 255, 255, 255);
+			}
+
+			// Finish the graph
+			$test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 8);
+
+			$test->setFontProperties(api_get_path(LIBRARY_PATH).'pchart/fonts/tahoma.ttf', 10);
+			$test->drawTitle(60, 22, get_lang('AccessDetails', ''), 50, 50, 50, 585);
+
+			//------------------
+			//echo 'not in cache';
+			$cache->WriteToCache($graph_id, $data_set->GetData(), $test);
+			ob_start();
+			$test->Stroke();
+			ob_end_clean();
+			$img_file = $cache->GetHash($graph_id, $data_set->GetData());
+		}
+		echo '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file.'">';
+	} else {
+		Display::display_warning_message (get_lang('GraphicNotAvailable'));
+	}
+	exit;
+}
+
+$nameTools = get_lang('AccessDetails');
+
+//StudentDetails
+if (isset($_GET['origin']) && strcmp($_GET['origin'], 'tracking_course') === 0) {
+	$interbreadcrumb[] = array ("url" => "../tracking/courseLog.php?cidReq=".Security::remove_XSS($_GET['course'])."&amp;studentlist=true&id_session=".api_get_session_id(), "name" => get_lang("Tracking"));
+	$interbreadcrumb[] = array ("url" => "myStudents.php?student=".Security::remove_XSS($_GET['student'])."&details=true&origin=".Security::remove_XSS($_GET['origin'])."&amp;course=".Security::remove_XSS($_GET['course']).'&amp;cidReq='.Security::remove_XSS($_GET['course']), "name" => get_lang('DetailsStudentInCourse'));
+	$interbreadcrumb[] = array ("url" => "javascript: void(0);", "name" => get_lang("Details"));
+} elseif (isset($_GET['origin']) && strcmp($_GET['origin'], 'user_course') === 0) {
+	$interbreadcrumb[] = array ("url" => "../user/user.php?cidReq=".Security::remove_XSS($_GET['course']), "name" => get_lang("Users"));
+	$interbreadcrumb[] = array ("url" => "myStudents.php?student=".Security::remove_XSS($_GET['student'])."&details=true&origin=".Security::remove_XSS($_GET['origin'])."&amp;course=".Security::remove_XSS($_GET['course']).'&amp;cidReq='.Security::remove_XSS($_GET['course']), "name" => get_lang('DetailsStudentInCourse'));
+	$interbreadcrumb[] = array ("url" => "javascript: void(0);", "name" => get_lang("Details"));
+}
+
+$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
+$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery-1.1.3.1.pack.js" type="text/javascript"></script>';
+$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.history_remote.pack.js" type="text/javascript"></script>';
+$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.tabs.pack.js" type="text/javascript"></script>';
+$htmlHeadXtra[] = '<link rel="stylesheet" href="../inc/lib/javascript/jquery.tabs.css" type="text/css" media="print, projection, screen">';
+
+$htmlHeadXtra[] = '<script type="text/javascript">
+$(function() {
+	$("#container-9").tabs({ remote: true});
+});
+
+</script>';
+
+Display :: display_header('');
+$tbl_userinfo_def = Database :: get_course_table(TABLE_USER_INFO);
+$main_user_info = api_get_user_info($user_id);
+
+$result_to_print = '';
+$main_date_array = array();
+
+foreach ($connections as $key => $data) {
+	$result_to_print .= '&nbsp;&nbsp;'.date('d-m-Y (H:i:s)', $data['login']).' - '.api_time_to_hms($data['logout'] - $data['login']).'<br />'."\n";
+}
+api_display_tool_title(get_lang('DetailsStudentInCourse'));
+echo '<div class="actions">';
+echo '<strong>'.get_lang('User').': '.api_get_person_name($main_user_info['firstName'], $main_user_info['lastName']).'</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>'.get_lang('Course').': '.$course_code.'</strong></div>';
+
+?>
+<div id="container-9">
+    <ul>
+        <li><a href="access_details.php?type=day&course=<?php echo $course_code?>&student=<?php echo $user_id?>"><span> <?php echo api_ucfirst(get_lang('Day')); ?></span></a></li>
+        <li><a href="access_details.php?type=month&course=<?php echo $course_code?>&student=<?php echo $user_id?>"><span><?php echo api_ucfirst(get_lang('MinMonth')); ?></span></a></li>
+    </ul>
+    <?php echo '<div id="show"></div>'; ?>
+</div>
+<?php
+
+echo '<div id="graph"></div><br />';
+echo '<div class="actions"><strong>', get_lang('DateAndTimeOfAccess'), ' - ', get_lang('Duration'), '</strong></div><br />';
+echo $result_to_print;
+
+/* Login time against logout time
+foreach ($connections as $key => $data) {
+    echo ("<tr><td>".date("d-m-Y (H:i:s)", $data['login'])."</td><td>".date("d-m-Y (H:i:s)", $data['logout'])."</td></tr>");
+}
+*/
+/*
+foreach ($connections as $key => $data) {
+    echo ("<tr><td>".date("d-m-Y (H:i:s)", $data['login'])."</td><td>".api_time_to_hms($data['logout'] - $data['login'])."</td></tr>");
+}
+echo ("</table>");
+*/
+
+Display:: display_footer();
+
+
+/*
+-----------------------------------------------------------
+	Functions
+-----------------------------------------------------------
+*/
+
+/**
+ * Gets the connections to a course as an array of login and logout time
+ *
+ * @param unknown_type $user_id
+ * @param unknown_type $course_code
+ * @return unknown
+ */
+function get_connections_to_course($user_id, $course_code) {
+	// Database table definitions
+    $tbl_track_course 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+    $tbl_main			= Database :: get_main_table(TABLE_MAIN_COURSE);
+
+    $sql_query = 'SELECT visual_code as course_code FROM '.$tbl_main.' c WHERE code="'.Database::escape_string($course_code).'";';
+    $result = Database::query($sql_query, __FILE__, __LINE__);
+    $row_query = Database::fetch_array($result, 'ASSOC');
+    $course_true = isset($row_query['course_code']) ? $row_query['course_code']: $course_code;
+
+    $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . '
+    	WHERE user_id = ' . intval($user_id) . '
+    	AND course_code="' . Database::escape_string($course_true) . '" ORDER BY login_course_date ASC';
+
+    $rs = Database::query($sql, __FILE__, __LINE__);
+    $connections = array();
+
+    while ($row = Database::fetch_array($rs)) {
+
+        $login_date = $row['login_course_date'];
+        $logout_date = $row['logout_course_date'];
+
+        $timestamp_login_date = strtotime($login_date);
+        $timestamp_logout_date = strtotime($logout_date);
+
+        $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
+    }
+    return $connections;
+}
+
+/**
+ * TODO: Not used, to b deleted?
+ * Enter description here...
+ *
+ * @param unknown_type $user_id
+ * @param unknown_type $course_code
+ * @param unknown_type $year
+ * @param unknown_type $month
+ * @param unknown_type $day
+ * @return unknown
+ */
+function get_connections_to_course_by_time($user_id, $course_code, $year = '', $month = '', $day = '') {
+	// Database table definitions
+    $tbl_track_course 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+    $tbl_main				= Database :: get_main_table(TABLE_MAIN_COURSE);
+
+    $sql_query = 'SELECT visual_code as course_code FROM '.$tbl_main.' c WHERE code="'.Database :: escape_string($course_code).'";';
+    $result = Database::query($sql_query, __FILE__, __LINE__);
+    $row_query = Database::fetch_array($result,'ASSOC');
+    $course_true = isset($row_query['course_code']) ? $row_query['course_code']: $course_code;
+
+    $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . '
+    				WHERE user_id = ' . intval($user_id) . '
+    				AND course_code="' . Database::escape_string($course_true) . '"
+    				ORDER BY login_course_date DESC';
+
+    $rs = Database::query($sql, __FILE__, __LINE__);
+    $connections = array();
+    while ($row = Database::fetch_array($rs)) {
+        $login_date = $row['login_course_date'];
+        $logout_date = $row['logout_course_date'];
+        $timestamp_login_date = strtotime($login_date);
+        $timestamp_logout_date = strtotime($logout_date);
+        $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
+    }
+    return $connections;
+}

+ 3 - 3
main/mySpace/coaches.php

@@ -82,7 +82,7 @@ if (isset($_GET["id_student"])) {
 			AND session_rel_course.id_coach=user.user_id".$order_clause;
 	}
 }
-$result_coachs = Database::query($sql_coachs, __FILE__, __LINE__);
+$result_coachs = Database::query($sql_coachs, __FILE__, __LINE__);
 
 if (api_is_western_name_order()) {
 	echo '<table class="data_table"><tr><th>'.get_lang('FirstName').'</th><th>'.get_lang('LastName').'</th><th>'.get_lang('ConnectionTime').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
@@ -105,7 +105,7 @@ if (Database::num_rows($result_coachs) > 0) {
 
 		if (isset($_GET["id_student"])) {
 			$sql_infos_coach = "SELECT lastname, firstname FROM $tbl_user WHERE user_id='$id_coach'";
-			$result_coachs_infos = Database::query($sql_infos_coach, __FILE__, __LINE__);
+			$result_coachs_infos = Database::query($sql_infos_coach, __FILE__, __LINE__);
 			$lastname = Database::result($result_coachs_infos, 0, "lastname");
 			$firstname = Database::result($result_coachs_infos, 0, "firstname");
 		} else {
@@ -114,7 +114,7 @@ if (Database::num_rows($result_coachs) > 0) {
 		}
 
 		$sql_connection_time = "SELECT login_date, logout_date FROM $tbl_track_login WHERE login_user_id ='$id_coach' AND logout_date <> 'null'";
-		$result_connection_time = Database::query($sql_connection_time, __FILE__, __LINE__);
+		$result_connection_time = Database::query($sql_connection_time, __FILE__, __LINE__);
 
 		$nb_seconds = 0;
 		while ($connections = Database::fetch_array($result_connection_time)) {

+ 172 - 172
main/mySpace/course.php

@@ -1,187 +1,187 @@
-<?php
-/*
- * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
- */
-ob_start();
-$nameTools = 'Cours';
-// name of the language file that needs to be included
-$language_file = array ('admin', 'registration', 'index', 'trad4all', 'tracking');
-$cidReset = true;
-
-require '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
-require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
-
-$this_section = "session_my_space";
+<?php
+/*
+ * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
+ */
+ob_start();
+$nameTools = 'Cours';
+// name of the language file that needs to be included
+$language_file = array ('admin', 'registration', 'index', 'trad4all', 'tracking');
+$cidReset = true;
+
+require '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
+require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+
+$this_section = "session_my_space";
 $id_session = intval($_GET['id_session']);
 
-api_block_anonymous_users();
-$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
-
-if (isset($_GET["id_session"]) && $_GET["id_session"] != "") {
-	$interbreadcrumb[] = array ("url" => "session.php", "name" => get_lang('Sessions'));
-}
-
-if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && isset($_GET["type"]) && $_GET["type"] == "coach") {
-	 $interbreadcrumb[] = array ("url" => "coaches.php", "name" => get_lang('Tutors'));
-}
-
-if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && isset($_GET["type"]) && $_GET["type"] == "student") {
-	 $interbreadcrumb[] = array ("url" => "student.php", "name" => get_lang('Students'));
-}
-
-if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && !isset($_GET["type"])) {
-	 $interbreadcrumb[] = array ("url" => "teachers.php", "name" => get_lang('Teachers'));
-}
-
-function count_courses() {
-	global $nb_courses;
-	return $nb_courses;
-}
-
+api_block_anonymous_users();
+$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
+
+if (isset($_GET["id_session"]) && $_GET["id_session"] != "") {
+	$interbreadcrumb[] = array ("url" => "session.php", "name" => get_lang('Sessions'));
+}
+
+if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && isset($_GET["type"]) && $_GET["type"] == "coach") {
+	 $interbreadcrumb[] = array ("url" => "coaches.php", "name" => get_lang('Tutors'));
+}
+
+if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && isset($_GET["type"]) && $_GET["type"] == "student") {
+	 $interbreadcrumb[] = array ("url" => "student.php", "name" => get_lang('Students'));
+}
+
+if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && !isset($_GET["type"])) {
+	 $interbreadcrumb[] = array ("url" => "teachers.php", "name" => get_lang('Teachers'));
+}
+
+function count_courses() {
+	global $nb_courses;
+	return $nb_courses;
+}
+
 //checking if the current coach is the admin coach
-$show_import_icon = false;
-
-if (api_get_setting('add_users_by_coach') == 'true') {
-	if (!api_is_platform_admin()) {
-		$sql = 'SELECT id_coach FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_session;
-		$rs = Database::query($sql, __FILE__, __LINE__);
-		if (Database::result($rs, 0, 0) != $_user['user_id']) {
-			api_not_allowed(true);
-		} else {
-			$show_import_icon=true;
-		}
-	}
-}
+$show_import_icon = false;
+
+if (api_get_setting('add_users_by_coach') == 'true') {
+	if (!api_is_platform_admin()) {
+		$sql = 'SELECT id_coach FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_session;
+		$rs = Database::query($sql, __FILE__, __LINE__);
+		if (Database::result($rs, 0, 0) != $_user['user_id']) {
+			api_not_allowed(true);
+		} else {
+			$show_import_icon=true;
+		}
+	}
+}
 
 Display :: display_header($nameTools);
-
-// Database Table Definitions
-$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_user_course 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_session_course 		= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session 				= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
+
+// Database Table Definitions
+$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_user_course 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_session_course 		= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session 				= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
 if (isset($_GET['action'])) {
 	if ($_GET['action'] == 'show_message') {
 		Display :: display_normal_message(stripslashes($_GET['message']), false);
-	}
-
-	if ($_GET['action'] == 'error_message') {
-		Display :: display_error_message(stripslashes($_GET['message']), false);
+	}
+
+	if ($_GET['action'] == 'error_message') {
+		Display :: display_error_message(stripslashes($_GET['message']), false);
 	}
 }
 
 if ($show_import_icon) {
 	echo "<div align=\"right\">";
 	echo '<a href="user_import.php?id_session='.$id_session.'&action=export&amp;type=xml">'.Display::return_icon('excel.gif', get_lang('ImportUserListXMLCSV')).'&nbsp;'.get_lang('ImportUserListXMLCSV').'</a>';
-	echo "</div><br />";
+	echo "</div><br />";
 }
-
-$a_courses = Tracking :: get_courses_followed_by_coach($_user['user_id'], $id_session);
-$nb_courses = count($a_courses);
-
-$table = new SortableTable('tracking_list_course', 'count_courses');
-$table -> set_header(0, get_lang('CourseTitle'), false, 'align="center"');
-$table -> set_header(1, get_lang('NbStudents'), false);
-$table -> set_header(2, get_lang('TimeSpentInTheCourse'), false);
-$table -> set_header(3, get_lang('AvgStudentsProgress'), false);
-$table -> set_header(4, get_lang('AvgCourseScore'), false);
-//$table -> set_header(5, get_lang('AvgExercisesScore'), false);// no code for this?
-$table -> set_header(5, get_lang('AvgMessages'), false);
-$table -> set_header(6, get_lang('AvgAssignments'), false);
-$table -> set_header(7, get_lang('Details'), false);
-
-$csv_header[] = array(
-	get_lang('CourseTitle', ''),
-	get_lang('NbStudents', ''),
-	get_lang('TimeSpentInTheCourse', ''),
-	get_lang('AvgStudentsProgress', ''),
-	get_lang('AvgCourseScore', ''),
-	//get_lang('AvgExercisesScore', ''),
-	get_lang('AvgMessages', ''),
-	get_lang('AvgAssignments', '')
-);
-
-if (is_array($a_courses)) {
-	foreach ($a_courses as $course_code) {
-		$nb_students_in_course = 0;
-		$a_students = array();
-		$course = CourseManager :: get_course_information($course_code);
-		$avg_assignments_in_course = $avg_messages_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = 0;
-
-		// students subscribed to the course throw a session
-		if (api_get_setting('use_session_mode') == 'true') {
-			$sql = 'SELECT id_user as user_id
-					FROM '.$tbl_session_course_user.'
-					WHERE course_code="'.Database :: escape_string($course_code).'"
-					AND id_session='.$id_session;
-			$rs = Database::query($sql, __FILE__, __LINE__);
-
-			while ($row = Database::fetch_array($rs)) {
-				if (!in_array($row['user_id'], $a_students)) {
-					$nb_students_in_course++;
-
-					// tracking datas
-					$avg_progress_in_course += Tracking :: get_avg_student_progress ($row['user_id'], $course_code);
-					$avg_score_in_course += Tracking :: get_avg_student_score ($row['user_id'], $course_code);
-					$avg_time_spent_in_course += Tracking :: get_time_spent_on_the_course ($row['user_id'], $course_code);
-					$avg_messages_in_course += Tracking :: count_student_messages ($row['user_id'], $course_code);
-					$avg_assignments_in_course += Tracking :: count_student_assignments ($row['user_id'], $course_code);
-					$a_students[] = $row['user_id'];
-				}
-			}
-		}
-		if ($nb_students_in_course > 0) {
-			$avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
-			$avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2).'%';
-			$avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2).'%';
-			$avg_messages_in_course = round($avg_messages_in_course / $nb_students_in_course, 2);
-			$avg_assignments_in_course = round($avg_assignments_in_course / $nb_students_in_course, 2);
-		} else {
-			$avg_time_spent_in_course = null;
-			$avg_progress_in_course = null;
-			$avg_score_in_course = null;
-			$avg_messages_in_course = null;
-			$avg_assignments_in_course = null;
-		}
-
-		$table_row = array();
-		$table_row[] = $course['title'];
-		$table_row[] = $nb_students_in_course;
-		$table_row[] = $avg_time_spent_in_course;
-		$table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course.'%';
-		$table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course.'%';
-		$table_row[] = $avg_messages_in_course;
-		$table_row[] = $avg_assignments_in_course;
-		$table_row[] = '<a href="../tracking/courseLog.php?cidReq='.$course_code.'&studentlist=true&id_session='.$id_session.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
-
-		$csv_content[] = array (
-			$course['title'],
-			$nb_students_in_course,
-			$avg_time_spent_in_course,
-			is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
-			is_null($avg_score_in_course) ? null : $avg_score_in_course.'%',
-			$avg_messages_in_course,
-			$avg_assignments_in_course,
-		);
-
-		$table -> addRow($table_row, 'align="right"');
-	}
-
-	// $csv_content = array_merge($csv_header, $csv_content); // Before this statement you are allowed to sort (in different way) the array $csv_content.
-}
-$table -> setColAttributes(0, array('align' => 'left'));
-$table -> setColAttributes(7, array('align' => 'center'));
-$table -> display();
-
-/*
- ==============================================================================
-		FOOTER
- ==============================================================================
- */
-
-Display :: display_footer();
+
+$a_courses = Tracking :: get_courses_followed_by_coach($_user['user_id'], $id_session);
+$nb_courses = count($a_courses);
+
+$table = new SortableTable('tracking_list_course', 'count_courses');
+$table -> set_header(0, get_lang('CourseTitle'), false, 'align="center"');
+$table -> set_header(1, get_lang('NbStudents'), false);
+$table -> set_header(2, get_lang('TimeSpentInTheCourse'), false);
+$table -> set_header(3, get_lang('AvgStudentsProgress'), false);
+$table -> set_header(4, get_lang('AvgCourseScore'), false);
+//$table -> set_header(5, get_lang('AvgExercisesScore'), false);// no code for this?
+$table -> set_header(5, get_lang('AvgMessages'), false);
+$table -> set_header(6, get_lang('AvgAssignments'), false);
+$table -> set_header(7, get_lang('Details'), false);
+
+$csv_header[] = array(
+	get_lang('CourseTitle', ''),
+	get_lang('NbStudents', ''),
+	get_lang('TimeSpentInTheCourse', ''),
+	get_lang('AvgStudentsProgress', ''),
+	get_lang('AvgCourseScore', ''),
+	//get_lang('AvgExercisesScore', ''),
+	get_lang('AvgMessages', ''),
+	get_lang('AvgAssignments', '')
+);
+
+if (is_array($a_courses)) {
+	foreach ($a_courses as $course_code) {
+		$nb_students_in_course = 0;
+		$a_students = array();
+		$course = CourseManager :: get_course_information($course_code);
+		$avg_assignments_in_course = $avg_messages_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = 0;
+
+		// students subscribed to the course throw a session
+		if (api_get_setting('use_session_mode') == 'true') {
+			$sql = 'SELECT id_user as user_id
+					FROM '.$tbl_session_course_user.'
+					WHERE course_code="'.Database :: escape_string($course_code).'"
+					AND id_session='.$id_session;
+			$rs = Database::query($sql, __FILE__, __LINE__);
+
+			while ($row = Database::fetch_array($rs)) {
+				if (!in_array($row['user_id'], $a_students)) {
+					$nb_students_in_course++;
+
+					// tracking datas
+					$avg_progress_in_course += Tracking :: get_avg_student_progress ($row['user_id'], $course_code);
+					$avg_score_in_course += Tracking :: get_avg_student_score ($row['user_id'], $course_code);
+					$avg_time_spent_in_course += Tracking :: get_time_spent_on_the_course ($row['user_id'], $course_code);
+					$avg_messages_in_course += Tracking :: count_student_messages ($row['user_id'], $course_code);
+					$avg_assignments_in_course += Tracking :: count_student_assignments ($row['user_id'], $course_code);
+					$a_students[] = $row['user_id'];
+				}
+			}
+		}
+		if ($nb_students_in_course > 0) {
+			$avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
+			$avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2).'%';
+			$avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2).'%';
+			$avg_messages_in_course = round($avg_messages_in_course / $nb_students_in_course, 2);
+			$avg_assignments_in_course = round($avg_assignments_in_course / $nb_students_in_course, 2);
+		} else {
+			$avg_time_spent_in_course = null;
+			$avg_progress_in_course = null;
+			$avg_score_in_course = null;
+			$avg_messages_in_course = null;
+			$avg_assignments_in_course = null;
+		}
+
+		$table_row = array();
+		$table_row[] = $course['title'];
+		$table_row[] = $nb_students_in_course;
+		$table_row[] = $avg_time_spent_in_course;
+		$table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course.'%';
+		$table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course.'%';
+		$table_row[] = $avg_messages_in_course;
+		$table_row[] = $avg_assignments_in_course;
+		$table_row[] = '<a href="../tracking/courseLog.php?cidReq='.$course_code.'&studentlist=true&id_session='.$id_session.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+
+		$csv_content[] = array (
+			$course['title'],
+			$nb_students_in_course,
+			$avg_time_spent_in_course,
+			is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
+			is_null($avg_score_in_course) ? null : $avg_score_in_course.'%',
+			$avg_messages_in_course,
+			$avg_assignments_in_course,
+		);
+
+		$table -> addRow($table_row, 'align="right"');
+	}
+
+	// $csv_content = array_merge($csv_header, $csv_content); // Before this statement you are allowed to sort (in different way) the array $csv_content.
+}
+$table -> setColAttributes(0, array('align' => 'left'));
+$table -> setColAttributes(7, array('align' => 'center'));
+$table -> display();
+
+/*
+ ==============================================================================
+		FOOTER
+ ==============================================================================
+ */
+
+Display :: display_footer();

+ 1208 - 1208
main/mySpace/index.php

@@ -1,1208 +1,1208 @@
-<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
-/* For licensing terms, see /dokeos_license.txt */
-/**
- * @todo use constant for $this_section
- */
-// name of the language file that needs to be included
-$language_file = array ('registration', 'index', 'tracking');
-
-// resetting the course id
-$cidReset = true;
-
-// including the global Dokeos file
-require '../inc/global.inc.php';
-
-// including additional libraries
-require api_get_path(LIBRARY_PATH).'tracking.lib.php';
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
-require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
-
-// the section (for the tabs)
-$this_section = "session_my_space";
-
-ob_start();
-
-$export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
-$csv_content = array();
-
-$nameTools = get_lang("MySpace");
-
-// access control
-api_block_anonymous_users();
-if (!$export_csv) {
-	Display :: display_header($nameTools);
-} else {
-	if ($_GET['view'] == 'admin' AND $_GET['display'] == 'useroverview') {
-		export_tracking_user_overview();
-		exit;
-	}
-}
-
-// Database table definitions
-$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_class 					= Database :: get_main_table(TABLE_MAIN_CLASS);
-$tbl_sessions 				= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_course 		= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_user 			= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-$tbl_admin					= Database :: get_main_table(TABLE_MAIN_ADMIN);
-
-
-/********************
- * FUNCTIONS
- ********************/
-
-function count_teacher_courses() {
-	global $nb_teacher_courses;
-	return $nb_teacher_courses;
-}
-
-function count_coaches() {
-	global $total_no_coaches;
-	return $total_no_coaches;
-}
-
-function sort_users($a, $b) {
-	return api_strcmp(trim(api_strtolower($a[$_SESSION['tracking_column']])), trim(api_strtolower($b[$_SESSION['tracking_column']])));
-}
-
-function rsort_users($a, $b) {
-	return api_strcmp(trim(api_strtolower($b[$_SESSION['tracking_column']])), trim(api_strtolower($a[$_SESSION['tracking_column']])));
-}
-
-
-/**************************
- * MAIN CODE
- ***************************/
-
-$is_coach = api_is_coach();
-$is_platform_admin = api_is_platform_admin();
-
-$view = isset($_GET['view']) ? $_GET['view'] : 'teacher';
-
-$menu_items = array();
-global $_configuration;
-
-if (api_is_allowed_to_create_course()) {
-	$sql_nb_cours = "SELECT course_rel_user.course_code, course.title
-			FROM $tbl_course_user as course_rel_user
-			INNER JOIN $tbl_course as course
-				ON course.code = course_rel_user.course_code
-			WHERE course_rel_user.user_id='".$_user['user_id']."' AND course_rel_user.status='1'
-			ORDER BY course.title";
-
-	if ($_configuration['multiple_access_urls'] == true) {
-		$tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1) {
-			$sql_nb_cours = "	SELECT course_rel_user.course_code, course.title
-				FROM $tbl_course_user as course_rel_user
-				INNER JOIN $tbl_course as course
-					ON course.code = course_rel_user.course_code
-			  	INNER JOIN $tbl_course_rel_access_url course_rel_url
-					ON (course_rel_url.course_code= course.code)
-			  	WHERE access_url_id =  $access_url_id  AND course_rel_user.user_id='".$_user['user_id']."' AND course_rel_user.status='1'
-			  	ORDER BY course.title";
-		}
-	}
-
-	$result_nb_cours = Database::query($sql_nb_cours, __FILE__, __LINE__);
-	$courses = Database::store_result($result_nb_cours);
-
-	$nb_teacher_courses = count($courses);
-	if ($nb_teacher_courses) {
-		if (!$is_coach && !$is_platform_admin) {
-			$view = 'teacher';
-		}
-		if ($view == 'teacher') {
-			$menu_items[] = get_lang('TeacherInterface');
-			$title = get_lang('YourCourseList');
-		} else {
-			$menu_items[] = '<a href="'.api_get_self().'?view=teacher">'.get_lang('TeacherInterface').'</a>';
-		}
-	}
-}
-if ($is_coach) {
-	if ($nb_teacher_courses == 0 && !$is_platform_admin) {
-		$view = 'coach';
-	}
-	if ($view == 'coach') {
-		$menu_items[] = get_lang('CoachInterface');
-		$title = get_lang('YourStatistics');
-	} else {
-		$menu_items[] = '<a href="'.api_get_self().'?view=coach">'.get_lang('CoachInterface').'</a>';
-	}
-}
-if ($is_platform_admin) {
-	if (!$is_coach && $nb_teacher_courses == 0) {
-		$view = 'admin';
-	}
-	if ($view == 'admin') {
-		$menu_items[] = get_lang('AdminInterface');
-		$title = get_lang('CoachList');
-	} else {
-		$menu_items[] = '<a href="'.api_get_self().'?view=admin">'.get_lang('AdminInterface').'</a>';
-	}
-}
-if ($_user['status'] == DRH) {
-	$view = 'drh';
-	$title = get_lang('DrhInterface');
-	$menu_items[] = '<a href="'.api_get_self().'?view=drh">'.get_lang('DrhInterface').'</a>';
-}
-
-echo '<div class="actions">';
-$nb_menu_items = count($menu_items);
-if ($nb_menu_items > 1) {
-	foreach ($menu_items as $key => $item) {
-		echo $item;
-		if ($key != $nb_menu_items - 1) {
-			echo ' | ';
-		}
-	}
-}
-echo '<a href="javascript: void(0);" onclick="javascript: window.print()"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a> ';
-echo (isset($_GET['display']) &&  $_GET['display'] == 'useroverview')? '' : '<a href="'.api_get_self().'?export=csv&view='.$view.'"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>';
-echo '</div>';
-echo '<h4>'.$title.'</h4>';
-
-if ($_user['status'] == DRH && $view == 'drh') {
-	$students = Tracking :: get_student_followed_by_drh($_user['user_id']);
-	$courses_of_the_platform = CourseManager :: get_real_course_list();
-	foreach ($courses_of_the_platform as $course) {
-		$courses[$course['code']] = $course['code'];
-	}
-}
-
-if ($is_coach && $view == 'coach') {
-	$students = Tracking :: get_student_followed_by_coach($_user['user_id']);
-	$courses = Tracking :: get_courses_followed_by_coach($_user['user_id']);
-}
-
-if ($view == 'coach' || $view == 'drh') {
-	$nb_students = count($students);
-
-	$total_time_spent = 0;
-	$total_courses = 0;
-	$avg_total_progress = 0;
-	$avg_results_to_exercises = 0;
-	$nb_inactive_students = 0;
-	$nb_posts = $nb_assignments = 0;
-	foreach ($students as $student_id) {
-		// inactive students
-		$last_connection_date = Tracking :: get_last_connection_date($student_id, true, true);
-		if ($last_connection_date != false) {
-			/*
-			list($last_connection_date, $last_connection_hour) = explode(' ', $last_connection_date);
-			$last_connection_date = explode('-', $last_connection_date);
-			$last_connection_hour = explode(':', $last_connection_hour);
-			$last_connection_hour[0];
-			$last_connection_time = mktime($last_connection_hour[0], $last_connection_hour[1], $last_connection_hour[2], $last_connection_date[1], $last_connection_date[2], $last_connection_date[0]);
-			*/
-			if (time() - (3600 * 24 * 7) > $last_connection_time) {
-				$nb_inactive_students++;
-			}
-		} else {
-			$nb_inactive_students++;
-		}
-
-		$total_time_spent += Tracking :: get_time_spent_on_the_platform($student_id);
-		$total_courses += Tracking :: count_course_per_student($student_id);
-		$avg_student_progress = $avg_student_score = 0;
-		$nb_courses_student = 0;
-		foreach ($courses as $course_code) {
-			if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
-				$nb_courses_student++;
-				$nb_posts += Tracking :: count_student_messages($student_id, $course_code);
-				$nb_assignments += Tracking :: count_student_assignments($student_id, $course_code);
-				$avg_student_progress += Tracking :: get_avg_student_progress($student_id, $course_code);
-				$avg_student_score += Tracking :: get_avg_student_score($student_id, $course_code);
-				if ($nb_posts !== null && $nb_assignments !== null && $avg_student_progress !== null && $avg_student_score !== null) {
-					//if one of these scores is null, it means that we had a problem connecting to the right database, so don't count it in
-					$nb_courses_student++;
-				}
-			}
-		}
-		// average progress of the student
-		$avg_student_progress = $avg_student_progress / $nb_courses_student;
-		$avg_total_progress += $avg_student_progress;
-
-		// average test results of the student
-		$avg_student_score = $avg_student_score / $nb_courses_student;
-		$avg_results_to_exercises += $avg_student_score;
-	}
-
-	if ($nb_students > 0) {
-		// average progress
-		$avg_total_progress = $avg_total_progress / $nb_students;
-		// average results to the tests
-		$avg_results_to_exercises = $avg_results_to_exercises / $nb_students;
-		// average courses by student
-		$avg_courses_per_student = round($total_courses / $nb_students, 2);
-		// average time spent on the platform
-		$avg_time_spent = $total_time_spent / $nb_students;
-		// average assignments
-		$nb_assignments = $nb_assignments / $nb_students;
-		// average posts
-		$nb_posts = $nb_posts / $nb_students;
-	} else {
-		$avg_total_progress = null;
-		$avg_results_to_exercises = null;
-		$avg_courses_per_student = null;
-		$avg_time_spent = null;
-		$nb_assignments = null;
-		$nb_posts = null;
-	}
-
-	if ($export_csv) {
-		//csv part
-		$csv_content[] = array(get_lang('Probationers', ''));
-		$csv_content[] = array(get_lang('InactivesStudents', ''), $nb_inactive_students );
-		$csv_content[] = array(get_lang('AverageTimeSpentOnThePlatform', ''), $avg_time_spent);
-		$csv_content[] = array(get_lang('AverageCoursePerStudent', ''), $avg_courses_per_student);
-		$csv_content[] = array(get_lang('AverageProgressInLearnpath', ''), is_null($avg_total_progress) ? null : round($avg_total_progress, 2).'%');
-		$csv_content[] = array(get_lang('AverageResultsToTheExercices', ''), is_null($avg_results_to_exercises) ? null : round($avg_results_to_exercises, 2).'%');
-		$csv_content[] = array(get_lang('AveragePostsInForum', ''), $nb_posts);
-		$csv_content[] = array(get_lang('AverageAssignments', ''), $nb_assignments);
-		$csv_content[] = array();
-	} else {
-		// html part
-		echo '
-		 <div class="report_section">
-			<h4>
-				<a href="student.php"><img src="'.api_get_path(WEB_IMG_PATH).'students.gif">&nbsp;'.get_lang('Probationers').' ('.$nb_students.')'.'</a>
-			</h4>
-			<table class="data_table">
-				<tr>
-					<td>
-						'.get_lang('InactivesStudents').'
-					</td>
-					<td align="right">
-						'.$nb_inactive_students.'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('AverageTimeSpentOnThePlatform').'
-					</td>
-					<td align="right">
-						'.(is_null($avg_time_spent) ? '' : api_time_to_hms($avg_time_spent)).'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('AverageCoursePerStudent').'
-					</td>
-					<td align="right">
-						'.(is_null($avg_courses_per_student) ? '' : $avg_courses_per_student).'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('AverageProgressInLearnpath').'
-					</td>
-					<td align="right">
-						'.(is_null($avg_total_progress) ? '' : round($avg_total_progress, 2).'%').'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('AverageResultsToTheExercices').'
-					</td>
-					<td align="right">
-						'.(is_null($avg_results_to_exercises) ? '' : round($avg_results_to_exercises, 2).'%').'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('AveragePostsInForum').'
-					</td>
-					<td align="right">
-						'.(is_null($nb_posts) ? '' : round($nb_posts, 2)).'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('AverageAssignments').'
-					</td>
-					<td align="right">
-						'.(is_null($nb_assignments) ? '' : round($nb_assignments, 2)).'
-					</td>
-				</tr>
-			</table>
-			<a href="student.php">'.get_lang('SeeStudentList').'</a>
-		 </div>';
-	}
-}
-if ($view == 'coach') {
-	/****************************************
-	 * Infos about sessions of the coach
-	 ****************************************/
-	$sessions = Tracking :: get_sessions_coached_by_user($_user['user_id']);
-	$nb_sessions = count($sessions);
-	$nb_sessions_past = $nb_sessions_future = $nb_sessions_current = 0;
-	$courses = array();
-	foreach ($sessions as $session) {
-		if ($session['date_start'] == '0000-00-00') {
-			$nb_sessions_current ++;
-		} else {
-			$date_start = explode('-', $session['date_start']);
-			$time_start = mktime(0, 0, 0, $date_start[1], $date_start[2], $date_start[0]);
-			$date_end = explode('-', $session['date_end']);
-			$time_end = mktime(0, 0, 0, $date_end[1], $date_end[2], $date_end[0]);
-			if ($time_start < time() && time() < $time_end) {
-				$nb_sessions_current++;
-			}
-			elseif (time() < $time_start) {
-				$nb_sessions_future++;
-			}
-			elseif (time() > $time_end) {
-				$nb_sessions_past++;
-			}
-		}
-		$courses = array_merge($courses, Tracking::get_courses_list_from_session($session['id']));
-	}
-
-	if ($nb_sessions > 0) {
-		$nb_courses_per_session = round(count($courses) / $nb_sessions, 2);
-		$nb_students_per_session = round($nb_students / $nb_sessions, 2);
-	} else {
-		$nb_courses_per_session = null;
-		$nb_students_per_session = null;
-	}
-
-
-	if ($export_csv) {
-		//csv part
-		$csv_content[] = array(get_lang('Sessions', ''));
-		$csv_content[] = array(get_lang('NbActiveSessions', '').';'.$nb_sessions_current);
-		$csv_content[] = array(get_lang('NbPastSessions', '').';'.$nb_sessions_past);
-		$csv_content[] = array(get_lang('NbFutureSessions', '').';'.$nb_sessions_future);
-		$csv_content[] = array(get_lang('NbStudentPerSession', '').';'.$nb_students_per_session);
-		$csv_content[] = array(get_lang('NbCoursesPerSession', '').';'.$nb_courses_per_session);
-		$csv_content[] = array();
-	} else {
-		// html part
-		echo '
-		 <div class="report_section">
-			<h4>
-				<a href="session.php"><img src="'.api_get_path(WEB_IMG_PATH).'sessions.gif">&nbsp;'.get_lang('Sessions').' ('.$nb_sessions.')'.'</a>
-			</h4>
-			<table class="data_table">
-				<tr>
-					<td>
-						'.get_lang('NbActiveSessions').'
-					</td>
-					<td align="right">
-						'.$nb_sessions_current.'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('NbPastSessions').'
-					</td>
-					<td align="right">
-						'.$nb_sessions_past.'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('NbFutureSessions').'
-					</td>
-					<td align="right">
-						'.$nb_sessions_future.'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('NbStudentPerSession').'
-					</td>
-					<td align="right">
-						'.(is_null($nb_students_per_session) ? '' : $nb_students_per_session).'
-					</td>
-				</tr>
-				<tr>
-					<td>
-						'.get_lang('NbCoursesPerSession').'
-					</td>
-					<td align="right">
-						'.(is_null($nb_courses_per_session) ? '' : $nb_courses_per_session).'
-					</td>
-				</tr>
-			</table>
-			<a href="session.php">'.get_lang('SeeSessionList').'</a>
-		 </div>';
-	 }
-}
-
-echo '<div class="clear">&nbsp;</div>';
-
-if (api_is_allowed_to_create_course() && $view == 'teacher') {
-	if ($nb_teacher_courses) {
-
-		$table = new SortableTable('tracking_list_course', 'count_teacher_courses');
-		$parameters['view'] = 'teacher';
-		$parameters['class'] = 'data_table';
-
-		$table->set_additional_parameters($parameters);
-		$table -> set_header(0, get_lang('CourseTitle'), false, 'align="center"');
-		$table -> set_header(1, get_lang('NbStudents'), false);
-		$table -> set_header(2, get_lang('AvgTimeSpentInTheCourse').Display :: return_icon('info3.gif', get_lang('TimeOfActiveByTraining'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
-		$table -> set_header(3, get_lang('AvgStudentsProgress').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
-		$table -> set_header(4, get_lang('AvgCourseScore').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
-		$table -> set_header(5, get_lang('AvgExercisesScore').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
-		$table -> set_header(6, get_lang('AvgMessages'), false);
-		$table -> set_header(7, get_lang('AvgAssignments'), false);
-		$table -> set_header(8, get_lang('Details'), false);
-
-		$csv_content[] = array (
-			get_lang('CourseTitle', ''),
-			get_lang('NbStudents', ''),
-			get_lang('AvgTimeSpentInTheCourse', ''),
-			get_lang('AvgStudentsProgress', ''),
-			get_lang('AvgCourseScore', ''),
-			get_lang('AvgExercisesScore', ''),
-			get_lang('AvgMessages', ''),
-			get_lang('AvgAssignments', '')
-		);
-
-		$a_course_students = array();
-
-		foreach ($courses as $course) {
-			$course_code = $course['course_code'];
-			$avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0;
-
-			// students directly subscribed to the course
-			$sql = "SELECT user_id FROM $tbl_course_user as course_rel_user WHERE course_rel_user.status='5' AND course_rel_user.course_code='$course_code'";
-			$rs = Database::query($sql, __FILE__, __LINE__);
-			while ($row = Database::fetch_array($rs)) {
-				$nb_students_in_course++;
-
-				// tracking datas
-				$avg_progress_in_course += Tracking :: get_avg_student_progress ($row['user_id'], $course_code);
-				$avg_score_in_course += Tracking :: get_avg_student_score ($row['user_id'], $course_code);
-				$avg_score_in_exercise += Tracking :: get_avg_student_exercise_score ($row['user_id'], $course_code);
-				$avg_time_spent_in_course += Tracking :: get_time_spent_on_the_course ($row['user_id'], $course_code);
-				$avg_messages_in_course += Tracking :: count_student_messages ($row['user_id'], $course_code);
-				$avg_assignments_in_course += Tracking :: count_student_assignments ($row['user_id'], $course_code);
-				$a_course_students[] = $row['user_id'];
-			}
-
-			// students subscribed to the course through a session
-			if (api_get_setting('use_session_mode') == 'true') {
-				$sql = 'SELECT id_user as user_id
-					FROM '.$tbl_session_course_user.'
-					WHERE course_code="'.addslashes($course_code).'" ORDER BY course_code';
-				$rs = Database::query($sql, __FILE__, __LINE__);
-				while ($row = Database::fetch_array($rs)) {
-					if (!in_array($row['user_id'], $a_course_students)) {
-						$nb_students_in_course++;
-
-						// tracking datas
-						$avg_progress_in_course += Tracking :: get_avg_student_progress ($row['user_id'], $course_code);
-						$avg_score_in_course += Tracking :: get_avg_student_score ($row['user_id'], $course_code);
-						$avg_score_in_exercise += Tracking :: get_avg_student_exercise_score ($row['user_id'], $course_code);
-						$avg_time_spent_in_course += Tracking :: get_time_spent_on_the_course ($row['user_id'], $course_code);
-						$avg_messages_in_course += Tracking :: count_student_messages ($row['user_id'], $course_code);
-						$avg_assignments_in_course += Tracking :: count_student_assignments ($row['user_id'], $course_code);
-						$a_course_students[] = $row['user_id'];
-					}
-				}
-			}
-
-			if ($nb_students_in_course > 0) {
-				$avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
-				$avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
-				$avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2);
-				$avg_score_in_exercise = round($avg_score_in_exercise / $nb_students_in_course, 2);
-				$avg_messages_in_course = round($avg_messages_in_course / $nb_students_in_course, 2);
-				$avg_assignments_in_course = round($avg_assignments_in_course / $nb_students_in_course, 2);
-			} else {
-				$avg_time_spent_in_course = null;
-				$avg_progress_in_course = null;
-				$avg_score_in_course = null;
-				$avg_score_in_exercise = null;
-				$avg_messages_in_course = null;
-				$avg_assignments_in_course = null;
-			}
-
-			$table_row = array();
-			$table_row[] = $course['title'];
-			$table_row[] = $nb_students_in_course;
-			$table_row[] = $avg_time_spent_in_course;
-			$table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course.'%';
-			$table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course.'%';
-			$table_row[] = is_null($avg_score_in_exercise) ? '' : $avg_score_in_exercise.'%';
-			$table_row[] = $avg_messages_in_course;
-			$table_row[] = $avg_assignments_in_course;
-			//set the "from" value to know if I access the Reporting by the Dokeos tab or the course link
-			$table_row[] = '<center><a href="../tracking/courseLog.php?cidReq='.$course_code.'&studentlist=true&from=myspace"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></center>';
-
-			$csv_content[] = array(
-				api_html_entity_decode($course['title'], ENT_QUOTES, $charset),
-				$nb_students_in_course,
-				$avg_time_spent_in_course,
-				is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
-				is_null($avg_score_in_course) ? null : $avg_score_in_course.'%',
-				is_null($avg_score_in_exercise) ? null : $avg_score_in_exercise.'%',
-				$avg_messages_in_course,
-				$avg_assignments_in_course,
-			);
-
-			$table -> addRow($table_row, 'align="right"');
-
-			$a_course_students = array();
-		}
-		$table -> updateColAttributes(0, array('align' => 'left'));
-		$table -> updateColAttributes(7, array('align' => 'center'));
-		$table -> display();
-	}
-}
-
-if ($is_platform_admin && $view == 'admin') {
-	echo '<a href="'.api_get_self().'?view=admin&amp;display=coaches">'.get_lang('DisplayCoaches').'</a> | ';
-	echo '<a href="'.api_get_self().'?view=admin&amp;display=useroverview">'.get_lang('DisplayUserOverview').'</a>';
-	if ($_GET['display'] == 'useroverview') {
-		echo ' | <a href="'.api_get_self().'?view=admin&amp;display=useroverview&amp;export=options">'.get_lang('ExportUserOverviewOptions').'</a>';
-	}
-
-	if ($_GET['display'] === 'useroverview') {
-		display_tracking_user_overview();
-	} else {
-		if ($export_csv) {
-			$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-		} else {
-			$is_western_name_order = api_is_western_name_order();
-		}
-		$sort_by_first_name = api_sort_by_first_name();
-		$tracking_column = isset($_GET['tracking_list_coaches_column']) ? $_GET['tracking_list_coaches_column'] : ($is_western_name_order xor $sort_by_first_name) ? 1 : 0;
-		$tracking_direction = (isset($_GET['tracking_list_coaches_direction']) && in_array(strtoupper($_GET['tracking_list_coaches_direction']), array('ASC', 'DESC', 'ASCENDING', 'DESCENDING', '0', '1'))) ? $_GET['tracking_list_coaches_direction'] : 'DESC';
-		// Prepare array for column order - when impossible, use some of user names.
-		if ($is_western_name_order) {
-			$order = array(0 => 'firstname', 1 => 'lastname', 2 => ($sort_by_first_name ? 'firstname' : 'lastname'), 3 => 'login_date', 4 => ($sort_by_first_name ? 'firstname' : 'lastname'), 5 => ($sort_by_first_name ? 'firstname' : 'lastname'));
-		} else {
-			$order = array(0 => 'lastname', 1 => 'firstname', 2 => ($sort_by_first_name ? 'firstname' : 'lastname'), 3 => 'login_date', 4 => ($sort_by_first_name ? 'firstname' : 'lastname'), 5 => ($sort_by_first_name ? 'firstname' : 'lastname'));
-		}
-
-		$table = new SortableTable('tracking_list_coaches', 'count_coaches', null, ($is_western_name_order xor $sort_by_first_name) ? 1 : 0);
-		$parameters['view'] = 'admin';
-		$table->set_additional_parameters($parameters);
-		if ($is_western_name_order) {
-			$table -> set_header(0, get_lang('FirstName'), true, 'align="center"');
-			$table -> set_header(1, get_lang('LastName'), true, 'align="center"');
-		} else {
-			$table -> set_header(0, get_lang('LastName'), true, 'align="center"');
-			$table -> set_header(1, get_lang('FirstName'), true, 'align="center"');
-		}
-		$table -> set_header(2, get_lang('TimeSpentOnThePlatform'), false);
-		$table -> set_header(3, get_lang('LastConnexion'), true, 'align="center"');
-		$table -> set_header(4, get_lang('NbStudents'), false);
-		$table -> set_header(5, get_lang('CountCours'), false);
-		$table -> set_header(6, get_lang('NumberOfSessions'), false);
-		$table -> set_header(7, get_lang('Sessions'), false, 'align="center"');
-
-		if ($is_western_name_order) {
-			$csv_header[] = array (
-				get_lang('FirstName', ''),
-				get_lang('LastName', ''),
-				get_lang('TimeSpentOnThePlatform', ''),
-				get_lang('LastConnexion', ''),
-				get_lang('NbStudents', ''),
-				get_lang('CountCours', ''),
-				get_lang('NumberOfSessions', '')
-			);
-		} else {
-			$csv_header[] = array (
-				get_lang('LastName', ''),
-				get_lang('FirstName', ''),
-				get_lang('TimeSpentOnThePlatform', ''),
-				get_lang('LastConnexion', ''),
-				get_lang('NbStudents', ''),
-				get_lang('CountCours', ''),
-				get_lang('NumberOfSessions', '')
-			);
-		}
-
-		$tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-
-		$sqlCoachs = "SELECT DISTINCT id_coach, user_id, lastname, firstname, MAX(login_date) as login_date
-			FROM $tbl_user, $tbl_session_course, $tbl_track_login
-			WHERE id_coach=user_id AND login_user_id=user_id
-			GROUP BY user_id ";
-		//	ORDER BY login_date ".$tracking_direction;
-
-		if ($_configuration['multiple_access_urls'] == true) {
-			$tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1) {
-				$sqlCoachs = "SELECT DISTINCT id_coach, user_id, lastname, firstname, MAX(login_date) as login_date
-					FROM $tbl_user, $tbl_session_course, $tbl_track_login , $tbl_session_rel_access_url session_rel_url
-					WHERE id_coach=user_id AND login_user_id=user_id AND access_url_id = $access_url_id AND session_rel_url.session_id=id_session
-					GROUP BY user_id ";
-			}
-		}
-
-		if (!empty($order[$tracking_column])) {
-			$sqlCoachs .= "ORDER BY ".$order[$tracking_column]." ".$tracking_direction;
-		}
-
-		$result_coaches = Database::query($sqlCoachs, __FILE__, __LINE__);
-		$total_no_coaches = Database::num_rows($result_coaches);
-
-		$global_coaches = array();
-		while ($coach = Database::fetch_array($result_coaches)) {
-			$global_coaches[$coach['user_id']] = $coach;
-		}
-
-		$sql_session_coach = 'SELECT session.id_coach, user_id, lastname, firstname, MAX(login_date) as login_date
-			FROM '.$tbl_user.','.$tbl_sessions.' as session,'.$tbl_track_login.'
-			WHERE id_coach=user_id AND login_user_id=user_id
-			GROUP BY user_id
-			ORDER BY login_date '.$tracking_direction;
-
-		if ($_configuration['multiple_access_urls'] == true) {
-			$tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1) {
-				$sql_session_coach = 'SELECT session.id_coach, user_id, lastname, firstname, MAX(login_date) as login_date
-					FROM '.$tbl_user.','.$tbl_sessions.' as session,'.$tbl_track_login.' , '.$tbl_session_rel_access_url.' as session_rel_url
-					WHERE id_coach=user_id AND login_user_id=user_id  AND access_url_id = '.$access_url_id.' AND  session_rel_url.session_id=session.id
-					GROUP BY user_id
-					ORDER BY login_date '.$tracking_direction;
-			}
-		}
-
-		$result_sessions_coach = Database::query($sql_session_coach, __FILE__, __LINE__);
-		$total_no_coaches += Database::num_rows($result_sessions_coach);
-		while ($coach = Database::fetch_array($result_sessions_coach)) {
-			$global_coaches[$coach['user_id']] = $coach;
-		}
-
-		$all_datas = array();
-
-		foreach ($global_coaches as $id_coach => $coaches) {
-
-			$time_on_platform = api_time_to_hms(Tracking :: get_time_spent_on_the_platform($coaches['user_id']));
-			$last_connection = Tracking :: get_last_connection_date($coaches['user_id']);
-			$nb_students = count(Tracking :: get_student_followed_by_coach($coaches['user_id']));
-			$nb_courses = count(Tracking :: get_courses_followed_by_coach($coaches['user_id']));
-			$nb_sessions = count(Tracking :: get_sessions_coached_by_user($coaches['user_id']));
-
-			$table_row = array();
-			if ($is_western_name_order) {
-				$table_row[] = $coaches['firstname'];
-				$table_row[] = $coaches['lastname'];
-			} else {
-				$table_row[] = $coaches['lastname'];
-				$table_row[] = $coaches['firstname'];
-			}
-			$table_row[] = $time_on_platform;
-			$table_row[] = $last_connection;
-			$table_row[] = $nb_students;
-			$table_row[] = $nb_courses;
-			$table_row[] = $nb_sessions;
-			$table_row[] = '<center><a href="session.php?id_coach='.$coaches['user_id'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></center>';
-			$all_datas[] = $table_row;
-
-			if ($is_western_name_order) {
-				$csv_content[] = array(
-					api_html_entity_decode($coaches['firstname'], ENT_QUOTES, $charset),
-					api_html_entity_decode($coaches['lastname'], ENT_QUOTES, $charset),
-					$time_on_platform,
-					$last_connection,
-					$nb_students,
-					$nb_courses,
-					$nb_sessions
-				);
-			} else {
-				$csv_content[] = array(
-					api_html_entity_decode($coaches['lastname'], ENT_QUOTES, $charset),
-					api_html_entity_decode($coaches['firstname'], ENT_QUOTES, $charset),
-					$time_on_platform,
-					$last_connection,
-					$nb_students,
-					$nb_courses,
-					$nb_sessions
-				);
-			}
-		}
-
-		if ($tracking_column != 3) {
-			if ($tracking_direction == 'DESC') {
-				usort($all_datas, 'rsort_users');
-			} else {
-				usort($all_datas, 'sort_users');
-			}
-		}
-
-		if ($export_csv && $tracking_column != 3) {
-			usort($csv_content, 'sort_users');
-		}
-		if ($export_csv) {
-			$csv_content = array_merge($csv_header, $csv_content);
-		}
-
-		foreach ($all_datas as $row) {
-			$table -> addRow($row, 'align="right"');
-		}
-
-		$table -> updateColAttributes(0, array('align' => 'left'));
-		$table -> updateColAttributes(1, array('align' => 'left'));
-		$table -> updateColAttributes(3, array('align' => 'left'));
-		$table -> updateColAttributes(7, array('align' => 'center'));
-		$table -> display();
-	}
-}
-
-// send the csv file if asked
-if ($export_csv) {
-	ob_end_clean();
-	/*echo "<pre>";
-	print_r($csv_content);
-	echo "</pre>";*/
-	Export :: export_table_csv($csv_content, 'reporting_index');
-}
-
-//footer
-if (!$export_csv) {
-	Display::display_footer();
-}
-
-/**
- * This function exports the table that we see in display_tracking_user_overview()
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version Dokeos 1.8.6
- * @since October 2008
- */
-function export_tracking_user_overview() {
-	// database table definitions
-	$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-
-	$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-	$sort_by_first_name = api_sort_by_first_name();
-
-	// the values of the sortable table
-	if ($_GET['tracking_user_overview_page_nr']) {
-		$from = $_GET['tracking_user_overview_page_nr'];
-	} else {
-		$from = 0;
-	}
-	if ($_GET['tracking_user_overview_column']) {
-		$orderby = $_GET['tracking_user_overview_column'];
-	} else {
-		$orderby = 0;
-	}
-	if ($is_western_name_order != api_is_western_name_order() && ($orderby == 1 || $orderby == 2)) {
-		// Swapping the sorting column if name order for export is different than the common name order.
-		$orderby = 3 - $orderby;
-	}
-	if ($_GET['tracking_user_overview_direction']) {
-		$direction = $_GET['tracking_user_overview_direction'];
-	} else {
-		$direction = 'ASC';
-	}
-
-	$user_data = get_user_data_tracking_overview($from, 1000, $orderby, $direction);
-
-	// the first line of the csv file with the column headers
-	$csv_row = array();
-	$csv_row[] = get_lang('OfficialCode');
-	if ($is_western_name_order) {
-		$csv_row[] = get_lang('FirstName', '');
-		$csv_row[] = get_lang('LastName', '');
-	} else {
-		$csv_row[] = get_lang('LastName', '');
-		$csv_row[] = get_lang('FirstName', '');
-	}
-	$csv_row[] = get_lang('LoginName');
-	$csv_row[] = get_lang('CourseCode');
-	// the additional user defined fields (only those that were selected to be exported)
-	require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-	$fields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
-	if (is_array($_SESSION['additional_export_fields'])) {
-		foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
-			$csv_row[] = $fields[$extra_field_export][3];
-			$field_names_to_be_exported[] = 'extra_'.$fields[$extra_field_export][1];
-		}
-	}
-	$csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
-	$csv_row[] = get_lang('AvgStudentsProgress', '');
-	$csv_row[] = get_lang('AvgCourseScore', '');
-	$csv_row[] = get_lang('AvgExercisesScore', '');
-	$csv_row[] = get_lang('AvgMessages', '');
-	$csv_row[] = get_lang('AvgAssignments', '');
-	$csv_row[] = get_lang('TotalExercisesScoreObtained', '');
-	$csv_row[] = get_lang('TotalExercisesScorePossible', '');
-	$csv_row[] = get_lang('TotalExercisesAnswered', '');
-	$csv_row[] = get_lang('TotalExercisesScorePercentage', '');
-	$csv_row[] = get_lang('FirstLogin', '');
-	$csv_row[] = get_lang('LatestLogin', '');
-	$csv_content[] = $csv_row;
-
-	// the other lines (the data)
-	foreach ($user_data as $key => $user) {
-		// getting all the courses of the user
-		$sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".Database::escape_string($user[4])."'";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		while ($row = Database::fetch_row($result)) {
-			$csv_row = array();
-			// user official code
-			$csv_row[] = $user[0];
-			// user first|last name
-			$csv_row[] = $user[1];
-			// user last|first name
-			$csv_row[] = $user[2];
-			// user login name
-			$csv_row[] = $user[3];
-			// course code
-			$csv_row[] = $row[0];
-			// the additional defined user fields
-			$extra_fields = get_user_overview_export_extra_fields($user[4]);
-			if (is_array($field_names_to_be_exported)) {
-				foreach ($field_names_to_be_exported as $key => $extra_field_export) {
-					$csv_row[] = $extra_fields[$extra_field_export];
-				}
-			}
-			// time spent in the course
-			$csv_row[] = api_time_to_hms(Tracking :: get_time_spent_on_the_course ($user[4], $row[0]));
-			// student progress in course
-			$csv_row[] = round(Tracking :: get_avg_student_progress ($user[4], $row[0]), 2);
-			// student score
-			$csv_row[] = round(Tracking :: get_avg_student_score ($user[4], $row[0]), 2);
-			// student tes score
-			$csv_row[] = round(Tracking :: get_avg_student_exercise_score ($user[4], $row[0]), 2);
-			// student messages
-			$csv_row[] = Tracking :: count_student_messages ($user[4], $row[0]);
-			// student assignments
-			$csv_row[] = Tracking :: count_student_assignments ($user[4], $row[0]);
-			// student exercises results
-			$exercises_results = exercises_results($user[4], $row[0]);
-			$csv_row[] = $exercises_results['score_obtained'];
-			$csv_row[] = $exercises_results['score_possible'];
-			$csv_row[] = $exercises_results['questions_answered'];
-			$csv_row[] = $exercises_results['percentage'];
-			// first connection
-			$csv_row[] = Tracking :: get_first_connection_date_on_the_course ($user[4], $row[0]);
-			// last connection
-			$csv_row[] = strip_tags(Tracking :: get_last_connection_date_on_the_course ($user[4], $row[0]));
-
-			$csv_content[] = $csv_row;
-		}
-	}
-	Export :: export_table_csv($csv_content, 'reporting_user_overview');
-}
-
-/**
- * Display a sortable table that contains an overview off all the reporting progress of all users and all courses the user is subscribed to
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version Dokeos 1.8.6
- * @since October 2008
- */
-function display_tracking_user_overview() {
-	display_user_overview_export_options();
-
-	$t_head .= '	<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
-	$t_head .= '	<caption>'.get_lang('CourseInformation').'</caption>';
-	$t_head .=		'<tr>';
-	$t_head .= '		<th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
-	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
-	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
-	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
-	//$t_head .= '		<th><div style="width:40px">'.get_lang('AvgExercisesScore').'</div></th>';
-	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgMessages'), 6, true).'</span></th>';
-	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgAssignments'), 6, true).'</span></th>';
-	$t_head .= '		<th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
-	//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePossible').'</div></th>';
-	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
-	//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePercentage').'</div></th>';
-	//$t_head .= '		<th><div style="width:60px">'.get_lang('FirstLogin').'</div></th>';
-	$t_head .= '		<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
-	$t_head .= '	</tr></table>';
-
-	$addparams = array('view' => 'admin', 'display' => 'useroverview');
-
-	$table = new SortableTable('tracking_user_overview', 'get_number_of_users_tracking_overview', 'get_user_data_tracking_overview', 0);
-	$table->additional_parameters = $addparams;
-
-	$table->set_header(0, get_lang('OfficialCode'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-	if (api_is_western_name_order()) {
-		$table->set_header(1, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-		$table->set_header(2, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-	} else {
-		$table->set_header(1, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-		$table->set_header(2, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-	}
-	$table->set_header(3, get_lang('LoginName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-	$table->set_header(4, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
-	$table->set_column_filter(4, 'course_info_tracking_filter');
-	$table->display();
-}
-
-/**
- * get the numer of users of the platform
- *
- * @return integer
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version Dokeos 1.8.6
- * @since October 2008
- */
-function get_number_of_users_tracking_overview() {
-	// database table definition
-	$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
-
-	// query
-	$sql = 'SELECT user_id FROM '.$main_user_table;
-	$result = Database::query($sql, __FILE__, __LINE__);
-
-	// return the number of results
-	return Database::num_rows($result);
-}
-
-/**
- * get all the data for the sortable table of the reporting progress of all users and all the courses the user is subscribed to.
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version Dokeos 1.8.6
- * @since October 2008
- */
-function get_user_data_tracking_overview($from, $number_of_items, $column, $direction) {
-	// database table definition
-	$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
-	global $export_csv;
-	if ($export_csv) {
-		$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-	} else {
-		$is_western_name_order = api_is_western_name_order();
-	}
-	$sql = "SELECT
-				official_code 	AS col0,
-				".($is_western_name_order ? "
-				firstname 		AS col1,
-				lastname 		AS col2,
-				" : "
-				lastname 		AS col1,
-				firstname 		AS col2,
-				").
-				"username		AS col3,
-				user_id 		AS col4
-			FROM
-				$main_user_table
-			";
-	$sql .= " ORDER BY col$column $direction ";
-	$sql .= " LIMIT $from,$number_of_items";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$return = array ();
-	while ($user = Database::fetch_row($result)) {
-		$return[] = $user;
-	}
-	return $return;
-}
-
-/**
- * Creates a small table in the last column of the table with the user overview
- *
- * @param integer $user_id the id of the user
- * @param array $url_params additonal url parameters
- * @param array $row the row information (the other columns)
- * @return html code
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version Dokeos 1.8.6
- * @since October 2008
- */
-function course_info_tracking_filter($user_id, $url_params, $row) {
-	// the table header
-	$return .= '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
-	/*$return .= '	<tr>';
-	$return .= '		<th>'.get_lang('Course').'</th>';
-	$return .= '		<th>'.get_lang('AvgTimeSpentInTheCourse').'</th>';
-	$return .= '		<th>'.get_lang('AvgStudentsProgress').'</th>';
-	$return .= '		<th>'.get_lang('AvgCourseScore').'</th>';
-	$return .= '		<th>'.get_lang('AvgExercisesScore').'</th>';
-	$return .= '		<th>'.get_lang('AvgMessages').'</th>';
-	$return .= '		<th>'.get_lang('AvgAssignments').'</th>';
-	$return .= '		<th>'.get_lang('TotalExercisesScoreObtained').'</th>';
-	$return .= '		<th>'.get_lang('TotalExercisesScorePossible').'</th>';
-	$return .= '		<th>'.get_lang('TotalExercisesAnswered').'</th>';
-	$return .= '		<th>'.get_lang('TotalExercisesScorePercentage').'</th>';
-	$return .= '		<th>'.get_lang('FirstLogin').'</th>';
-	$return .= '		<th>'.get_lang('LatestLogin').'</th>';
-	$return .= '	</tr>';*/
-
-	// database table definition
-	$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-
-	// getting all the courses of the user
-	$sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".Database::escape_string($user_id)."'";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	while ($row = Database::fetch_row($result)) {
-		$return .= '<tr>';
-		// course code
-		$return .= '	<td width="157px" >'.cut($row[0], 20, true).'</td>';
-		// time spent in the course
-		$return .= '	<td><div>'.api_time_to_hms(Tracking :: get_time_spent_on_the_course($user_id, $row[0])).'</div></td>';
-		// student progress in course
-		$return .= '	<td><div>'.round(Tracking :: get_avg_student_progress($user_id, $row[0]), 2).'</div></td>';
-		// student score
-		$return .= '	<td><div>'.round(Tracking :: get_avg_student_score($user_id, $row[0]), 2).'</div></td>';
-		// student tes score
-		//$return .= '	<td><div style="width:40px">'.round(Tracking :: get_avg_student_exercise_score ($user_id, $row[0]),2).'%</div></td>';
-		// student messages
-		$return .= '	<td><div>'.Tracking :: count_student_messages($user_id, $row[0]).'</div></td>';
-		// student assignments
-		$return .= '	<td><div>'.Tracking :: count_student_assignments($user_id, $row[0]).'</div></td>';
-		// student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
-		$exercises_results = exercises_results($user_id, $row[0]);
-		$return .= '	<td width="105px"><div>'.(is_null($exercises_results['percentage']) ? '' : $exercises_results['score_obtained'].'/'.$exercises_results['score_possible'].' ( '.$exercises_results['percentage'].'% )').'</div></td>';
-		//$return .= '	<td><div>'.$exercises_results['score_possible'].'</div></td>';
-		$return .= '	<td><div>'.$exercises_results['questions_answered'].'</div></td>';
-		//$return .= '	<td><div>'.$exercises_results['percentage'].'% </div></td>';
-		// first connection
-		//$return .= '	<td width="60px">'.Tracking :: get_first_connection_date_on_the_course ($user_id, $row[0]).'</td>';
-		// last connection
-		$return .= '	<td><div>'.Tracking :: get_last_connection_date_on_the_course ($user_id, $row[0]).'</div></td>';
-		$return .= '<tr>';
-	}
-	$return .= '</table>';
-	return $return;
-}
-
-/**
- * Get general information about the exercise performance of the user
- * the total obtained score (all the score on all the questions)
- * the maximum score that could be obtained
- * the number of questions answered
- * the success percentage
- *
- * @param integer $user_id the id of the user
- * @param string $course_code the course code
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version Dokeos 1.8.6
- * @since November 2008
- */
-function exercises_results($user_id, $course_code) {
-	$questions_answered = 0;
-	$sql = 'SELECT exe_result , exe_weighting
-		FROM '.Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES)."
-		WHERE exe_cours_id = '".Database::escape_string($course_code)."'
-		AND exe_user_id = '".Database::escape_string($user_id)."'";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$score_obtained = 0;
-	$score_possible = 0;
-	$questions_answered = 0;
-	while ($row = Database::fetch_array($result)) {
-		$score_obtained += $row['exe_result'];
-		$score_possible += $row['exe_weighting'];
-		$questions_answered ++;
-	}
-
-	if ($score_possible != 0) {
-		$percentage = round(($score_obtained / $score_possible * 100), 2);
-	} else {
-		$percentage = null;
-	}
-
-	return array('score_obtained' => $score_obtained, 'score_possible' => $score_possible, 'questions_answered' => $questions_answered, 'percentage' => $percentage);
-}
-
-/**
- * Displays a form with all the additionally defined user fields of the profile
- * and give you the opportunity to include these in the CSV export
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version Dokeos 1.8.6
- * @since November 2008
- */
-function display_user_overview_export_options() {
-	// include the user manager and formvalidator library
-	require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-	require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-
-	if ($_GET['export'] == 'options') {
-		// get all the defined extra fields
-		$extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC', false);
-
-		// creating the form with all the defined extra fields
-		$form = new FormValidator('exportextrafields', 'post', api_get_self()."?view=".Security::remove_XSS($_GET['view']).'&display='.Security::remove_XSS($_GET['display']).'&export='.Security::remove_XSS($_GET['export']));
-		foreach ($extrafields as $key => $extra) {
-			$form->addElement('checkbox', 'extra_export_field'.$extra[0], '', $extra[3]);
-		}
-		$form->addElement('submit', null, get_lang('Ok'));
-
-		// setting the default values for the form that contains all the extra fields
-		if (is_array($_SESSION['additional_export_fields'])) {
-			foreach ($_SESSION['additional_export_fields'] as $key => $value) {
-				$defaults['extra_export_field'.$value] = 1;
-			}
-		}
-		$form->setDefaults($defaults);
-
-		if ($form->validate()) {
-			// exporting the form values
-			$values = $form->exportValues();
-
-			// re-initialising the session that contains the additional fields that need to be exported
-			$_SESSION['additional_export_fields'] = array();
-
-			// adding the fields that are checked to the session
-			$message = '';
-			foreach ($values as $field_ids => $value) {
-				if ($value == 1 && strstr($field_ids,'extra_export_field')) {
-					$_SESSION['additional_export_fields'][] = str_replace('extra_export_field', '', $field_ids);
-				}
-			}
-
-			// adding the fields that will be also exported to a message string
-			if (is_array($_SESSION['additional_export_fields'])) {
-				foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
-					$message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
-				}
-			}
-
-			// Displaying a feedback message
-			if (!empty($_SESSION['additional_export_fields'])) {
-				Display::display_confirmation_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
-			} else  {
-				Display::display_confirmation_message(get_lang('NoAdditionalFieldsWillBeExported'), false);
-			}
-			$message = '';
-		} else {
-			$form->display();
-		}
-	} else {
-		if (!empty($_SESSION['additional_export_fields'])) {
-			// get all the defined extra fields
-			$extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
-
-			foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
-				$message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
-			}
-
-			Display::display_normal_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
-			$message = '';
-		}
-	}
-}
-
-/**
- * Get all information that the user with user_id = $user_data has
- * entered in the additionally defined profile fields
- *
- * @param integer $user_id the id of the user
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
- * @version Dokeos 1.8.6
- * @since November 2008
- */
-function get_user_overview_export_extra_fields($user_id) {
-	// include the user manager
-	require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-
-	$extra_data = UserManager::get_extra_user_data($user_id, true);
-	return $extra_data;
-}
+<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+ * @todo use constant for $this_section
+ */
+// name of the language file that needs to be included
+$language_file = array ('registration', 'index', 'tracking');
+
+// resetting the course id
+$cidReset = true;
+
+// including the global Dokeos file
+require '../inc/global.inc.php';
+
+// including additional libraries
+require api_get_path(LIBRARY_PATH).'tracking.lib.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
+
+// the section (for the tabs)
+$this_section = "session_my_space";
+
+ob_start();
+
+$export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
+$csv_content = array();
+
+$nameTools = get_lang("MySpace");
+
+// access control
+api_block_anonymous_users();
+if (!$export_csv) {
+	Display :: display_header($nameTools);
+} else {
+	if ($_GET['view'] == 'admin' AND $_GET['display'] == 'useroverview') {
+		export_tracking_user_overview();
+		exit;
+	}
+}
+
+// Database table definitions
+$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_class 					= Database :: get_main_table(TABLE_MAIN_CLASS);
+$tbl_sessions 				= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course 		= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session_user 			= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+$tbl_admin					= Database :: get_main_table(TABLE_MAIN_ADMIN);
+
+
+/********************
+ * FUNCTIONS
+ ********************/
+
+function count_teacher_courses() {
+	global $nb_teacher_courses;
+	return $nb_teacher_courses;
+}
+
+function count_coaches() {
+	global $total_no_coaches;
+	return $total_no_coaches;
+}
+
+function sort_users($a, $b) {
+	return api_strcmp(trim(api_strtolower($a[$_SESSION['tracking_column']])), trim(api_strtolower($b[$_SESSION['tracking_column']])));
+}
+
+function rsort_users($a, $b) {
+	return api_strcmp(trim(api_strtolower($b[$_SESSION['tracking_column']])), trim(api_strtolower($a[$_SESSION['tracking_column']])));
+}
+
+
+/**************************
+ * MAIN CODE
+ ***************************/
+
+$is_coach = api_is_coach();
+$is_platform_admin = api_is_platform_admin();
+
+$view = isset($_GET['view']) ? $_GET['view'] : 'teacher';
+
+$menu_items = array();
+global $_configuration;
+
+if (api_is_allowed_to_create_course()) {
+	$sql_nb_cours = "SELECT course_rel_user.course_code, course.title
+			FROM $tbl_course_user as course_rel_user
+			INNER JOIN $tbl_course as course
+				ON course.code = course_rel_user.course_code
+			WHERE course_rel_user.user_id='".$_user['user_id']."' AND course_rel_user.status='1'
+			ORDER BY course.title";
+
+	if ($_configuration['multiple_access_urls'] == true) {
+		$tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+		$access_url_id = api_get_current_access_url_id();
+		if ($access_url_id != -1) {
+			$sql_nb_cours = "	SELECT course_rel_user.course_code, course.title
+				FROM $tbl_course_user as course_rel_user
+				INNER JOIN $tbl_course as course
+					ON course.code = course_rel_user.course_code
+			  	INNER JOIN $tbl_course_rel_access_url course_rel_url
+					ON (course_rel_url.course_code= course.code)
+			  	WHERE access_url_id =  $access_url_id  AND course_rel_user.user_id='".$_user['user_id']."' AND course_rel_user.status='1'
+			  	ORDER BY course.title";
+		}
+	}
+
+	$result_nb_cours = Database::query($sql_nb_cours, __FILE__, __LINE__);
+	$courses = Database::store_result($result_nb_cours);
+
+	$nb_teacher_courses = count($courses);
+	if ($nb_teacher_courses) {
+		if (!$is_coach && !$is_platform_admin) {
+			$view = 'teacher';
+		}
+		if ($view == 'teacher') {
+			$menu_items[] = get_lang('TeacherInterface');
+			$title = get_lang('YourCourseList');
+		} else {
+			$menu_items[] = '<a href="'.api_get_self().'?view=teacher">'.get_lang('TeacherInterface').'</a>';
+		}
+	}
+}
+if ($is_coach) {
+	if ($nb_teacher_courses == 0 && !$is_platform_admin) {
+		$view = 'coach';
+	}
+	if ($view == 'coach') {
+		$menu_items[] = get_lang('CoachInterface');
+		$title = get_lang('YourStatistics');
+	} else {
+		$menu_items[] = '<a href="'.api_get_self().'?view=coach">'.get_lang('CoachInterface').'</a>';
+	}
+}
+if ($is_platform_admin) {
+	if (!$is_coach && $nb_teacher_courses == 0) {
+		$view = 'admin';
+	}
+	if ($view == 'admin') {
+		$menu_items[] = get_lang('AdminInterface');
+		$title = get_lang('CoachList');
+	} else {
+		$menu_items[] = '<a href="'.api_get_self().'?view=admin">'.get_lang('AdminInterface').'</a>';
+	}
+}
+if ($_user['status'] == DRH) {
+	$view = 'drh';
+	$title = get_lang('DrhInterface');
+	$menu_items[] = '<a href="'.api_get_self().'?view=drh">'.get_lang('DrhInterface').'</a>';
+}
+
+echo '<div class="actions">';
+$nb_menu_items = count($menu_items);
+if ($nb_menu_items > 1) {
+	foreach ($menu_items as $key => $item) {
+		echo $item;
+		if ($key != $nb_menu_items - 1) {
+			echo ' | ';
+		}
+	}
+}
+echo '<a href="javascript: void(0);" onclick="javascript: window.print()"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a> ';
+echo (isset($_GET['display']) &&  $_GET['display'] == 'useroverview')? '' : '<a href="'.api_get_self().'?export=csv&view='.$view.'"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>';
+echo '</div>';
+echo '<h4>'.$title.'</h4>';
+
+if ($_user['status'] == DRH && $view == 'drh') {
+	$students = Tracking :: get_student_followed_by_drh($_user['user_id']);
+	$courses_of_the_platform = CourseManager :: get_real_course_list();
+	foreach ($courses_of_the_platform as $course) {
+		$courses[$course['code']] = $course['code'];
+	}
+}
+
+if ($is_coach && $view == 'coach') {
+	$students = Tracking :: get_student_followed_by_coach($_user['user_id']);
+	$courses = Tracking :: get_courses_followed_by_coach($_user['user_id']);
+}
+
+if ($view == 'coach' || $view == 'drh') {
+	$nb_students = count($students);
+
+	$total_time_spent = 0;
+	$total_courses = 0;
+	$avg_total_progress = 0;
+	$avg_results_to_exercises = 0;
+	$nb_inactive_students = 0;
+	$nb_posts = $nb_assignments = 0;
+	foreach ($students as $student_id) {
+		// inactive students
+		$last_connection_date = Tracking :: get_last_connection_date($student_id, true, true);
+		if ($last_connection_date != false) {
+			/*
+			list($last_connection_date, $last_connection_hour) = explode(' ', $last_connection_date);
+			$last_connection_date = explode('-', $last_connection_date);
+			$last_connection_hour = explode(':', $last_connection_hour);
+			$last_connection_hour[0];
+			$last_connection_time = mktime($last_connection_hour[0], $last_connection_hour[1], $last_connection_hour[2], $last_connection_date[1], $last_connection_date[2], $last_connection_date[0]);
+			*/
+			if (time() - (3600 * 24 * 7) > $last_connection_time) {
+				$nb_inactive_students++;
+			}
+		} else {
+			$nb_inactive_students++;
+		}
+
+		$total_time_spent += Tracking :: get_time_spent_on_the_platform($student_id);
+		$total_courses += Tracking :: count_course_per_student($student_id);
+		$avg_student_progress = $avg_student_score = 0;
+		$nb_courses_student = 0;
+		foreach ($courses as $course_code) {
+			if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
+				$nb_courses_student++;
+				$nb_posts += Tracking :: count_student_messages($student_id, $course_code);
+				$nb_assignments += Tracking :: count_student_assignments($student_id, $course_code);
+				$avg_student_progress += Tracking :: get_avg_student_progress($student_id, $course_code);
+				$avg_student_score += Tracking :: get_avg_student_score($student_id, $course_code);
+				if ($nb_posts !== null && $nb_assignments !== null && $avg_student_progress !== null && $avg_student_score !== null) {
+					//if one of these scores is null, it means that we had a problem connecting to the right database, so don't count it in
+					$nb_courses_student++;
+				}
+			}
+		}
+		// average progress of the student
+		$avg_student_progress = $avg_student_progress / $nb_courses_student;
+		$avg_total_progress += $avg_student_progress;
+
+		// average test results of the student
+		$avg_student_score = $avg_student_score / $nb_courses_student;
+		$avg_results_to_exercises += $avg_student_score;
+	}
+
+	if ($nb_students > 0) {
+		// average progress
+		$avg_total_progress = $avg_total_progress / $nb_students;
+		// average results to the tests
+		$avg_results_to_exercises = $avg_results_to_exercises / $nb_students;
+		// average courses by student
+		$avg_courses_per_student = round($total_courses / $nb_students, 2);
+		// average time spent on the platform
+		$avg_time_spent = $total_time_spent / $nb_students;
+		// average assignments
+		$nb_assignments = $nb_assignments / $nb_students;
+		// average posts
+		$nb_posts = $nb_posts / $nb_students;
+	} else {
+		$avg_total_progress = null;
+		$avg_results_to_exercises = null;
+		$avg_courses_per_student = null;
+		$avg_time_spent = null;
+		$nb_assignments = null;
+		$nb_posts = null;
+	}
+
+	if ($export_csv) {
+		//csv part
+		$csv_content[] = array(get_lang('Probationers', ''));
+		$csv_content[] = array(get_lang('InactivesStudents', ''), $nb_inactive_students );
+		$csv_content[] = array(get_lang('AverageTimeSpentOnThePlatform', ''), $avg_time_spent);
+		$csv_content[] = array(get_lang('AverageCoursePerStudent', ''), $avg_courses_per_student);
+		$csv_content[] = array(get_lang('AverageProgressInLearnpath', ''), is_null($avg_total_progress) ? null : round($avg_total_progress, 2).'%');
+		$csv_content[] = array(get_lang('AverageResultsToTheExercices', ''), is_null($avg_results_to_exercises) ? null : round($avg_results_to_exercises, 2).'%');
+		$csv_content[] = array(get_lang('AveragePostsInForum', ''), $nb_posts);
+		$csv_content[] = array(get_lang('AverageAssignments', ''), $nb_assignments);
+		$csv_content[] = array();
+	} else {
+		// html part
+		echo '
+		 <div class="report_section">
+			<h4>
+				<a href="student.php"><img src="'.api_get_path(WEB_IMG_PATH).'students.gif">&nbsp;'.get_lang('Probationers').' ('.$nb_students.')'.'</a>
+			</h4>
+			<table class="data_table">
+				<tr>
+					<td>
+						'.get_lang('InactivesStudents').'
+					</td>
+					<td align="right">
+						'.$nb_inactive_students.'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('AverageTimeSpentOnThePlatform').'
+					</td>
+					<td align="right">
+						'.(is_null($avg_time_spent) ? '' : api_time_to_hms($avg_time_spent)).'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('AverageCoursePerStudent').'
+					</td>
+					<td align="right">
+						'.(is_null($avg_courses_per_student) ? '' : $avg_courses_per_student).'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('AverageProgressInLearnpath').'
+					</td>
+					<td align="right">
+						'.(is_null($avg_total_progress) ? '' : round($avg_total_progress, 2).'%').'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('AverageResultsToTheExercices').'
+					</td>
+					<td align="right">
+						'.(is_null($avg_results_to_exercises) ? '' : round($avg_results_to_exercises, 2).'%').'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('AveragePostsInForum').'
+					</td>
+					<td align="right">
+						'.(is_null($nb_posts) ? '' : round($nb_posts, 2)).'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('AverageAssignments').'
+					</td>
+					<td align="right">
+						'.(is_null($nb_assignments) ? '' : round($nb_assignments, 2)).'
+					</td>
+				</tr>
+			</table>
+			<a href="student.php">'.get_lang('SeeStudentList').'</a>
+		 </div>';
+	}
+}
+if ($view == 'coach') {
+	/****************************************
+	 * Infos about sessions of the coach
+	 ****************************************/
+	$sessions = Tracking :: get_sessions_coached_by_user($_user['user_id']);
+	$nb_sessions = count($sessions);
+	$nb_sessions_past = $nb_sessions_future = $nb_sessions_current = 0;
+	$courses = array();
+	foreach ($sessions as $session) {
+		if ($session['date_start'] == '0000-00-00') {
+			$nb_sessions_current ++;
+		} else {
+			$date_start = explode('-', $session['date_start']);
+			$time_start = mktime(0, 0, 0, $date_start[1], $date_start[2], $date_start[0]);
+			$date_end = explode('-', $session['date_end']);
+			$time_end = mktime(0, 0, 0, $date_end[1], $date_end[2], $date_end[0]);
+			if ($time_start < time() && time() < $time_end) {
+				$nb_sessions_current++;
+			}
+			elseif (time() < $time_start) {
+				$nb_sessions_future++;
+			}
+			elseif (time() > $time_end) {
+				$nb_sessions_past++;
+			}
+		}
+		$courses = array_merge($courses, Tracking::get_courses_list_from_session($session['id']));
+	}
+
+	if ($nb_sessions > 0) {
+		$nb_courses_per_session = round(count($courses) / $nb_sessions, 2);
+		$nb_students_per_session = round($nb_students / $nb_sessions, 2);
+	} else {
+		$nb_courses_per_session = null;
+		$nb_students_per_session = null;
+	}
+
+
+	if ($export_csv) {
+		//csv part
+		$csv_content[] = array(get_lang('Sessions', ''));
+		$csv_content[] = array(get_lang('NbActiveSessions', '').';'.$nb_sessions_current);
+		$csv_content[] = array(get_lang('NbPastSessions', '').';'.$nb_sessions_past);
+		$csv_content[] = array(get_lang('NbFutureSessions', '').';'.$nb_sessions_future);
+		$csv_content[] = array(get_lang('NbStudentPerSession', '').';'.$nb_students_per_session);
+		$csv_content[] = array(get_lang('NbCoursesPerSession', '').';'.$nb_courses_per_session);
+		$csv_content[] = array();
+	} else {
+		// html part
+		echo '
+		 <div class="report_section">
+			<h4>
+				<a href="session.php"><img src="'.api_get_path(WEB_IMG_PATH).'sessions.gif">&nbsp;'.get_lang('Sessions').' ('.$nb_sessions.')'.'</a>
+			</h4>
+			<table class="data_table">
+				<tr>
+					<td>
+						'.get_lang('NbActiveSessions').'
+					</td>
+					<td align="right">
+						'.$nb_sessions_current.'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('NbPastSessions').'
+					</td>
+					<td align="right">
+						'.$nb_sessions_past.'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('NbFutureSessions').'
+					</td>
+					<td align="right">
+						'.$nb_sessions_future.'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('NbStudentPerSession').'
+					</td>
+					<td align="right">
+						'.(is_null($nb_students_per_session) ? '' : $nb_students_per_session).'
+					</td>
+				</tr>
+				<tr>
+					<td>
+						'.get_lang('NbCoursesPerSession').'
+					</td>
+					<td align="right">
+						'.(is_null($nb_courses_per_session) ? '' : $nb_courses_per_session).'
+					</td>
+				</tr>
+			</table>
+			<a href="session.php">'.get_lang('SeeSessionList').'</a>
+		 </div>';
+	 }
+}
+
+echo '<div class="clear">&nbsp;</div>';
+
+if (api_is_allowed_to_create_course() && $view == 'teacher') {
+	if ($nb_teacher_courses) {
+
+		$table = new SortableTable('tracking_list_course', 'count_teacher_courses');
+		$parameters['view'] = 'teacher';
+		$parameters['class'] = 'data_table';
+
+		$table->set_additional_parameters($parameters);
+		$table -> set_header(0, get_lang('CourseTitle'), false, 'align="center"');
+		$table -> set_header(1, get_lang('NbStudents'), false);
+		$table -> set_header(2, get_lang('AvgTimeSpentInTheCourse').Display :: return_icon('info3.gif', get_lang('TimeOfActiveByTraining'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
+		$table -> set_header(3, get_lang('AvgStudentsProgress').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
+		$table -> set_header(4, get_lang('AvgCourseScore').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
+		$table -> set_header(5, get_lang('AvgExercisesScore').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
+		$table -> set_header(6, get_lang('AvgMessages'), false);
+		$table -> set_header(7, get_lang('AvgAssignments'), false);
+		$table -> set_header(8, get_lang('Details'), false);
+
+		$csv_content[] = array (
+			get_lang('CourseTitle', ''),
+			get_lang('NbStudents', ''),
+			get_lang('AvgTimeSpentInTheCourse', ''),
+			get_lang('AvgStudentsProgress', ''),
+			get_lang('AvgCourseScore', ''),
+			get_lang('AvgExercisesScore', ''),
+			get_lang('AvgMessages', ''),
+			get_lang('AvgAssignments', '')
+		);
+
+		$a_course_students = array();
+
+		foreach ($courses as $course) {
+			$course_code = $course['course_code'];
+			$avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0;
+
+			// students directly subscribed to the course
+			$sql = "SELECT user_id FROM $tbl_course_user as course_rel_user WHERE course_rel_user.status='5' AND course_rel_user.course_code='$course_code'";
+			$rs = Database::query($sql, __FILE__, __LINE__);
+			while ($row = Database::fetch_array($rs)) {
+				$nb_students_in_course++;
+
+				// tracking datas
+				$avg_progress_in_course += Tracking :: get_avg_student_progress ($row['user_id'], $course_code);
+				$avg_score_in_course += Tracking :: get_avg_student_score ($row['user_id'], $course_code);
+				$avg_score_in_exercise += Tracking :: get_avg_student_exercise_score ($row['user_id'], $course_code);
+				$avg_time_spent_in_course += Tracking :: get_time_spent_on_the_course ($row['user_id'], $course_code);
+				$avg_messages_in_course += Tracking :: count_student_messages ($row['user_id'], $course_code);
+				$avg_assignments_in_course += Tracking :: count_student_assignments ($row['user_id'], $course_code);
+				$a_course_students[] = $row['user_id'];
+			}
+
+			// students subscribed to the course through a session
+			if (api_get_setting('use_session_mode') == 'true') {
+				$sql = 'SELECT id_user as user_id
+					FROM '.$tbl_session_course_user.'
+					WHERE course_code="'.addslashes($course_code).'" ORDER BY course_code';
+				$rs = Database::query($sql, __FILE__, __LINE__);
+				while ($row = Database::fetch_array($rs)) {
+					if (!in_array($row['user_id'], $a_course_students)) {
+						$nb_students_in_course++;
+
+						// tracking datas
+						$avg_progress_in_course += Tracking :: get_avg_student_progress ($row['user_id'], $course_code);
+						$avg_score_in_course += Tracking :: get_avg_student_score ($row['user_id'], $course_code);
+						$avg_score_in_exercise += Tracking :: get_avg_student_exercise_score ($row['user_id'], $course_code);
+						$avg_time_spent_in_course += Tracking :: get_time_spent_on_the_course ($row['user_id'], $course_code);
+						$avg_messages_in_course += Tracking :: count_student_messages ($row['user_id'], $course_code);
+						$avg_assignments_in_course += Tracking :: count_student_assignments ($row['user_id'], $course_code);
+						$a_course_students[] = $row['user_id'];
+					}
+				}
+			}
+
+			if ($nb_students_in_course > 0) {
+				$avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
+				$avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
+				$avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2);
+				$avg_score_in_exercise = round($avg_score_in_exercise / $nb_students_in_course, 2);
+				$avg_messages_in_course = round($avg_messages_in_course / $nb_students_in_course, 2);
+				$avg_assignments_in_course = round($avg_assignments_in_course / $nb_students_in_course, 2);
+			} else {
+				$avg_time_spent_in_course = null;
+				$avg_progress_in_course = null;
+				$avg_score_in_course = null;
+				$avg_score_in_exercise = null;
+				$avg_messages_in_course = null;
+				$avg_assignments_in_course = null;
+			}
+
+			$table_row = array();
+			$table_row[] = $course['title'];
+			$table_row[] = $nb_students_in_course;
+			$table_row[] = $avg_time_spent_in_course;
+			$table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course.'%';
+			$table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course.'%';
+			$table_row[] = is_null($avg_score_in_exercise) ? '' : $avg_score_in_exercise.'%';
+			$table_row[] = $avg_messages_in_course;
+			$table_row[] = $avg_assignments_in_course;
+			//set the "from" value to know if I access the Reporting by the Dokeos tab or the course link
+			$table_row[] = '<center><a href="../tracking/courseLog.php?cidReq='.$course_code.'&studentlist=true&from=myspace"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></center>';
+
+			$csv_content[] = array(
+				api_html_entity_decode($course['title'], ENT_QUOTES, $charset),
+				$nb_students_in_course,
+				$avg_time_spent_in_course,
+				is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
+				is_null($avg_score_in_course) ? null : $avg_score_in_course.'%',
+				is_null($avg_score_in_exercise) ? null : $avg_score_in_exercise.'%',
+				$avg_messages_in_course,
+				$avg_assignments_in_course,
+			);
+
+			$table -> addRow($table_row, 'align="right"');
+
+			$a_course_students = array();
+		}
+		$table -> updateColAttributes(0, array('align' => 'left'));
+		$table -> updateColAttributes(7, array('align' => 'center'));
+		$table -> display();
+	}
+}
+
+if ($is_platform_admin && $view == 'admin') {
+	echo '<a href="'.api_get_self().'?view=admin&amp;display=coaches">'.get_lang('DisplayCoaches').'</a> | ';
+	echo '<a href="'.api_get_self().'?view=admin&amp;display=useroverview">'.get_lang('DisplayUserOverview').'</a>';
+	if ($_GET['display'] == 'useroverview') {
+		echo ' | <a href="'.api_get_self().'?view=admin&amp;display=useroverview&amp;export=options">'.get_lang('ExportUserOverviewOptions').'</a>';
+	}
+
+	if ($_GET['display'] === 'useroverview') {
+		display_tracking_user_overview();
+	} else {
+		if ($export_csv) {
+			$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+		} else {
+			$is_western_name_order = api_is_western_name_order();
+		}
+		$sort_by_first_name = api_sort_by_first_name();
+		$tracking_column = isset($_GET['tracking_list_coaches_column']) ? $_GET['tracking_list_coaches_column'] : ($is_western_name_order xor $sort_by_first_name) ? 1 : 0;
+		$tracking_direction = (isset($_GET['tracking_list_coaches_direction']) && in_array(strtoupper($_GET['tracking_list_coaches_direction']), array('ASC', 'DESC', 'ASCENDING', 'DESCENDING', '0', '1'))) ? $_GET['tracking_list_coaches_direction'] : 'DESC';
+		// Prepare array for column order - when impossible, use some of user names.
+		if ($is_western_name_order) {
+			$order = array(0 => 'firstname', 1 => 'lastname', 2 => ($sort_by_first_name ? 'firstname' : 'lastname'), 3 => 'login_date', 4 => ($sort_by_first_name ? 'firstname' : 'lastname'), 5 => ($sort_by_first_name ? 'firstname' : 'lastname'));
+		} else {
+			$order = array(0 => 'lastname', 1 => 'firstname', 2 => ($sort_by_first_name ? 'firstname' : 'lastname'), 3 => 'login_date', 4 => ($sort_by_first_name ? 'firstname' : 'lastname'), 5 => ($sort_by_first_name ? 'firstname' : 'lastname'));
+		}
+
+		$table = new SortableTable('tracking_list_coaches', 'count_coaches', null, ($is_western_name_order xor $sort_by_first_name) ? 1 : 0);
+		$parameters['view'] = 'admin';
+		$table->set_additional_parameters($parameters);
+		if ($is_western_name_order) {
+			$table -> set_header(0, get_lang('FirstName'), true, 'align="center"');
+			$table -> set_header(1, get_lang('LastName'), true, 'align="center"');
+		} else {
+			$table -> set_header(0, get_lang('LastName'), true, 'align="center"');
+			$table -> set_header(1, get_lang('FirstName'), true, 'align="center"');
+		}
+		$table -> set_header(2, get_lang('TimeSpentOnThePlatform'), false);
+		$table -> set_header(3, get_lang('LastConnexion'), true, 'align="center"');
+		$table -> set_header(4, get_lang('NbStudents'), false);
+		$table -> set_header(5, get_lang('CountCours'), false);
+		$table -> set_header(6, get_lang('NumberOfSessions'), false);
+		$table -> set_header(7, get_lang('Sessions'), false, 'align="center"');
+
+		if ($is_western_name_order) {
+			$csv_header[] = array (
+				get_lang('FirstName', ''),
+				get_lang('LastName', ''),
+				get_lang('TimeSpentOnThePlatform', ''),
+				get_lang('LastConnexion', ''),
+				get_lang('NbStudents', ''),
+				get_lang('CountCours', ''),
+				get_lang('NumberOfSessions', '')
+			);
+		} else {
+			$csv_header[] = array (
+				get_lang('LastName', ''),
+				get_lang('FirstName', ''),
+				get_lang('TimeSpentOnThePlatform', ''),
+				get_lang('LastConnexion', ''),
+				get_lang('NbStudents', ''),
+				get_lang('CountCours', ''),
+				get_lang('NumberOfSessions', '')
+			);
+		}
+
+		$tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+
+		$sqlCoachs = "SELECT DISTINCT id_coach, user_id, lastname, firstname, MAX(login_date) as login_date
+			FROM $tbl_user, $tbl_session_course, $tbl_track_login
+			WHERE id_coach=user_id AND login_user_id=user_id
+			GROUP BY user_id ";
+		//	ORDER BY login_date ".$tracking_direction;
+
+		if ($_configuration['multiple_access_urls'] == true) {
+			$tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+			$access_url_id = api_get_current_access_url_id();
+			if ($access_url_id != -1) {
+				$sqlCoachs = "SELECT DISTINCT id_coach, user_id, lastname, firstname, MAX(login_date) as login_date
+					FROM $tbl_user, $tbl_session_course, $tbl_track_login , $tbl_session_rel_access_url session_rel_url
+					WHERE id_coach=user_id AND login_user_id=user_id AND access_url_id = $access_url_id AND session_rel_url.session_id=id_session
+					GROUP BY user_id ";
+			}
+		}
+
+		if (!empty($order[$tracking_column])) {
+			$sqlCoachs .= "ORDER BY ".$order[$tracking_column]." ".$tracking_direction;
+		}
+
+		$result_coaches = Database::query($sqlCoachs, __FILE__, __LINE__);
+		$total_no_coaches = Database::num_rows($result_coaches);
+
+		$global_coaches = array();
+		while ($coach = Database::fetch_array($result_coaches)) {
+			$global_coaches[$coach['user_id']] = $coach;
+		}
+
+		$sql_session_coach = 'SELECT session.id_coach, user_id, lastname, firstname, MAX(login_date) as login_date
+			FROM '.$tbl_user.','.$tbl_sessions.' as session,'.$tbl_track_login.'
+			WHERE id_coach=user_id AND login_user_id=user_id
+			GROUP BY user_id
+			ORDER BY login_date '.$tracking_direction;
+
+		if ($_configuration['multiple_access_urls'] == true) {
+			$tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+			$access_url_id = api_get_current_access_url_id();
+			if ($access_url_id != -1) {
+				$sql_session_coach = 'SELECT session.id_coach, user_id, lastname, firstname, MAX(login_date) as login_date
+					FROM '.$tbl_user.','.$tbl_sessions.' as session,'.$tbl_track_login.' , '.$tbl_session_rel_access_url.' as session_rel_url
+					WHERE id_coach=user_id AND login_user_id=user_id  AND access_url_id = '.$access_url_id.' AND  session_rel_url.session_id=session.id
+					GROUP BY user_id
+					ORDER BY login_date '.$tracking_direction;
+			}
+		}
+
+		$result_sessions_coach = Database::query($sql_session_coach, __FILE__, __LINE__);
+		$total_no_coaches += Database::num_rows($result_sessions_coach);
+		while ($coach = Database::fetch_array($result_sessions_coach)) {
+			$global_coaches[$coach['user_id']] = $coach;
+		}
+
+		$all_datas = array();
+
+		foreach ($global_coaches as $id_coach => $coaches) {
+
+			$time_on_platform = api_time_to_hms(Tracking :: get_time_spent_on_the_platform($coaches['user_id']));
+			$last_connection = Tracking :: get_last_connection_date($coaches['user_id']);
+			$nb_students = count(Tracking :: get_student_followed_by_coach($coaches['user_id']));
+			$nb_courses = count(Tracking :: get_courses_followed_by_coach($coaches['user_id']));
+			$nb_sessions = count(Tracking :: get_sessions_coached_by_user($coaches['user_id']));
+
+			$table_row = array();
+			if ($is_western_name_order) {
+				$table_row[] = $coaches['firstname'];
+				$table_row[] = $coaches['lastname'];
+			} else {
+				$table_row[] = $coaches['lastname'];
+				$table_row[] = $coaches['firstname'];
+			}
+			$table_row[] = $time_on_platform;
+			$table_row[] = $last_connection;
+			$table_row[] = $nb_students;
+			$table_row[] = $nb_courses;
+			$table_row[] = $nb_sessions;
+			$table_row[] = '<center><a href="session.php?id_coach='.$coaches['user_id'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></center>';
+			$all_datas[] = $table_row;
+
+			if ($is_western_name_order) {
+				$csv_content[] = array(
+					api_html_entity_decode($coaches['firstname'], ENT_QUOTES, $charset),
+					api_html_entity_decode($coaches['lastname'], ENT_QUOTES, $charset),
+					$time_on_platform,
+					$last_connection,
+					$nb_students,
+					$nb_courses,
+					$nb_sessions
+				);
+			} else {
+				$csv_content[] = array(
+					api_html_entity_decode($coaches['lastname'], ENT_QUOTES, $charset),
+					api_html_entity_decode($coaches['firstname'], ENT_QUOTES, $charset),
+					$time_on_platform,
+					$last_connection,
+					$nb_students,
+					$nb_courses,
+					$nb_sessions
+				);
+			}
+		}
+
+		if ($tracking_column != 3) {
+			if ($tracking_direction == 'DESC') {
+				usort($all_datas, 'rsort_users');
+			} else {
+				usort($all_datas, 'sort_users');
+			}
+		}
+
+		if ($export_csv && $tracking_column != 3) {
+			usort($csv_content, 'sort_users');
+		}
+		if ($export_csv) {
+			$csv_content = array_merge($csv_header, $csv_content);
+		}
+
+		foreach ($all_datas as $row) {
+			$table -> addRow($row, 'align="right"');
+		}
+
+		$table -> updateColAttributes(0, array('align' => 'left'));
+		$table -> updateColAttributes(1, array('align' => 'left'));
+		$table -> updateColAttributes(3, array('align' => 'left'));
+		$table -> updateColAttributes(7, array('align' => 'center'));
+		$table -> display();
+	}
+}
+
+// send the csv file if asked
+if ($export_csv) {
+	ob_end_clean();
+	/*echo "<pre>";
+	print_r($csv_content);
+	echo "</pre>";*/
+	Export :: export_table_csv($csv_content, 'reporting_index');
+}
+
+//footer
+if (!$export_csv) {
+	Display::display_footer();
+}
+
+/**
+ * This function exports the table that we see in display_tracking_user_overview()
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version Dokeos 1.8.6
+ * @since October 2008
+ */
+function export_tracking_user_overview() {
+	// database table definitions
+	$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+
+	$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+	$sort_by_first_name = api_sort_by_first_name();
+
+	// the values of the sortable table
+	if ($_GET['tracking_user_overview_page_nr']) {
+		$from = $_GET['tracking_user_overview_page_nr'];
+	} else {
+		$from = 0;
+	}
+	if ($_GET['tracking_user_overview_column']) {
+		$orderby = $_GET['tracking_user_overview_column'];
+	} else {
+		$orderby = 0;
+	}
+	if ($is_western_name_order != api_is_western_name_order() && ($orderby == 1 || $orderby == 2)) {
+		// Swapping the sorting column if name order for export is different than the common name order.
+		$orderby = 3 - $orderby;
+	}
+	if ($_GET['tracking_user_overview_direction']) {
+		$direction = $_GET['tracking_user_overview_direction'];
+	} else {
+		$direction = 'ASC';
+	}
+
+	$user_data = get_user_data_tracking_overview($from, 1000, $orderby, $direction);
+
+	// the first line of the csv file with the column headers
+	$csv_row = array();
+	$csv_row[] = get_lang('OfficialCode');
+	if ($is_western_name_order) {
+		$csv_row[] = get_lang('FirstName', '');
+		$csv_row[] = get_lang('LastName', '');
+	} else {
+		$csv_row[] = get_lang('LastName', '');
+		$csv_row[] = get_lang('FirstName', '');
+	}
+	$csv_row[] = get_lang('LoginName');
+	$csv_row[] = get_lang('CourseCode');
+	// the additional user defined fields (only those that were selected to be exported)
+	require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
+	$fields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+	if (is_array($_SESSION['additional_export_fields'])) {
+		foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
+			$csv_row[] = $fields[$extra_field_export][3];
+			$field_names_to_be_exported[] = 'extra_'.$fields[$extra_field_export][1];
+		}
+	}
+	$csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
+	$csv_row[] = get_lang('AvgStudentsProgress', '');
+	$csv_row[] = get_lang('AvgCourseScore', '');
+	$csv_row[] = get_lang('AvgExercisesScore', '');
+	$csv_row[] = get_lang('AvgMessages', '');
+	$csv_row[] = get_lang('AvgAssignments', '');
+	$csv_row[] = get_lang('TotalExercisesScoreObtained', '');
+	$csv_row[] = get_lang('TotalExercisesScorePossible', '');
+	$csv_row[] = get_lang('TotalExercisesAnswered', '');
+	$csv_row[] = get_lang('TotalExercisesScorePercentage', '');
+	$csv_row[] = get_lang('FirstLogin', '');
+	$csv_row[] = get_lang('LatestLogin', '');
+	$csv_content[] = $csv_row;
+
+	// the other lines (the data)
+	foreach ($user_data as $key => $user) {
+		// getting all the courses of the user
+		$sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".Database::escape_string($user[4])."'";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		while ($row = Database::fetch_row($result)) {
+			$csv_row = array();
+			// user official code
+			$csv_row[] = $user[0];
+			// user first|last name
+			$csv_row[] = $user[1];
+			// user last|first name
+			$csv_row[] = $user[2];
+			// user login name
+			$csv_row[] = $user[3];
+			// course code
+			$csv_row[] = $row[0];
+			// the additional defined user fields
+			$extra_fields = get_user_overview_export_extra_fields($user[4]);
+			if (is_array($field_names_to_be_exported)) {
+				foreach ($field_names_to_be_exported as $key => $extra_field_export) {
+					$csv_row[] = $extra_fields[$extra_field_export];
+				}
+			}
+			// time spent in the course
+			$csv_row[] = api_time_to_hms(Tracking :: get_time_spent_on_the_course ($user[4], $row[0]));
+			// student progress in course
+			$csv_row[] = round(Tracking :: get_avg_student_progress ($user[4], $row[0]), 2);
+			// student score
+			$csv_row[] = round(Tracking :: get_avg_student_score ($user[4], $row[0]), 2);
+			// student tes score
+			$csv_row[] = round(Tracking :: get_avg_student_exercise_score ($user[4], $row[0]), 2);
+			// student messages
+			$csv_row[] = Tracking :: count_student_messages ($user[4], $row[0]);
+			// student assignments
+			$csv_row[] = Tracking :: count_student_assignments ($user[4], $row[0]);
+			// student exercises results
+			$exercises_results = exercises_results($user[4], $row[0]);
+			$csv_row[] = $exercises_results['score_obtained'];
+			$csv_row[] = $exercises_results['score_possible'];
+			$csv_row[] = $exercises_results['questions_answered'];
+			$csv_row[] = $exercises_results['percentage'];
+			// first connection
+			$csv_row[] = Tracking :: get_first_connection_date_on_the_course ($user[4], $row[0]);
+			// last connection
+			$csv_row[] = strip_tags(Tracking :: get_last_connection_date_on_the_course ($user[4], $row[0]));
+
+			$csv_content[] = $csv_row;
+		}
+	}
+	Export :: export_table_csv($csv_content, 'reporting_user_overview');
+}
+
+/**
+ * Display a sortable table that contains an overview off all the reporting progress of all users and all courses the user is subscribed to
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version Dokeos 1.8.6
+ * @since October 2008
+ */
+function display_tracking_user_overview() {
+	display_user_overview_export_options();
+
+	$t_head .= '	<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
+	$t_head .= '	<caption>'.get_lang('CourseInformation').'</caption>';
+	$t_head .=		'<tr>';
+	$t_head .= '		<th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
+	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
+	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
+	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
+	//$t_head .= '		<th><div style="width:40px">'.get_lang('AvgExercisesScore').'</div></th>';
+	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgMessages'), 6, true).'</span></th>';
+	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgAssignments'), 6, true).'</span></th>';
+	$t_head .= '		<th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
+	//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePossible').'</div></th>';
+	$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
+	//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePercentage').'</div></th>';
+	//$t_head .= '		<th><div style="width:60px">'.get_lang('FirstLogin').'</div></th>';
+	$t_head .= '		<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
+	$t_head .= '	</tr></table>';
+
+	$addparams = array('view' => 'admin', 'display' => 'useroverview');
+
+	$table = new SortableTable('tracking_user_overview', 'get_number_of_users_tracking_overview', 'get_user_data_tracking_overview', 0);
+	$table->additional_parameters = $addparams;
+
+	$table->set_header(0, get_lang('OfficialCode'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+	if (api_is_western_name_order()) {
+		$table->set_header(1, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+		$table->set_header(2, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+	} else {
+		$table->set_header(1, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+		$table->set_header(2, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+	}
+	$table->set_header(3, get_lang('LoginName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+	$table->set_header(4, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
+	$table->set_column_filter(4, 'course_info_tracking_filter');
+	$table->display();
+}
+
+/**
+ * get the numer of users of the platform
+ *
+ * @return integer
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version Dokeos 1.8.6
+ * @since October 2008
+ */
+function get_number_of_users_tracking_overview() {
+	// database table definition
+	$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
+
+	// query
+	$sql = 'SELECT user_id FROM '.$main_user_table;
+	$result = Database::query($sql, __FILE__, __LINE__);
+
+	// return the number of results
+	return Database::num_rows($result);
+}
+
+/**
+ * get all the data for the sortable table of the reporting progress of all users and all the courses the user is subscribed to.
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version Dokeos 1.8.6
+ * @since October 2008
+ */
+function get_user_data_tracking_overview($from, $number_of_items, $column, $direction) {
+	// database table definition
+	$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
+	global $export_csv;
+	if ($export_csv) {
+		$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+	} else {
+		$is_western_name_order = api_is_western_name_order();
+	}
+	$sql = "SELECT
+				official_code 	AS col0,
+				".($is_western_name_order ? "
+				firstname 		AS col1,
+				lastname 		AS col2,
+				" : "
+				lastname 		AS col1,
+				firstname 		AS col2,
+				").
+				"username		AS col3,
+				user_id 		AS col4
+			FROM
+				$main_user_table
+			";
+	$sql .= " ORDER BY col$column $direction ";
+	$sql .= " LIMIT $from,$number_of_items";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$return = array ();
+	while ($user = Database::fetch_row($result)) {
+		$return[] = $user;
+	}
+	return $return;
+}
+
+/**
+ * Creates a small table in the last column of the table with the user overview
+ *
+ * @param integer $user_id the id of the user
+ * @param array $url_params additonal url parameters
+ * @param array $row the row information (the other columns)
+ * @return html code
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version Dokeos 1.8.6
+ * @since October 2008
+ */
+function course_info_tracking_filter($user_id, $url_params, $row) {
+	// the table header
+	$return .= '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
+	/*$return .= '	<tr>';
+	$return .= '		<th>'.get_lang('Course').'</th>';
+	$return .= '		<th>'.get_lang('AvgTimeSpentInTheCourse').'</th>';
+	$return .= '		<th>'.get_lang('AvgStudentsProgress').'</th>';
+	$return .= '		<th>'.get_lang('AvgCourseScore').'</th>';
+	$return .= '		<th>'.get_lang('AvgExercisesScore').'</th>';
+	$return .= '		<th>'.get_lang('AvgMessages').'</th>';
+	$return .= '		<th>'.get_lang('AvgAssignments').'</th>';
+	$return .= '		<th>'.get_lang('TotalExercisesScoreObtained').'</th>';
+	$return .= '		<th>'.get_lang('TotalExercisesScorePossible').'</th>';
+	$return .= '		<th>'.get_lang('TotalExercisesAnswered').'</th>';
+	$return .= '		<th>'.get_lang('TotalExercisesScorePercentage').'</th>';
+	$return .= '		<th>'.get_lang('FirstLogin').'</th>';
+	$return .= '		<th>'.get_lang('LatestLogin').'</th>';
+	$return .= '	</tr>';*/
+
+	// database table definition
+	$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+
+	// getting all the courses of the user
+	$sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".Database::escape_string($user_id)."'";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	while ($row = Database::fetch_row($result)) {
+		$return .= '<tr>';
+		// course code
+		$return .= '	<td width="157px" >'.cut($row[0], 20, true).'</td>';
+		// time spent in the course
+		$return .= '	<td><div>'.api_time_to_hms(Tracking :: get_time_spent_on_the_course($user_id, $row[0])).'</div></td>';
+		// student progress in course
+		$return .= '	<td><div>'.round(Tracking :: get_avg_student_progress($user_id, $row[0]), 2).'</div></td>';
+		// student score
+		$return .= '	<td><div>'.round(Tracking :: get_avg_student_score($user_id, $row[0]), 2).'</div></td>';
+		// student tes score
+		//$return .= '	<td><div style="width:40px">'.round(Tracking :: get_avg_student_exercise_score ($user_id, $row[0]),2).'%</div></td>';
+		// student messages
+		$return .= '	<td><div>'.Tracking :: count_student_messages($user_id, $row[0]).'</div></td>';
+		// student assignments
+		$return .= '	<td><div>'.Tracking :: count_student_assignments($user_id, $row[0]).'</div></td>';
+		// student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
+		$exercises_results = exercises_results($user_id, $row[0]);
+		$return .= '	<td width="105px"><div>'.(is_null($exercises_results['percentage']) ? '' : $exercises_results['score_obtained'].'/'.$exercises_results['score_possible'].' ( '.$exercises_results['percentage'].'% )').'</div></td>';
+		//$return .= '	<td><div>'.$exercises_results['score_possible'].'</div></td>';
+		$return .= '	<td><div>'.$exercises_results['questions_answered'].'</div></td>';
+		//$return .= '	<td><div>'.$exercises_results['percentage'].'% </div></td>';
+		// first connection
+		//$return .= '	<td width="60px">'.Tracking :: get_first_connection_date_on_the_course ($user_id, $row[0]).'</td>';
+		// last connection
+		$return .= '	<td><div>'.Tracking :: get_last_connection_date_on_the_course ($user_id, $row[0]).'</div></td>';
+		$return .= '<tr>';
+	}
+	$return .= '</table>';
+	return $return;
+}
+
+/**
+ * Get general information about the exercise performance of the user
+ * the total obtained score (all the score on all the questions)
+ * the maximum score that could be obtained
+ * the number of questions answered
+ * the success percentage
+ *
+ * @param integer $user_id the id of the user
+ * @param string $course_code the course code
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version Dokeos 1.8.6
+ * @since November 2008
+ */
+function exercises_results($user_id, $course_code) {
+	$questions_answered = 0;
+	$sql = 'SELECT exe_result , exe_weighting
+		FROM '.Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES)."
+		WHERE exe_cours_id = '".Database::escape_string($course_code)."'
+		AND exe_user_id = '".Database::escape_string($user_id)."'";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$score_obtained = 0;
+	$score_possible = 0;
+	$questions_answered = 0;
+	while ($row = Database::fetch_array($result)) {
+		$score_obtained += $row['exe_result'];
+		$score_possible += $row['exe_weighting'];
+		$questions_answered ++;
+	}
+
+	if ($score_possible != 0) {
+		$percentage = round(($score_obtained / $score_possible * 100), 2);
+	} else {
+		$percentage = null;
+	}
+
+	return array('score_obtained' => $score_obtained, 'score_possible' => $score_possible, 'questions_answered' => $questions_answered, 'percentage' => $percentage);
+}
+
+/**
+ * Displays a form with all the additionally defined user fields of the profile
+ * and give you the opportunity to include these in the CSV export
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version Dokeos 1.8.6
+ * @since November 2008
+ */
+function display_user_overview_export_options() {
+	// include the user manager and formvalidator library
+	require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+	require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
+	if ($_GET['export'] == 'options') {
+		// get all the defined extra fields
+		$extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC', false);
+
+		// creating the form with all the defined extra fields
+		$form = new FormValidator('exportextrafields', 'post', api_get_self()."?view=".Security::remove_XSS($_GET['view']).'&display='.Security::remove_XSS($_GET['display']).'&export='.Security::remove_XSS($_GET['export']));
+		foreach ($extrafields as $key => $extra) {
+			$form->addElement('checkbox', 'extra_export_field'.$extra[0], '', $extra[3]);
+		}
+		$form->addElement('submit', null, get_lang('Ok'));
+
+		// setting the default values for the form that contains all the extra fields
+		if (is_array($_SESSION['additional_export_fields'])) {
+			foreach ($_SESSION['additional_export_fields'] as $key => $value) {
+				$defaults['extra_export_field'.$value] = 1;
+			}
+		}
+		$form->setDefaults($defaults);
+
+		if ($form->validate()) {
+			// exporting the form values
+			$values = $form->exportValues();
+
+			// re-initialising the session that contains the additional fields that need to be exported
+			$_SESSION['additional_export_fields'] = array();
+
+			// adding the fields that are checked to the session
+			$message = '';
+			foreach ($values as $field_ids => $value) {
+				if ($value == 1 && strstr($field_ids,'extra_export_field')) {
+					$_SESSION['additional_export_fields'][] = str_replace('extra_export_field', '', $field_ids);
+				}
+			}
+
+			// adding the fields that will be also exported to a message string
+			if (is_array($_SESSION['additional_export_fields'])) {
+				foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
+					$message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
+				}
+			}
+
+			// Displaying a feedback message
+			if (!empty($_SESSION['additional_export_fields'])) {
+				Display::display_confirmation_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
+			} else  {
+				Display::display_confirmation_message(get_lang('NoAdditionalFieldsWillBeExported'), false);
+			}
+			$message = '';
+		} else {
+			$form->display();
+		}
+	} else {
+		if (!empty($_SESSION['additional_export_fields'])) {
+			// get all the defined extra fields
+			$extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+
+			foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
+				$message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
+			}
+
+			Display::display_normal_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
+			$message = '';
+		}
+	}
+}
+
+/**
+ * Get all information that the user with user_id = $user_data has
+ * entered in the additionally defined profile fields
+ *
+ * @param integer $user_id the id of the user
+ *
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ * @version Dokeos 1.8.6
+ * @since November 2008
+ */
+function get_user_overview_export_extra_fields($user_id) {
+	// include the user manager
+	require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+
+	$extra_data = UserManager::get_extra_user_data($user_id, true);
+	return $extra_data;
+}

+ 1202 - 1202
main/mySpace/myStudents.php

@@ -1,1202 +1,1202 @@
-<?php
-//$Id: myStudents.php 21874 2009-07-08 08:45:18Z herodoto $
-/* For licensing terms, see /dokeos_license.txt */
-/**
- * Implements the tracking of students in the Reporting pages
- * @package dokeos.mySpace
- */
-
-// name of the language file that needs to be included
-$language_file = array('registration', 'index', 'tracking', 'exercice', 'admin');
-//$cidReset = true;
-
-require '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
-require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
-require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
-require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
-require_once api_get_path(SYS_CODE_PATH).'mySpace/myspace.lib.php';
-
-$htmlHeadXtra[] = '<script type="text/javascript">
-
-function show_image(image,width,height) {
-	width = parseInt(width) + 20;
-	height = parseInt(height) + 20;
-	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \'\');
-}
-
-</script>';
-
-$export_csv = isset ($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
-
-if ($export_csv) {
-	ob_start();
-}
-$csv_content = array ();
-
-$from_myspace = false;
-if (isset ($_GET['from']) && $_GET['from'] == 'myspace') {
-	$from_myspace = true;
-	$this_section = "session_my_space";
-} else {
-	$this_section = SECTION_COURSES;
-}
-
-$nameTools = get_lang("StudentDetails");
-//$nameTools = SECTION_PLATFORM_ADMIN;
-
-$get_course_code = Security :: remove_XSS($_GET['course']);
-if (isset ($_GET['details'])) {
-	if (!empty ($_GET['origin']) && $_GET['origin'] == 'user_course') {
-		$course_info = CourseManager :: get_course_information($get_course_code);
-		if (empty ($cidReq)) {
-			$interbreadcrumb[] = array (
-				"url" => api_get_path(WEB_COURSE_PATH) . $course_info['directory'],
-				'name' => $course_info['title']
-			);
-		}
-		$interbreadcrumb[] = array (
-			"url" => "../user/user.php?cidReq=" . $get_course_code,
-			"name" => get_lang("Users")
-		);
-	} else
-		if (!empty ($_GET['origin']) && $_GET['origin'] == 'tracking_course') {
-			$course_info = CourseManager :: get_course_information($get_course_code);
-			if (empty ($cidReq)) {
-				//$interbreadcrumb[] = array ("url" => api_get_path(WEB_COURSE_PATH).$course_info['directory'], 'name' => $course_info['title']);
-			}
-			$interbreadcrumb[] = array (
-				"url" => "../tracking/courseLog.php?cidReq=" . $get_course_code . '&studentlist=true&id_session=' . (empty ($_SESSION['id_session']) ? '' : $_SESSION['id_session']),
-				"name" => get_lang("Tracking")
-			);
-		} else
-			if (!empty ($_GET['origin']) && $_GET['origin'] == 'resume_session') {
-				$interbreadcrumb[] = array (
-					'url' => '../admin/index.php',
-					"name" => get_lang('PlatformAdmin')
-				);
-				$interbreadcrumb[] = array (
-					'url' => "../admin/session_list.php",
-					"name" => get_lang('SessionList')
-				);
-				$interbreadcrumb[] = array (
-					'url' => "../admin/resume_session.php?id_session=" . Security :: remove_XSS($_GET['id_session']),
-					"name" => get_lang('SessionOverview')
-				);
-			} else {
-				$interbreadcrumb[] = array (
-					"url" => "index.php",
-					"name" => get_lang('MySpace')
-				);
-				if (isset ($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
-					$interbreadcrumb[] = array (
-						"url" => "student.php?id_coach=" . Security :: remove_XSS($_GET['id_coach']),
-						"name" => get_lang("CoachStudents")
-					);
-					$interbreadcrumb[] = array (
-						"url" => "myStudents.php?student=" . Security :: remove_XSS($_GET['student']) . '&id_coach=' . Security :: remove_XSS($_GET['id_coach']),
-						"name" => get_lang("StudentDetails")
-					);
-				} else {
-					$interbreadcrumb[] = array (
-						"url" => "student.php",
-						"name" => get_lang("MyStudents")
-					);
-					$interbreadcrumb[] = array (
-						"url" => "myStudents.php?student=" . Security :: remove_XSS($_GET['student']),
-						"name" => get_lang("StudentDetails")
-					);
-				}
-			}
-	$nameTools = get_lang("DetailsStudentInCourse");
-} else {
-	if (!empty ($_GET['origin']) && $_GET['origin'] == 'resume_session') {
-		$interbreadcrumb[] = array (
-			'url' => '../admin/index.php',
-			"name" => get_lang('PlatformAdmin')
-		);
-		$interbreadcrumb[] = array (
-			'url' => "../admin/session_list.php",
-			"name" => get_lang('SessionList')
-		);
-		$interbreadcrumb[] = array (
-			'url' => "../admin/resume_session.php?id_session=" . Security :: remove_XSS($_GET['id_session']),
-			"name" => get_lang('SessionOverview')
-		);
-	} else {
-		$interbreadcrumb[] = array (
-			"url" => "index.php",
-			"name" => get_lang('MySpace')
-		);
-		if (isset ($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
-			if (isset ($_GET['id_session']) && intval($_GET['id_session']) != 0) {
-				$interbreadcrumb[] = array (
-					"url" => "student.php?id_coach=" . Security :: remove_XSS($_GET['id_coach']) . "&id_session=" . $_GET['id_session'],
-					"name" => get_lang("CoachStudents")
-				);
-			} else {
-				$interbreadcrumb[] = array (
-					"url" => "student.php?id_coach=" . Security :: remove_XSS($_GET['id_coach']),
-					"name" => get_lang("CoachStudents")
-				);
-			}
-		} else {
-			$interbreadcrumb[] = array (
-				"url" => "student.php",
-				"name" => get_lang("MyStudents")
-			);
-		}
-	}
-}
-
-api_block_anonymous_users();
-
-if (!api_is_allowed_to_edit() && !api_is_coach() && $_user['status'] != DRH && $_user['status'] != SESSIONADMIN) {
-	api_not_allowed(true);
-}
-
-Display :: display_header($nameTools);
-
-/*
- * ======================================================================================
- * 	FUNCTIONS
- * ======================================================================================
- */
-
-function is_teacher($course_code) {
-	global $_user;
-	$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-	$sql = "SELECT 1 FROM $tbl_course_user WHERE user_id='" . $_user["user_id"] . "' AND course_code='" . Database :: escape_string($course_code) . "' AND status='1'";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	if (Database :: result($result) != 1) {
-		return true;
-	} else {
-		return false;
-	}
-}
-
-/*
- *===============================================================================
- *	MAIN CODE
- *===============================================================================
- */
-// Database Table Definitions
-$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_stats_exercices = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$tbl_stats_exercices_attempts = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-//$tbl_course_lp_view = Database :: get_course_table(TABLE_LP_VIEW);
-//$tbl_course_lp_view_item = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
-//$tbl_course_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
-
-$tbl_course_lp_view = 'lp_view';
-$tbl_course_lp_view_item = 'lp_item_view';
-$tbl_course_lp_item = 'lp_item';
-$tbl_course_lp = 'lp';
-$tbl_course_quiz = 'quiz';
-$course_quiz_question = 'quiz_question';
-$course_quiz_rel_question = 'quiz_rel_question';
-$course_quiz_answer = 'quiz_answer';
-$course_student_publication = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
-
-if (isset ($_GET["user_id"]) && $_GET["user_id"] != "") {
-	$user_id = (int) $_GET["user_id"];
-} else {
-	$user_id = $_user['user_id'];
-}
-
-if (!empty ($_GET['student'])) {
-
-	$student_id = intval($_GET['student']);
-
-	// infos about user
-	$info_user = UserManager :: get_user_info_by_id($student_id);
-	if ($_user['status'] == DRH && $info_user['hr_dept_id'] != $_user['user_id']) {
-		api_not_allowed();
-	}
-
-	$info_user['name'] = api_get_person_name($info_user['firstname'], $info_user['lastname']);
-
-	// Actions bar
-	echo '<div class="actions">';
-	echo '<a href="javascript: void(0);" onclick="javascript: window.print();"><img src="../img/printmgr.gif">&nbsp;' . get_lang('Print') . '</a>';
-	echo '<a href="' . api_get_self() . '?' . Security :: remove_XSS($_SERVER['QUERY_STRING']) . '&export=csv"><img src="../img/excel.gif">&nbsp;' . get_lang('ExportAsCSV') . '</a>';
-	if (!empty ($info_user['email'])) {
-		$send_mail = Display :: return_icon('send_mail.gif', get_lang('SendMail')) . ' ' . Display :: encrypted_mailto_link($info_user['email'], get_lang('SendMail'));
-	} else {
-		$send_mail = Display :: return_icon('send_mail.gif', get_lang('SendMail')) . ' ' . get_lang('SendMail');
-	}
-	echo $send_mail;
-	if (!empty ($_GET['student']) && !empty ($_GET['course'])) { //only show link to connection details if course and student were defined in the URL
-		echo '<a href="access_details.php?student=' . Security :: remove_XSS($_GET['student']) . '&course=' . Security :: remove_XSS($_GET['course']) . '&amp;origin=' . Security :: remove_XSS($_GET['origin']) . '&amp;cidReq=' . Security :: remove_XSS($_GET['course']) . '">' . Display :: return_icon('statistics.gif', get_lang('AccessDetails')) . ' ' . get_lang('AccessDetails') . '</a>';
-	}
-	echo '</div>';
-
-	// is the user online ?
-	$statistics_database = Database :: get_statistic_database();
-	$student_online = Security :: remove_XSS($_GET['student']);
-	$users_online = WhoIsOnline($student_online, $statistics_database, 30);
-	foreach ($users_online as $online) {
-		if (in_array($_GET['student'], $online)) {
-			$online = get_lang('Yes');
-			break;
-		} else {
-			$online = get_lang('No');
-		}
-	}
-
-	$avg_student_progress = $avg_student_score = $nb_courses = 0;
-	$sql = 'SELECT course_code FROM ' . $tbl_course_user . ' WHERE user_id=' . Database :: escape_string($info_user['user_id']);
-	$rs = Database::query($sql, __FILE__, __LINE__);
-	$courses = array ();
-	while ($row = Database :: fetch_array($rs)) {
-		$courses[$row['course_code']] = $row['course_code'];
-	}
-
-	// get the list of sessions where the user is subscribed as student
-	$sql = 'SELECT DISTINCT course_code FROM ' . Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . ' WHERE id_user=' . intval($info_user['user_id']);
-	$rs = Database::query($sql, __FILE__, __LINE__);
-	while ($row = Database :: fetch_array($rs)) {
-		$courses[$row['course_code']] = $row['course_code'];
-	}
-
-	$course_id = Security :: remove_XSS($_GET['course']);
-	if (!CourseManager :: is_user_subscribed_in_course($info_user['user_id'], $course_id, true)) {
-		unset ($courses[$key]);
-	} else {
-		$nb_courses++;
-		$avg_student_progress = Tracking :: get_avg_student_progress($info_user['user_id'], $course_id);
-		//the score inside the Reporting table
-		$avg_student_score = Tracking :: get_average_test_scorm_and_lp($info_user['user_id'], $course_id);
-	}
-
-	$avg_student_progress = round($avg_student_progress, 2);
-	$avg_student_score = round($avg_student_score, 2);
-
-	$first_connection_date = Tracking :: get_first_connection_date($info_user['user_id']);
-	if ($first_connection_date == '') {
-		$first_connection_date = get_lang('NoConnexion');
-	}
-
-	$last_connection_date = Tracking :: get_last_connection_date($info_user['user_id'], true);
-	if ($last_connection_date == '') {
-		$last_connection_date = get_lang('NoConnexion');
-	}
-
-	$time_spent_on_the_course = api_time_to_hms(Tracking :: get_time_spent_on_the_course($info_user['user_id'], $course_id));
-	// cvs informations
-	$csv_content[] = array (
-		get_lang('Informations', '')
-	);
-	$csv_content[] = array (
-		get_lang('Name', ''),
-		get_lang('Email', ''),
-		get_lang('Tel', '')
-	);
-	$csv_content[] = array (
-		$info_user['name'],
-		$info_user['email'],
-		$info_user['phone']
-	);
-
-	$csv_content[] = array ();
-
-	// csv tracking
-	$csv_content[] = array (
-		get_lang('Tracking', '')
-	);
-	$csv_content[] = array (
-		get_lang('FirstLogin', ''),
-		get_lang('LatestLogin', ''),
-		get_lang('TimeSpentInTheCourse', ''),
-		get_lang('Progress', ''),
-		get_lang('Score', '')
-	);
-	$csv_content[] = array (
-		strip_tags($first_connection_date),
-		strip_tags($last_connection_date),
-		$time_spent_on_the_course,
-		$avg_student_progress . '%',
-		$avg_student_score . '%'
-	);
-?>
-	<a name="infosStudent"></a>
-				<table width="100%" border="0" >
-					<tr>
-
-							<?php
-
-	$image_array = UserManager :: get_user_picture_path_by_id($info_user['user_id'], 'web', false, true);
-	echo '<td class="borderRight" width="10%" valign="top">';
-
-	// get the path,width and height from original picture
-	$image_file = $image_array['dir'] . $image_array['file'];
-	$big_image = $image_array['dir'] . 'big_' . $image_array['file'];
-	$big_image_size = api_getimagesize($big_image);
-	$big_image_width = $big_image_size[0];
-	$big_image_height = $big_image_size[1];
-	$url_big_image = $big_image . '?rnd=' . time();
-	$img_attributes = 'src="' . $image_file . '?rand=' . time() . '" ' .
-	'alt="' . api_get_person_name($info_user['lastname'], $info_user['firstname']) . '" ' .
-	'style="float:' . ($text_dir == 'rtl' ? 'left' : 'right') . '; padding:5px;" ';
-
-	if ($image_array['file'] == 'unknown.jpg') {
-		echo '<img ' . $img_attributes . ' />';
-	} else {
-		echo '<input type="image" ' . $img_attributes . ' onclick="javascript: return show_image(\'' . $url_big_image . '\',\'' . $big_image_width . '\',\'' . $big_image_height . '\');"/>';
-	}
-
-	echo '</td>';
-?>
-
-			<td width="40%" valign="top">
-
-				<table width="100%" class="data_table">
-								<tr>
-									<th>
-										<?php echo get_lang('Information'); ?>
-									</th>
-								</tr>
-								<tr>
-						<td>
-										<?php
-
-	echo get_lang('Name') . ' : ';
-	echo $info_user['name'];
-?>
-									</td>
-								</tr>
-								<tr>
-						<td>
-										<?php
-
-	echo get_lang('Email') . ' : ';
-	if (!empty ($info_user['email'])) {
-		echo '<a href="mailto:' . $info_user['email'] . '">' . $info_user['email'] . '</a>';
-	} else {
-		echo get_lang('NoEmail');
-	}
-?>
-									</td>
-								</tr>
-								<tr>
-						<td>
-										<?php
-
-	echo get_lang('Tel') . '. ';
-
-	if (!empty ($info_user['phone'])) {
-		echo $info_user['phone'];
-	} else {
-		echo get_lang('NoTel');
-	}
-?>
-									</td>
-								</tr>
-								<tr>
-						<td>
-										<?php
-
-	echo get_lang('OfficialCode') . ' : ';
-
-	if (!empty ($info_user['official_code'])) {
-		echo $info_user['official_code'];
-	} else {
-		echo get_lang('NoOfficialCode');
-	}
-?>
-									</td>
-								</tr>
-								<tr>
-						<td>
-										<?php
-
-	echo get_lang('OnLine') . ' : ';
-	echo $online;
-?>
-									</td>
-								</tr>
-							</table>
-						</td>
-						<td class="borderLeft" width="35%" valign="top">
-
-				<table width="100%" class="data_table">
-								<tr>
-						<th colspan="2">
-										<?php echo get_lang('Tracking'); ?>
-									</th>
-								</tr>
-								<tr>
-						<td align="right">
-													<?php echo get_lang('FirstLogin') ?>
-												</td>
-						<td align="left">
-													<?php echo $first_connection_date ?>
-												</td>
-											</tr>
-											<tr>
-						<td align="right">
-													<?php echo get_lang('LatestLogin') ?>
-												</td>
-						<td align="left">
-													<?php echo $last_connection_date ?>
-												</td>
-											</tr>
-											<tr>
-						<td align="right">
-													<?php echo get_lang('TimeSpentInTheCourse') ?>
-												</td>
-						<td align="left">
-													<?php echo $time_spent_on_the_course ?>
-												</td>
-											</tr>
-											<tr>
-						<td align="right">
-													<?php
-
-	echo get_lang('Progress');
-	Display :: display_icon('info3.gif', get_lang('ScormAndLPProgressTotalAverage'), array (
-		'align' => 'absmiddle',
-		'hspace' => '3px'
-	));
-?>
-												</td>
-						<td align="left">
-													<?php echo $avg_student_progress.'%' ?>
-												</td>
-											</tr>
-											<tr>
-						<td align="right">
-													<?php
-
-	echo get_lang('Score');
-	Display :: display_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array (
-		'align' => 'absmiddle',
-		'hspace' => '3px'
-	));
-?>
-												</td>
-						<td align="left">
-													<?php  echo $avg_student_score.'%' ?>
-												</td>
-											</tr>
-										</table>
-									</td>
-					</tr>
-				</table>
-
-	<table class="data_table">
-		<tr>
-			<td colspan="5" style="border-width: 0px;">&nbsp;</td>
-		</tr>
-<?php
-
-	if (!empty ($_GET['details'])) {
-		$course_code_info = Security :: remove_XSS($_GET['course']);
-		$info_course = CourseManager :: get_course_information($course_code_info);
-
-		//get coach and session_name if there is one and if session_mode is activated
-		if (api_get_setting('use_session_mode') == 'true') {
-			$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
-			$tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
-			$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-			$tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-			$sql = 'SELECT id_session
-										FROM ' . $tbl_session_course_user . ' session_course_user
-										WHERE session_course_user.id_user = ' . intval($info_user['user_id']) . '
-										AND session_course_user.course_code = "' . Database :: escape_string($course_code_info) . '"
-										ORDER BY id_session DESC';
-			$rs = Database::query($sql, __FILE__, __LINE__);
-			$num_row = Database :: num_rows($rs);
-			if ($num_row > 0) {
-				$le_session_id = intval(Database :: result($rs, 0, 0));
-				if ($le_session_id > 0) {
-					// get session name and coach of the session
-					$sql = 'SELECT name, id_coach FROM ' . $tbl_session . '
-														WHERE id=' . $le_session_id;
-					$rs = Database::query($sql, __FILE__, __LINE__);
-					$session_name = Database :: result($rs, 0, 'name');
-					$session_coach_id = intval(Database :: result($rs, 0, 'id_coach'));
-
-					// get coach of the course in the session
-					$sql = 'SELECT id_coach FROM ' . $tbl_session_course . '
-														WHERE id_session=' . $le_session_id . '
-														AND course_code = "' . Database :: escape_string($_GET['course']) . '"';
-					$rs = Database::query($sql, __FILE__, __LINE__);
-					$session_course_coach_id = intval(Database :: result($rs, 0, 0));
-
-					if ($session_course_coach_id != 0) {
-						$coach_infos = UserManager :: get_user_info_by_id($session_course_coach_id);
-						$info_course['tutor_name'] = api_get_person_name($coach_infos['firstname'], $coach_infos['lastname']);
-					}
-					elseif ($session_coach_id != 0) {
-						$coach_infos = UserManager :: get_user_info_by_id($session_coach_id);
-						$info_course['tutor_name'] = api_get_person_name($coach_infos['firstname'], $coach_infos['lastname']);
-					}
-				}
-			}
-		} // end if(api_get_setting('use_session_mode')=='true')
-
-		$date_start = '';
-		if (!empty ($info_course['date_start'])) {
-			$date_start = explode('-', $info_course['date_start']);
-			$date_start = $date_start[2] . '/' . $date_start[1] . '/' . $date_start[0];
-		}
-		$date_end = '';
-		if (!empty ($info_course['date_end'])) {
-			$date_end = explode('-', $info_course['date_end']);
-			$date_end = $date_end[2] . '/' . $date_end[1] . '/' . $date_end[0];
-		}
-		$dateSession = get_lang('From') . ' ' . $date_start . ' ' . get_lang('To') . ' ' . $date_end;
-		$nb_login = Tracking :: count_login_per_student($info_user['user_id'], $_GET['course']);
-		$table_title = $info_course['title'] . '&nbsp;|&nbsp;' . get_lang('CountToolAccess') . ' : ' . $nb_login . '&nbsp; | &nbsp;' . get_lang('Tutor') . ' : ' . stripslashes($info_course['tutor_name']) . ((!empty ($session_name)) ? ' | ' . get_lang('Session') . ' : ' . $session_name : '');
-
-		$csv_content[] = array ();
-		$csv_content[] = array (str_replace('&nbsp;', '', $table_title));
-?>
-		<tr>
-			<td colspan="6">
-					<strong><?php echo $table_title; ?></strong>
-			</td>
-		</tr>
-	</table>
-
-	<!-- line about learnpaths -->
-				<table class="data_table">
-					<tr>
-						<th>
-							<?php echo get_lang('Learnpaths');?>
-						</th>
-						<th>
-							<?php
-
-		echo get_lang('Time');
-		Display :: display_icon('info3.gif', get_lang('TotalTimeByCourse'), array (
-			'align' => 'absmiddle',
-			'hspace' => '3px'
-		));
-?>
-						</th>
-						<th>
-							<?php
-
-		echo get_lang('Score');
-		Display :: display_icon('info3.gif', get_lang('LPTestScore'), array (
-			'align' => 'absmiddle',
-			'hspace' => '3px'
-		));
-?>
-						</th>
-						<th>
-							<?php
-
-		echo get_lang('Progress');
-		Display :: display_icon('info3.gif', get_lang('LPProgressScore'), array (
-			'align' => 'absmiddle',
-			'hspace' => '3px'
-		));
-?>
-						</th>
-						<th>
-							<?php
-
-		echo get_lang('LastConnexion');
-		Display :: display_icon('info3.gif', get_lang('LastTimeTheCourseWasUsed'), array (
-			'align' => 'absmiddle',
-			'hspace' => '3px'
-		));
-?>
-						</th>
-						<th>
-							<?php echo get_lang('Details');?>
-						</th>
-					</tr>
-<?php
-
-		$headerLearnpath = array (
-			get_lang('Learnpath'),
-			get_lang('Time'),
-			get_lang('Progress'),
-			get_lang('LastConnexion')
-		);
-
-		$t_lp = Database :: get_course_table(TABLE_LP_MAIN, $info_course['db_name']);
-		$t_lpi = Database :: get_course_table(TABLE_LP_ITEM, $info_course['db_name']);
-		$t_lpv = Database :: get_course_table(TABLE_LP_VIEW, $info_course['db_name']);
-		$t_lpiv = Database :: get_course_table(TABLE_LP_ITEM_VIEW, $info_course['db_name']);
-
-		$tbl_stats_exercices = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-		$tbl_stats_attempts = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-		$tbl_quiz_questions = Database :: get_course_table(TABLE_QUIZ_QUESTION, $info_course['db_name']);
-
-		$sql_learnpath = "SELECT lp.name,lp.id
-										FROM $t_lp AS lp ORDER BY lp.name ASC
-									";
-
-		$result_learnpath = Database::query($sql_learnpath, __FILE__, __LINE__);
-
-		$csv_content[] = array ();
-		$csv_content[] = array (
-			get_lang('Learnpath', ''),
-			get_lang('Time', ''),
-			get_lang('Score', ''),
-			get_lang('Progress', ''),
-			get_lang('LastConnexion', '')
-		);
-
-		if (Database :: num_rows($result_learnpath) > 0) {
-			$i = 0;
-			while ($learnpath = Database :: fetch_array($result_learnpath)) {
-				$any_result = false;
-				$progress = learnpath :: get_db_progress($learnpath['id'], $student_id, '%', $info_course['db_name'], true);
-				if ($progress === null) {
-					$progress = '0%';
-				} else {
-					$any_result = true;
-				}
-
-				// calculates time
-				$sql = 'SELECT SUM(total_time)
-												FROM ' . $t_lpiv . ' AS item_view
-												INNER JOIN ' . $t_lpv . ' AS view
-													ON item_view.lp_view_id = view.id
-													AND view.lp_id = ' . $learnpath['id'] . '
-													AND view.user_id = ' . intval($_GET['student']);
-				$rs = Database::query($sql, __FILE__, __LINE__);
-				$total_time = 0;
-				if (Database :: num_rows($rs) > 0) {
-					$total_time = Database :: result($rs, 0, 0);
-					if ($total_time > 0)
-						$any_result = true;
-				}
-
-				// calculates last connection time
-				$sql = 'SELECT MAX(start_time)
-												FROM ' . $t_lpiv . ' AS item_view
-												INNER JOIN ' . $t_lpv . ' AS view
-													ON item_view.lp_view_id = view.id
-													AND view.lp_id = ' . $learnpath['id'] . '
-													AND view.user_id = ' . intval($_GET['student']);
-				$rs = Database::query($sql, __FILE__, __LINE__);
-				$start_time = null;
-				if (Database :: num_rows($rs) > 0) {
-					$start_time = Database :: result($rs, 0, 0);
-					if ($start_time > 0)
-						$any_result = true;
-				}
-
-				//QUIZZ IN LP
-				$score = Tracking :: get_avg_student_score(intval($_GET['student']), Database :: escape_string($_GET['course']), array (
-					$learnpath['id']
-				));
-
-				if (empty ($score)) {
-					//$score = 0;
-				}
-				if ($i % 2 == 0) {
-					$css_class = "row_odd";
-				} else {
-					$css_class = "row_even";
-				}
-
-				$i++;
-
-				$csv_content[] = array (
-					api_html_entity_decode(stripslashes($learnpath['name']), ENT_QUOTES, $charset),
-					api_time_to_hms($total_time),
-					$score . '%',
-					$progress,
-					date('Y-m-d', $start_time)
-				);
-?>
-					<tr class="<?php echo $css_class;?>">
-						<td>
-							<?php echo stripslashes($learnpath['name']); ?>
-						</td>
-						<td align="center">
-						<?php echo api_time_to_hms($total_time) ?>
-						</td>
-						<td align="center">
-							<?php
-
-				if (!is_null($score)) {
-					echo $score . '%';
-				} else {
-					if ('0' == $progress {
-						0 }) {
-						echo '/';
-					} else {
-						echo '0%';
-					}
-					$score = 0;
-				}
-?>
-						</td>
-						<td align="center">
-							<?php echo $progress ?>
-						</td>
-						<td align="center">
-							<?php
-				if ($start_time != '' && $start_time > 0) {
-					echo format_locale_date(get_lang('DateFormatLongWithoutDay'), $start_time);
-				} else {
-					echo '-';
-				}
-?>
-						</td>
-						<td align="center">
-							<?php
-				if ($any_result === true) {
-					$from = '';
-					if ($from_myspace) {
-						$from ='&from=myspace';
-					}
-?>
-					<a href="lp_tracking.php?course=<?php echo Security::remove_XSS($_GET['course']).$from; ?>&origin=<?php echo Security::remove_XSS($_GET['origin']) ?>&lp_id=<?php echo $learnpath['id']?>&student_id=<?php echo $info_user['user_id'] ?>">
-						<img src="../img/2rightarrow.gif" border="0" />
-					</a>
-					<?php
-				}
-?>
-						</td>
-					</tr>
-				<?php
-				$data_learnpath[$i][] = $learnpath['name'];
-				$data_learnpath[$i][] = $progress . '%';
-				$i++;
-			}
-		} else {
-			echo "	<tr>
-										<td colspan='6'>
-											" . get_lang('NoLearnpath') . "
-										</td>
-									</tr>
-								 ";
-		}
-?>
-				</table>
-
-	<!-- line about exercises -->
-			<table class="data_table">
-				<tr>
-					<th>
-						<?php echo get_lang('Exercices'); ?>
-					</th>
-					<th>
-						<?php echo get_lang('Score').Display :: return_icon('info3.gif', get_lang('LastScoreTest'), array('align' => 'absmiddle', 'hspace' => '3px')) ?>
-					</th>
-					<th>
-						<?php echo get_lang('Attempts'); ?>
-					</th>
-					<th>
-						<?php echo get_lang('CorrectTest'); ?>
-					</th>
-				</tr>
-			<?php
-
-		$csv_content[] = array ();
-		$csv_content[] = array (
-			get_lang('Exercices'),
-			get_lang('Score'),
-			get_lang('Attempts')
-		);
-
-		$info_course = CourseManager :: get_course_information(Security :: remove_XSS($_GET['course']));
-		$t_tool = Database :: get_course_table(TABLE_TOOL_LIST, $info_course['db_name']);
-		$sql = 'SELECT visibility FROM ' . $t_tool . ' WHERE name="quiz"';
-
-		$result_visibility_quizz = Database::query($sql, __FILE__, __LINE__);
-		$t_quiz = Database :: get_course_table(TABLE_QUIZ_TEST, $info_course['db_name']);
-
-		if (Database :: result($result_visibility_quizz, 0, 'visibility') == 1) {
-
-			$sql_exercices = "SELECT quiz.title,id
-												FROM " . $t_quiz . " AS quiz
-												WHERE active='1' ORDER BY quiz.title ASC
-												";
-
-			$result_exercices = Database::query($sql_exercices, __FILE__, __LINE__);
-			$i = 0;
-			$is_student = Security :: remove_XSS($_GET['student']);
-			if (Database :: num_rows($result_exercices) > 0) {
-				while ($exercices = Database :: fetch_array($result_exercices)) {
-					$sql_essais = "SELECT COUNT(ex.exe_id) as essais
-															FROM $tbl_stats_exercices AS ex
-															WHERE  ex.exe_cours_id = '" . $info_course['code'] . "'
-															AND ex.exe_exo_id = " . $exercices['id'] . "
-															AND orig_lp_id = 0
-															AND orig_lp_item_id = 0
-															AND exe_user_id='" . Database :: escape_string($is_student) . "'";
-					$result_essais = Database::query($sql_essais, __FILE__, __LINE__);
-					$essais = Database :: fetch_array($result_essais);
-
-					$sql_score = "SELECT exe_id, exe_result,exe_weighting
-														 FROM $tbl_stats_exercices
-														 WHERE exe_user_id = " . Database :: escape_string($is_student) . "
-														 AND exe_cours_id = '" . $info_course['code'] . "'
-														 AND exe_exo_id = " . $exercices['id'] . "
-														 AND orig_lp_id = 0
-														 AND orig_lp_item_id = 0
-														 ORDER BY exe_date DESC LIMIT 1";
-
-					$result_score = Database::query($sql_score, __FILE__, __LINE__);
-					$score = 0;
-					while ($scores = Database :: fetch_array($result_score)) {
-						$score = $score + $scores['exe_result'];
-						$weighting = $weighting + $scores['exe_weighting'];
-						$exe_id = $scores['exe_id'];
-					}
-					$score_percentage = 0;
-					if ($weighting != 0) {
-						//i.e 10.50
-						$score_percentage = round(($score * 100) / $weighting, 2);
-					} else {
-						$score_percentage = null;
-					}
-
-					$weighting = 0;
-
-					$csv_content[] = array (
-						$exercices['title'],
-						$score_percentage . '%',
-						$essais['essais']
-					);
-
-					if ($i % 2 == 0) {
-						$css_class = "row_odd";
-					} else {
-						$css_class = "row_even";
-					}
-
-					$i++;
-
-					echo '<tr class="' . $css_class . '">
-													<td>
-										 ';
-					echo $exercices['title'];
-					echo "	</td>
-												 ";
-					echo "	<td align='center'>
-												  ";
-					if ($essais['essais'] > 0) {
-						echo $score_percentage . '%';
-					} else {
-						echo '/';
-						$score_percentage = 0;
-					}
-
-					echo "	</td>
-													<td align='center'>
-												 ";
-					echo $essais['essais'];
-					echo "	</td>
-													<td align='center'>
-												 ";
-
-					$sql_last_attempt = 'SELECT exe_id FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $exercices['id'] . '" AND exe_user_id="' . Security :: remove_XSS($_GET['student']) . '" AND exe_cours_id="' . $info_course['code'] . '" AND orig_lp_id = 0 AND orig_lp_item_id = 0 ORDER BY exe_date DESC LIMIT 1';
-					$result_last_attempt = Database::query($sql_last_attempt, __FILE__, __LINE__);
-					if (Database :: num_rows($result_last_attempt) > 0) {
-						$id_last_attempt = Database :: result($result_last_attempt, 0, 0);
-
-						if ($essais['essais'] > 0)
-							echo '<a href="../exercice/exercise_show.php?id=' . $id_last_attempt . '&cidReq=' . $info_course['code'] . '&student=' . Security :: remove_XSS($_GET['student']) . '&origin=' . (empty ($_GET['origin']) ? 'tracking' : Security :: remove_XSS($_GET['origin'])) . '"> <img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" border="0" /> </a>';
-					}
-					echo "	</td>
-												  </tr>
-												 ";
-					$data_exercices[$i][] = $exercices['title'];
-					$data_exercices[$i][] = $score_percentage . '%';
-					$data_exercices[$i][] = $essais['essais'];
-					//$data_exercices[$i][] =  corrections;
-					$i++;
-
-				}
-			} else {
-				echo "	<tr>
-												<td colspan='6'>
-													" . get_lang('NoExercise') . "
-												</td>
-											</tr>
-										 ";
-			}
-		} else {
-			echo "	<tr>
-										<td colspan='6'>
-											" . get_lang('NoExercise') . "
-										</td>
-									</tr>
-								 ";
-		}
-?>
-					</table>
-
-	<!-- line about other tools -->
-			<table class="data_table">
-	<tr>
-		<td>
-			<?php
-
-		$csv_content[] = array ();
-
-		$nb_assignments = Tracking :: count_student_assignments($info_user['user_id'], $info_course['code']);
-		$messages = Tracking :: count_student_messages($info_user['user_id'], $info_course['code']);
-		$links = Tracking :: count_student_visited_links($info_user['user_id'], $info_course['code']);
-		$documents = Tracking :: count_student_downloaded_documents($info_user['user_id'], $info_course['code']);
-		$chat_last_connection = Tracking :: chat_last_connection($info_user['user_id'], $info_course['code']);
-
-		$csv_content[] = array (
-			get_lang('Student_publication'),
-			$nb_assignments
-		);
-		$csv_content[] = array (
-			get_lang('Messages'),
-			$messages
-		);
-		$csv_content[] = array (
-			get_lang('LinksDetails'),
-			$links
-		);
-		$csv_content[] = array (
-			get_lang('DocumentsDetails'),
-			$documents
-		);
-		$csv_content[] = array (
-			get_lang('ChatLastConnection'),
-			$chat_last_connection
-		);
-?>
-				<tr>
-					<th colspan="2">
-						<?php echo get_lang('OtherTools'); ?>
-					</th>
-				</tr>
-				<tr><!-- assignments -->
-					<td width="40%">
-						<?php echo get_lang('Student_publication') ?>
-					</td>
-					<td>
-						<?php echo $nb_assignments ?>
-					</td>
-				</tr>
-				<tr><!-- messages -->
-					<td>
-						<?php echo get_lang('Messages') ?>
-					</td>
-					<td>
-						<?php echo $messages ?>
-					</td>
-				</tr>
-				<tr><!-- links -->
-					<td>
-						<?php echo get_lang('LinksDetails') ?>
-					</td>
-					<td>
-						<?php echo $links ?>
-					</td>
-				</tr>
-				<tr><!-- documents -->
-					<td>
-						<?php echo get_lang('DocumentsDetails') ?>
-					</td>
-					<td>
-						<?php echo $documents ?>
-					</td>
-				</tr>
-				<tr><!-- Chats -->
-					<td>
-						<?php echo get_lang('ChatLastConnection') ?>
-					</td>
-					<td>
-						<?php echo $chat_last_connection; ?>
-					</td>
-				</tr>
-			</table>
-			</td>
-		</tr>
-		</table>
-<?php
-
-	} else {
-?>
-		<tr>
-			<th>
-				<?php echo get_lang('Course'); ?>
-			</th>
-			<th>
-				<?php echo get_lang('Time'); ?>
-			</th>
-			<th>
-				<?php echo get_lang('Progress'); ?>
-			</th>
-			<th>
-				<?php echo get_lang('Score'); ?>
-			</th>
-			<th>
-				<?php echo get_lang('Details'); ?>
-			</th>
-		</tr>
-<?php
-
-		if (!api_is_platform_admin(true) && $_user['status'] != DRH) {
-			// courses followed by user where we are coach
-			if (!isset ($_GET['id_coach'])) {
-				$courses = Tracking :: get_courses_followed_by_coach($_user['user_id']);
-			} else {
-				$courses = Tracking :: get_courses_followed_by_coach(Security :: remove_XSS($_GET['id_coach']));
-			}
-		}
-		if (count($courses) > 0) {
-			$csv_content[] = array ();
-			$csv_content[] = array (
-				get_lang('Course', ''),
-				get_lang('Time', ''),
-				get_lang('Progress', ''),
-				get_lang('Score', '')
-			);
-			foreach ($courses as $course_code) {
-				if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
-					$course_info = CourseManager :: get_course_information($course_code);
-					$time_spent_on_course = api_time_to_hms(Tracking :: get_time_spent_on_the_course($info_user['user_id'], $course_code));
-					$progress = Tracking :: get_avg_student_progress($info_user['user_id'], $course_code);
-					$score = Tracking :: get_avg_student_score($info_user['user_id'], $course_code);
-					$progress = empty($progress) ? '0%' : $progress.'%';
-					$score = empty($score) ? '0%' : $score.'%';
-					$csv_content[] = array (
-						$course_info['title'],
-						$time_spent_on_course,
-						$progress,
-						$score
-					);
-					echo '
-										<tr>
-											<td align="right">
-												' . $course_info['title'] . '
-											</td>
-											<td align="right">
-												' . $time_spent_on_course . '
-											</td>
-											<td align="right">
-												' . $progress . '
-											</td>
-											<td align="right">
-												' . $score . '
-											</td>';
-					if (isset ($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
-						echo '<td align="center" width="10">
-														<a href="' . api_get_self() . '?student=' . $info_user['user_id'] . '&details=true&course=' . $course_info['code'] . '&id_coach=' . Security :: remove_XSS($_GET['id_coach']) . '&origin=' . Security :: remove_XSS($_GET['origin']) . '&id_session=' . Security :: remove_XSS($_GET['id_session']) . '#infosStudent"><img src="' . api_get_path(WEB_IMG_PATH) . '2rightarrow.gif" border="0" /></a>
-													</td>';
-					} else {
-						echo '<td align="center" width="10">
-														<a href="' . api_get_self() . '?student=' . $info_user['user_id'] . '&details=true&course=' . $course_info['code'] . '&origin=' . Security :: remove_XSS($_GET['origin']) . '&id_session=' . Security :: remove_XSS($_GET['id_session']) . '#infosStudent"><img src="' . api_get_path(WEB_IMG_PATH) . '2rightarrow.gif" border="0" /></a>
-													</td>';
-					}
-					echo '</tr>';
-				}
-
-			}
-		} else {
-			echo "<tr>
-								<td colspan='5'>
-									" . get_lang('NoCourse') . "
-								</td>
-							  </tr>
-							 ";
-		}
-	} //end of else !empty($details)
-?>
-	</table>
-	<br />
-<?php
-
-	if (!empty ($_GET['details']) && $_GET['origin'] != 'tracking_course' && $_GET['origin'] != 'user_course') {
-?>
-
-		<br /><br />
-<?php
-
-	}
-	if (!empty ($_GET['exe_id'])) {
-		$t_q = Database :: get_course_table(TABLE_QUIZ_TEST, $info_course['db_name']);
-		$t_qq = Database :: get_course_table(TABLE_QUIZ_QUESTION, $info_course['db_name']);
-		$t_qa = Database :: get_course_table(TABLE_QUIZ_ANSWER, $info_course['db_name']);
-		$t_qtq = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION, $info_course['db_name']);
-		$sql_exercice_details = "SELECT qq.question, qq.ponderation, qq.id
-						 				FROM " . $t_qq . " as qq
-										INNER JOIN " . $t_qtq . " as qrq
-											ON qrq.question_id = qq.id
-											AND qrq.exercice_id = " . intval($_GET['exe_id']);
-
-		$result_exercice_details = Database::query($sql_exercice_details, __FILE__, __LINE__);
-
-		$sql_ex_name = "SELECT quiz.title
-								FROM " . $t_q . " AS quiz
-							 	WHERE quiz.id = " . intval($_GET['exe_id']);
-		;
-
-		$resultExName = Database::query($sql_ex_name, __FILE__, __LINE__);
-		$exName = Database :: fetch_array($resultExName);
-
-		echo "<table class='data_table'>
-					 	<tr>
-							<th colspan='2'>
-								" . $exName['title'] . "
-							</th>
-						</tr>
-		             ";
-
-		while ($exerciceDetails = Database :: fetch_array($result_exercice_details)) {
-			$sqlAnswer = "	SELECT qa.comment, qa.answer
-										FROM  " . $t_qa . " as qa
-										WHERE qa.question_id = " . $exerciceDetails['id'];
-
-			$resultAnswer = Database::query($sqlAnswer, __FILE__, __LINE__);
-
-			echo "<a name='infosExe'></a>";
-
-			echo "
-						<tr>
-							<td colspan='2'>
-								<strong>" . $exerciceDetails['question'] . ' /' . $exerciceDetails['ponderation'] . "</strong>
-							</td>
-						</tr>
-						";
-			while ($answer = Database :: fetch_array($resultAnswer)) {
-				echo "
-								<tr>
-									<td>
-										" . $answer['answer'] . "
-									</td>
-									<td>
-								";
-				if (!empty ($answer['comment']))
-					echo $answer['comment'];
-				else
-					echo get_lang('NoComment');
-				echo "
-									</td>
-								</tr>
-								";
-			}
-		}
-		echo "</table>";
-	}
-	//YW - commented out because it doesn't seem to be used
-	//$header = array_merge($headerLearnpath,$headerExercices,$headerProductions);
-}
-if ($export_csv) {
-	ob_end_clean();
-	Export :: export_table_csv($csv_content, 'reporting_student');
-}
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display :: display_footer();
+<?php
+//$Id: myStudents.php 21874 2009-07-08 08:45:18Z herodoto $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+ * Implements the tracking of students in the Reporting pages
+ * @package dokeos.mySpace
+ */
+
+// name of the language file that needs to be included
+$language_file = array('registration', 'index', 'tracking', 'exercice', 'admin');
+//$cidReset = true;
+
+require '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
+require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
+require_once api_get_path(SYS_CODE_PATH).'mySpace/myspace.lib.php';
+
+$htmlHeadXtra[] = '<script type="text/javascript">
+
+function show_image(image,width,height) {
+	width = parseInt(width) + 20;
+	height = parseInt(height) + 20;
+	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \'\');
+}
+
+</script>';
+
+$export_csv = isset ($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
+
+if ($export_csv) {
+	ob_start();
+}
+$csv_content = array ();
+
+$from_myspace = false;
+if (isset ($_GET['from']) && $_GET['from'] == 'myspace') {
+	$from_myspace = true;
+	$this_section = "session_my_space";
+} else {
+	$this_section = SECTION_COURSES;
+}
+
+$nameTools = get_lang("StudentDetails");
+//$nameTools = SECTION_PLATFORM_ADMIN;
+
+$get_course_code = Security :: remove_XSS($_GET['course']);
+if (isset ($_GET['details'])) {
+	if (!empty ($_GET['origin']) && $_GET['origin'] == 'user_course') {
+		$course_info = CourseManager :: get_course_information($get_course_code);
+		if (empty ($cidReq)) {
+			$interbreadcrumb[] = array (
+				"url" => api_get_path(WEB_COURSE_PATH) . $course_info['directory'],
+				'name' => $course_info['title']
+			);
+		}
+		$interbreadcrumb[] = array (
+			"url" => "../user/user.php?cidReq=" . $get_course_code,
+			"name" => get_lang("Users")
+		);
+	} else
+		if (!empty ($_GET['origin']) && $_GET['origin'] == 'tracking_course') {
+			$course_info = CourseManager :: get_course_information($get_course_code);
+			if (empty ($cidReq)) {
+				//$interbreadcrumb[] = array ("url" => api_get_path(WEB_COURSE_PATH).$course_info['directory'], 'name' => $course_info['title']);
+			}
+			$interbreadcrumb[] = array (
+				"url" => "../tracking/courseLog.php?cidReq=" . $get_course_code . '&studentlist=true&id_session=' . (empty ($_SESSION['id_session']) ? '' : $_SESSION['id_session']),
+				"name" => get_lang("Tracking")
+			);
+		} else
+			if (!empty ($_GET['origin']) && $_GET['origin'] == 'resume_session') {
+				$interbreadcrumb[] = array (
+					'url' => '../admin/index.php',
+					"name" => get_lang('PlatformAdmin')
+				);
+				$interbreadcrumb[] = array (
+					'url' => "../admin/session_list.php",
+					"name" => get_lang('SessionList')
+				);
+				$interbreadcrumb[] = array (
+					'url' => "../admin/resume_session.php?id_session=" . Security :: remove_XSS($_GET['id_session']),
+					"name" => get_lang('SessionOverview')
+				);
+			} else {
+				$interbreadcrumb[] = array (
+					"url" => "index.php",
+					"name" => get_lang('MySpace')
+				);
+				if (isset ($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
+					$interbreadcrumb[] = array (
+						"url" => "student.php?id_coach=" . Security :: remove_XSS($_GET['id_coach']),
+						"name" => get_lang("CoachStudents")
+					);
+					$interbreadcrumb[] = array (
+						"url" => "myStudents.php?student=" . Security :: remove_XSS($_GET['student']) . '&id_coach=' . Security :: remove_XSS($_GET['id_coach']),
+						"name" => get_lang("StudentDetails")
+					);
+				} else {
+					$interbreadcrumb[] = array (
+						"url" => "student.php",
+						"name" => get_lang("MyStudents")
+					);
+					$interbreadcrumb[] = array (
+						"url" => "myStudents.php?student=" . Security :: remove_XSS($_GET['student']),
+						"name" => get_lang("StudentDetails")
+					);
+				}
+			}
+	$nameTools = get_lang("DetailsStudentInCourse");
+} else {
+	if (!empty ($_GET['origin']) && $_GET['origin'] == 'resume_session') {
+		$interbreadcrumb[] = array (
+			'url' => '../admin/index.php',
+			"name" => get_lang('PlatformAdmin')
+		);
+		$interbreadcrumb[] = array (
+			'url' => "../admin/session_list.php",
+			"name" => get_lang('SessionList')
+		);
+		$interbreadcrumb[] = array (
+			'url' => "../admin/resume_session.php?id_session=" . Security :: remove_XSS($_GET['id_session']),
+			"name" => get_lang('SessionOverview')
+		);
+	} else {
+		$interbreadcrumb[] = array (
+			"url" => "index.php",
+			"name" => get_lang('MySpace')
+		);
+		if (isset ($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
+			if (isset ($_GET['id_session']) && intval($_GET['id_session']) != 0) {
+				$interbreadcrumb[] = array (
+					"url" => "student.php?id_coach=" . Security :: remove_XSS($_GET['id_coach']) . "&id_session=" . $_GET['id_session'],
+					"name" => get_lang("CoachStudents")
+				);
+			} else {
+				$interbreadcrumb[] = array (
+					"url" => "student.php?id_coach=" . Security :: remove_XSS($_GET['id_coach']),
+					"name" => get_lang("CoachStudents")
+				);
+			}
+		} else {
+			$interbreadcrumb[] = array (
+				"url" => "student.php",
+				"name" => get_lang("MyStudents")
+			);
+		}
+	}
+}
+
+api_block_anonymous_users();
+
+if (!api_is_allowed_to_edit() && !api_is_coach() && $_user['status'] != DRH && $_user['status'] != SESSIONADMIN) {
+	api_not_allowed(true);
+}
+
+Display :: display_header($nameTools);
+
+/*
+ * ======================================================================================
+ * 	FUNCTIONS
+ * ======================================================================================
+ */
+
+function is_teacher($course_code) {
+	global $_user;
+	$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+	$sql = "SELECT 1 FROM $tbl_course_user WHERE user_id='" . $_user["user_id"] . "' AND course_code='" . Database :: escape_string($course_code) . "' AND status='1'";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	if (Database :: result($result) != 1) {
+		return true;
+	} else {
+		return false;
+	}
+}
+
+/*
+ *===============================================================================
+ *	MAIN CODE
+ *===============================================================================
+ */
+// Database Table Definitions
+$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_stats_exercices = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$tbl_stats_exercices_attempts = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+//$tbl_course_lp_view = Database :: get_course_table(TABLE_LP_VIEW);
+//$tbl_course_lp_view_item = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+//$tbl_course_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
+
+$tbl_course_lp_view = 'lp_view';
+$tbl_course_lp_view_item = 'lp_item_view';
+$tbl_course_lp_item = 'lp_item';
+$tbl_course_lp = 'lp';
+$tbl_course_quiz = 'quiz';
+$course_quiz_question = 'quiz_question';
+$course_quiz_rel_question = 'quiz_rel_question';
+$course_quiz_answer = 'quiz_answer';
+$course_student_publication = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+
+if (isset ($_GET["user_id"]) && $_GET["user_id"] != "") {
+	$user_id = (int) $_GET["user_id"];
+} else {
+	$user_id = $_user['user_id'];
+}
+
+if (!empty ($_GET['student'])) {
+
+	$student_id = intval($_GET['student']);
+
+	// infos about user
+	$info_user = UserManager :: get_user_info_by_id($student_id);
+	if ($_user['status'] == DRH && $info_user['hr_dept_id'] != $_user['user_id']) {
+		api_not_allowed();
+	}
+
+	$info_user['name'] = api_get_person_name($info_user['firstname'], $info_user['lastname']);
+
+	// Actions bar
+	echo '<div class="actions">';
+	echo '<a href="javascript: void(0);" onclick="javascript: window.print();"><img src="../img/printmgr.gif">&nbsp;' . get_lang('Print') . '</a>';
+	echo '<a href="' . api_get_self() . '?' . Security :: remove_XSS($_SERVER['QUERY_STRING']) . '&export=csv"><img src="../img/excel.gif">&nbsp;' . get_lang('ExportAsCSV') . '</a>';
+	if (!empty ($info_user['email'])) {
+		$send_mail = Display :: return_icon('send_mail.gif', get_lang('SendMail')) . ' ' . Display :: encrypted_mailto_link($info_user['email'], get_lang('SendMail'));
+	} else {
+		$send_mail = Display :: return_icon('send_mail.gif', get_lang('SendMail')) . ' ' . get_lang('SendMail');
+	}
+	echo $send_mail;
+	if (!empty ($_GET['student']) && !empty ($_GET['course'])) { //only show link to connection details if course and student were defined in the URL
+		echo '<a href="access_details.php?student=' . Security :: remove_XSS($_GET['student']) . '&course=' . Security :: remove_XSS($_GET['course']) . '&amp;origin=' . Security :: remove_XSS($_GET['origin']) . '&amp;cidReq=' . Security :: remove_XSS($_GET['course']) . '">' . Display :: return_icon('statistics.gif', get_lang('AccessDetails')) . ' ' . get_lang('AccessDetails') . '</a>';
+	}
+	echo '</div>';
+
+	// is the user online ?
+	$statistics_database = Database :: get_statistic_database();
+	$student_online = Security :: remove_XSS($_GET['student']);
+	$users_online = WhoIsOnline($student_online, $statistics_database, 30);
+	foreach ($users_online as $online) {
+		if (in_array($_GET['student'], $online)) {
+			$online = get_lang('Yes');
+			break;
+		} else {
+			$online = get_lang('No');
+		}
+	}
+
+	$avg_student_progress = $avg_student_score = $nb_courses = 0;
+	$sql = 'SELECT course_code FROM ' . $tbl_course_user . ' WHERE user_id=' . Database :: escape_string($info_user['user_id']);
+	$rs = Database::query($sql, __FILE__, __LINE__);
+	$courses = array ();
+	while ($row = Database :: fetch_array($rs)) {
+		$courses[$row['course_code']] = $row['course_code'];
+	}
+
+	// get the list of sessions where the user is subscribed as student
+	$sql = 'SELECT DISTINCT course_code FROM ' . Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . ' WHERE id_user=' . intval($info_user['user_id']);
+	$rs = Database::query($sql, __FILE__, __LINE__);
+	while ($row = Database :: fetch_array($rs)) {
+		$courses[$row['course_code']] = $row['course_code'];
+	}
+
+	$course_id = Security :: remove_XSS($_GET['course']);
+	if (!CourseManager :: is_user_subscribed_in_course($info_user['user_id'], $course_id, true)) {
+		unset ($courses[$key]);
+	} else {
+		$nb_courses++;
+		$avg_student_progress = Tracking :: get_avg_student_progress($info_user['user_id'], $course_id);
+		//the score inside the Reporting table
+		$avg_student_score = Tracking :: get_average_test_scorm_and_lp($info_user['user_id'], $course_id);
+	}
+
+	$avg_student_progress = round($avg_student_progress, 2);
+	$avg_student_score = round($avg_student_score, 2);
+
+	$first_connection_date = Tracking :: get_first_connection_date($info_user['user_id']);
+	if ($first_connection_date == '') {
+		$first_connection_date = get_lang('NoConnexion');
+	}
+
+	$last_connection_date = Tracking :: get_last_connection_date($info_user['user_id'], true);
+	if ($last_connection_date == '') {
+		$last_connection_date = get_lang('NoConnexion');
+	}
+
+	$time_spent_on_the_course = api_time_to_hms(Tracking :: get_time_spent_on_the_course($info_user['user_id'], $course_id));
+	// cvs informations
+	$csv_content[] = array (
+		get_lang('Informations', '')
+	);
+	$csv_content[] = array (
+		get_lang('Name', ''),
+		get_lang('Email', ''),
+		get_lang('Tel', '')
+	);
+	$csv_content[] = array (
+		$info_user['name'],
+		$info_user['email'],
+		$info_user['phone']
+	);
+
+	$csv_content[] = array ();
+
+	// csv tracking
+	$csv_content[] = array (
+		get_lang('Tracking', '')
+	);
+	$csv_content[] = array (
+		get_lang('FirstLogin', ''),
+		get_lang('LatestLogin', ''),
+		get_lang('TimeSpentInTheCourse', ''),
+		get_lang('Progress', ''),
+		get_lang('Score', '')
+	);
+	$csv_content[] = array (
+		strip_tags($first_connection_date),
+		strip_tags($last_connection_date),
+		$time_spent_on_the_course,
+		$avg_student_progress . '%',
+		$avg_student_score . '%'
+	);
+?>
+	<a name="infosStudent"></a>
+				<table width="100%" border="0" >
+					<tr>
+
+							<?php
+
+	$image_array = UserManager :: get_user_picture_path_by_id($info_user['user_id'], 'web', false, true);
+	echo '<td class="borderRight" width="10%" valign="top">';
+
+	// get the path,width and height from original picture
+	$image_file = $image_array['dir'] . $image_array['file'];
+	$big_image = $image_array['dir'] . 'big_' . $image_array['file'];
+	$big_image_size = api_getimagesize($big_image);
+	$big_image_width = $big_image_size[0];
+	$big_image_height = $big_image_size[1];
+	$url_big_image = $big_image . '?rnd=' . time();
+	$img_attributes = 'src="' . $image_file . '?rand=' . time() . '" ' .
+	'alt="' . api_get_person_name($info_user['lastname'], $info_user['firstname']) . '" ' .
+	'style="float:' . ($text_dir == 'rtl' ? 'left' : 'right') . '; padding:5px;" ';
+
+	if ($image_array['file'] == 'unknown.jpg') {
+		echo '<img ' . $img_attributes . ' />';
+	} else {
+		echo '<input type="image" ' . $img_attributes . ' onclick="javascript: return show_image(\'' . $url_big_image . '\',\'' . $big_image_width . '\',\'' . $big_image_height . '\');"/>';
+	}
+
+	echo '</td>';
+?>
+
+			<td width="40%" valign="top">
+
+				<table width="100%" class="data_table">
+								<tr>
+									<th>
+										<?php echo get_lang('Information'); ?>
+									</th>
+								</tr>
+								<tr>
+						<td>
+										<?php
+
+	echo get_lang('Name') . ' : ';
+	echo $info_user['name'];
+?>
+									</td>
+								</tr>
+								<tr>
+						<td>
+										<?php
+
+	echo get_lang('Email') . ' : ';
+	if (!empty ($info_user['email'])) {
+		echo '<a href="mailto:' . $info_user['email'] . '">' . $info_user['email'] . '</a>';
+	} else {
+		echo get_lang('NoEmail');
+	}
+?>
+									</td>
+								</tr>
+								<tr>
+						<td>
+										<?php
+
+	echo get_lang('Tel') . '. ';
+
+	if (!empty ($info_user['phone'])) {
+		echo $info_user['phone'];
+	} else {
+		echo get_lang('NoTel');
+	}
+?>
+									</td>
+								</tr>
+								<tr>
+						<td>
+										<?php
+
+	echo get_lang('OfficialCode') . ' : ';
+
+	if (!empty ($info_user['official_code'])) {
+		echo $info_user['official_code'];
+	} else {
+		echo get_lang('NoOfficialCode');
+	}
+?>
+									</td>
+								</tr>
+								<tr>
+						<td>
+										<?php
+
+	echo get_lang('OnLine') . ' : ';
+	echo $online;
+?>
+									</td>
+								</tr>
+							</table>
+						</td>
+						<td class="borderLeft" width="35%" valign="top">
+
+				<table width="100%" class="data_table">
+								<tr>
+						<th colspan="2">
+										<?php echo get_lang('Tracking'); ?>
+									</th>
+								</tr>
+								<tr>
+						<td align="right">
+													<?php echo get_lang('FirstLogin') ?>
+												</td>
+						<td align="left">
+													<?php echo $first_connection_date ?>
+												</td>
+											</tr>
+											<tr>
+						<td align="right">
+													<?php echo get_lang('LatestLogin') ?>
+												</td>
+						<td align="left">
+													<?php echo $last_connection_date ?>
+												</td>
+											</tr>
+											<tr>
+						<td align="right">
+													<?php echo get_lang('TimeSpentInTheCourse') ?>
+												</td>
+						<td align="left">
+													<?php echo $time_spent_on_the_course ?>
+												</td>
+											</tr>
+											<tr>
+						<td align="right">
+													<?php
+
+	echo get_lang('Progress');
+	Display :: display_icon('info3.gif', get_lang('ScormAndLPProgressTotalAverage'), array (
+		'align' => 'absmiddle',
+		'hspace' => '3px'
+	));
+?>
+												</td>
+						<td align="left">
+													<?php echo $avg_student_progress.'%' ?>
+												</td>
+											</tr>
+											<tr>
+						<td align="right">
+													<?php
+
+	echo get_lang('Score');
+	Display :: display_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array (
+		'align' => 'absmiddle',
+		'hspace' => '3px'
+	));
+?>
+												</td>
+						<td align="left">
+													<?php  echo $avg_student_score.'%' ?>
+												</td>
+											</tr>
+										</table>
+									</td>
+					</tr>
+				</table>
+
+	<table class="data_table">
+		<tr>
+			<td colspan="5" style="border-width: 0px;">&nbsp;</td>
+		</tr>
+<?php
+
+	if (!empty ($_GET['details'])) {
+		$course_code_info = Security :: remove_XSS($_GET['course']);
+		$info_course = CourseManager :: get_course_information($course_code_info);
+
+		//get coach and session_name if there is one and if session_mode is activated
+		if (api_get_setting('use_session_mode') == 'true') {
+			$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
+			$tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
+			$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+			$tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+			$sql = 'SELECT id_session
+										FROM ' . $tbl_session_course_user . ' session_course_user
+										WHERE session_course_user.id_user = ' . intval($info_user['user_id']) . '
+										AND session_course_user.course_code = "' . Database :: escape_string($course_code_info) . '"
+										ORDER BY id_session DESC';
+			$rs = Database::query($sql, __FILE__, __LINE__);
+			$num_row = Database :: num_rows($rs);
+			if ($num_row > 0) {
+				$le_session_id = intval(Database :: result($rs, 0, 0));
+				if ($le_session_id > 0) {
+					// get session name and coach of the session
+					$sql = 'SELECT name, id_coach FROM ' . $tbl_session . '
+														WHERE id=' . $le_session_id;
+					$rs = Database::query($sql, __FILE__, __LINE__);
+					$session_name = Database :: result($rs, 0, 'name');
+					$session_coach_id = intval(Database :: result($rs, 0, 'id_coach'));
+
+					// get coach of the course in the session
+					$sql = 'SELECT id_coach FROM ' . $tbl_session_course . '
+														WHERE id_session=' . $le_session_id . '
+														AND course_code = "' . Database :: escape_string($_GET['course']) . '"';
+					$rs = Database::query($sql, __FILE__, __LINE__);
+					$session_course_coach_id = intval(Database :: result($rs, 0, 0));
+
+					if ($session_course_coach_id != 0) {
+						$coach_infos = UserManager :: get_user_info_by_id($session_course_coach_id);
+						$info_course['tutor_name'] = api_get_person_name($coach_infos['firstname'], $coach_infos['lastname']);
+					}
+					elseif ($session_coach_id != 0) {
+						$coach_infos = UserManager :: get_user_info_by_id($session_coach_id);
+						$info_course['tutor_name'] = api_get_person_name($coach_infos['firstname'], $coach_infos['lastname']);
+					}
+				}
+			}
+		} // end if(api_get_setting('use_session_mode')=='true')
+
+		$date_start = '';
+		if (!empty ($info_course['date_start'])) {
+			$date_start = explode('-', $info_course['date_start']);
+			$date_start = $date_start[2] . '/' . $date_start[1] . '/' . $date_start[0];
+		}
+		$date_end = '';
+		if (!empty ($info_course['date_end'])) {
+			$date_end = explode('-', $info_course['date_end']);
+			$date_end = $date_end[2] . '/' . $date_end[1] . '/' . $date_end[0];
+		}
+		$dateSession = get_lang('From') . ' ' . $date_start . ' ' . get_lang('To') . ' ' . $date_end;
+		$nb_login = Tracking :: count_login_per_student($info_user['user_id'], $_GET['course']);
+		$table_title = $info_course['title'] . '&nbsp;|&nbsp;' . get_lang('CountToolAccess') . ' : ' . $nb_login . '&nbsp; | &nbsp;' . get_lang('Tutor') . ' : ' . stripslashes($info_course['tutor_name']) . ((!empty ($session_name)) ? ' | ' . get_lang('Session') . ' : ' . $session_name : '');
+
+		$csv_content[] = array ();
+		$csv_content[] = array (str_replace('&nbsp;', '', $table_title));
+?>
+		<tr>
+			<td colspan="6">
+					<strong><?php echo $table_title; ?></strong>
+			</td>
+		</tr>
+	</table>
+
+	<!-- line about learnpaths -->
+				<table class="data_table">
+					<tr>
+						<th>
+							<?php echo get_lang('Learnpaths');?>
+						</th>
+						<th>
+							<?php
+
+		echo get_lang('Time');
+		Display :: display_icon('info3.gif', get_lang('TotalTimeByCourse'), array (
+			'align' => 'absmiddle',
+			'hspace' => '3px'
+		));
+?>
+						</th>
+						<th>
+							<?php
+
+		echo get_lang('Score');
+		Display :: display_icon('info3.gif', get_lang('LPTestScore'), array (
+			'align' => 'absmiddle',
+			'hspace' => '3px'
+		));
+?>
+						</th>
+						<th>
+							<?php
+
+		echo get_lang('Progress');
+		Display :: display_icon('info3.gif', get_lang('LPProgressScore'), array (
+			'align' => 'absmiddle',
+			'hspace' => '3px'
+		));
+?>
+						</th>
+						<th>
+							<?php
+
+		echo get_lang('LastConnexion');
+		Display :: display_icon('info3.gif', get_lang('LastTimeTheCourseWasUsed'), array (
+			'align' => 'absmiddle',
+			'hspace' => '3px'
+		));
+?>
+						</th>
+						<th>
+							<?php echo get_lang('Details');?>
+						</th>
+					</tr>
+<?php
+
+		$headerLearnpath = array (
+			get_lang('Learnpath'),
+			get_lang('Time'),
+			get_lang('Progress'),
+			get_lang('LastConnexion')
+		);
+
+		$t_lp = Database :: get_course_table(TABLE_LP_MAIN, $info_course['db_name']);
+		$t_lpi = Database :: get_course_table(TABLE_LP_ITEM, $info_course['db_name']);
+		$t_lpv = Database :: get_course_table(TABLE_LP_VIEW, $info_course['db_name']);
+		$t_lpiv = Database :: get_course_table(TABLE_LP_ITEM_VIEW, $info_course['db_name']);
+
+		$tbl_stats_exercices = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+		$tbl_stats_attempts = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+		$tbl_quiz_questions = Database :: get_course_table(TABLE_QUIZ_QUESTION, $info_course['db_name']);
+
+		$sql_learnpath = "SELECT lp.name,lp.id
+										FROM $t_lp AS lp ORDER BY lp.name ASC
+									";
+
+		$result_learnpath = Database::query($sql_learnpath, __FILE__, __LINE__);
+
+		$csv_content[] = array ();
+		$csv_content[] = array (
+			get_lang('Learnpath', ''),
+			get_lang('Time', ''),
+			get_lang('Score', ''),
+			get_lang('Progress', ''),
+			get_lang('LastConnexion', '')
+		);
+
+		if (Database :: num_rows($result_learnpath) > 0) {
+			$i = 0;
+			while ($learnpath = Database :: fetch_array($result_learnpath)) {
+				$any_result = false;
+				$progress = learnpath :: get_db_progress($learnpath['id'], $student_id, '%', $info_course['db_name'], true);
+				if ($progress === null) {
+					$progress = '0%';
+				} else {
+					$any_result = true;
+				}
+
+				// calculates time
+				$sql = 'SELECT SUM(total_time)
+												FROM ' . $t_lpiv . ' AS item_view
+												INNER JOIN ' . $t_lpv . ' AS view
+													ON item_view.lp_view_id = view.id
+													AND view.lp_id = ' . $learnpath['id'] . '
+													AND view.user_id = ' . intval($_GET['student']);
+				$rs = Database::query($sql, __FILE__, __LINE__);
+				$total_time = 0;
+				if (Database :: num_rows($rs) > 0) {
+					$total_time = Database :: result($rs, 0, 0);
+					if ($total_time > 0)
+						$any_result = true;
+				}
+
+				// calculates last connection time
+				$sql = 'SELECT MAX(start_time)
+												FROM ' . $t_lpiv . ' AS item_view
+												INNER JOIN ' . $t_lpv . ' AS view
+													ON item_view.lp_view_id = view.id
+													AND view.lp_id = ' . $learnpath['id'] . '
+													AND view.user_id = ' . intval($_GET['student']);
+				$rs = Database::query($sql, __FILE__, __LINE__);
+				$start_time = null;
+				if (Database :: num_rows($rs) > 0) {
+					$start_time = Database :: result($rs, 0, 0);
+					if ($start_time > 0)
+						$any_result = true;
+				}
+
+				//QUIZZ IN LP
+				$score = Tracking :: get_avg_student_score(intval($_GET['student']), Database :: escape_string($_GET['course']), array (
+					$learnpath['id']
+				));
+
+				if (empty ($score)) {
+					//$score = 0;
+				}
+				if ($i % 2 == 0) {
+					$css_class = "row_odd";
+				} else {
+					$css_class = "row_even";
+				}
+
+				$i++;
+
+				$csv_content[] = array (
+					api_html_entity_decode(stripslashes($learnpath['name']), ENT_QUOTES, $charset),
+					api_time_to_hms($total_time),
+					$score . '%',
+					$progress,
+					date('Y-m-d', $start_time)
+				);
+?>
+					<tr class="<?php echo $css_class;?>">
+						<td>
+							<?php echo stripslashes($learnpath['name']); ?>
+						</td>
+						<td align="center">
+						<?php echo api_time_to_hms($total_time) ?>
+						</td>
+						<td align="center">
+							<?php
+
+				if (!is_null($score)) {
+					echo $score . '%';
+				} else {
+					if ('0' == $progress {
+						0 }) {
+						echo '/';
+					} else {
+						echo '0%';
+					}
+					$score = 0;
+				}
+?>
+						</td>
+						<td align="center">
+							<?php echo $progress ?>
+						</td>
+						<td align="center">
+							<?php
+				if ($start_time != '' && $start_time > 0) {
+					echo format_locale_date(get_lang('DateFormatLongWithoutDay'), $start_time);
+				} else {
+					echo '-';
+				}
+?>
+						</td>
+						<td align="center">
+							<?php
+				if ($any_result === true) {
+					$from = '';
+					if ($from_myspace) {
+						$from ='&from=myspace';
+					}
+?>
+					<a href="lp_tracking.php?course=<?php echo Security::remove_XSS($_GET['course']).$from; ?>&origin=<?php echo Security::remove_XSS($_GET['origin']) ?>&lp_id=<?php echo $learnpath['id']?>&student_id=<?php echo $info_user['user_id'] ?>">
+						<img src="../img/2rightarrow.gif" border="0" />
+					</a>
+					<?php
+				}
+?>
+						</td>
+					</tr>
+				<?php
+				$data_learnpath[$i][] = $learnpath['name'];
+				$data_learnpath[$i][] = $progress . '%';
+				$i++;
+			}
+		} else {
+			echo "	<tr>
+										<td colspan='6'>
+											" . get_lang('NoLearnpath') . "
+										</td>
+									</tr>
+								 ";
+		}
+?>
+				</table>
+
+	<!-- line about exercises -->
+			<table class="data_table">
+				<tr>
+					<th>
+						<?php echo get_lang('Exercices'); ?>
+					</th>
+					<th>
+						<?php echo get_lang('Score').Display :: return_icon('info3.gif', get_lang('LastScoreTest'), array('align' => 'absmiddle', 'hspace' => '3px')) ?>
+					</th>
+					<th>
+						<?php echo get_lang('Attempts'); ?>
+					</th>
+					<th>
+						<?php echo get_lang('CorrectTest'); ?>
+					</th>
+				</tr>
+			<?php
+
+		$csv_content[] = array ();
+		$csv_content[] = array (
+			get_lang('Exercices'),
+			get_lang('Score'),
+			get_lang('Attempts')
+		);
+
+		$info_course = CourseManager :: get_course_information(Security :: remove_XSS($_GET['course']));
+		$t_tool = Database :: get_course_table(TABLE_TOOL_LIST, $info_course['db_name']);
+		$sql = 'SELECT visibility FROM ' . $t_tool . ' WHERE name="quiz"';
+
+		$result_visibility_quizz = Database::query($sql, __FILE__, __LINE__);
+		$t_quiz = Database :: get_course_table(TABLE_QUIZ_TEST, $info_course['db_name']);
+
+		if (Database :: result($result_visibility_quizz, 0, 'visibility') == 1) {
+
+			$sql_exercices = "SELECT quiz.title,id
+												FROM " . $t_quiz . " AS quiz
+												WHERE active='1' ORDER BY quiz.title ASC
+												";
+
+			$result_exercices = Database::query($sql_exercices, __FILE__, __LINE__);
+			$i = 0;
+			$is_student = Security :: remove_XSS($_GET['student']);
+			if (Database :: num_rows($result_exercices) > 0) {
+				while ($exercices = Database :: fetch_array($result_exercices)) {
+					$sql_essais = "SELECT COUNT(ex.exe_id) as essais
+															FROM $tbl_stats_exercices AS ex
+															WHERE  ex.exe_cours_id = '" . $info_course['code'] . "'
+															AND ex.exe_exo_id = " . $exercices['id'] . "
+															AND orig_lp_id = 0
+															AND orig_lp_item_id = 0
+															AND exe_user_id='" . Database :: escape_string($is_student) . "'";
+					$result_essais = Database::query($sql_essais, __FILE__, __LINE__);
+					$essais = Database :: fetch_array($result_essais);
+
+					$sql_score = "SELECT exe_id, exe_result,exe_weighting
+														 FROM $tbl_stats_exercices
+														 WHERE exe_user_id = " . Database :: escape_string($is_student) . "
+														 AND exe_cours_id = '" . $info_course['code'] . "'
+														 AND exe_exo_id = " . $exercices['id'] . "
+														 AND orig_lp_id = 0
+														 AND orig_lp_item_id = 0
+														 ORDER BY exe_date DESC LIMIT 1";
+
+					$result_score = Database::query($sql_score, __FILE__, __LINE__);
+					$score = 0;
+					while ($scores = Database :: fetch_array($result_score)) {
+						$score = $score + $scores['exe_result'];
+						$weighting = $weighting + $scores['exe_weighting'];
+						$exe_id = $scores['exe_id'];
+					}
+					$score_percentage = 0;
+					if ($weighting != 0) {
+						//i.e 10.50
+						$score_percentage = round(($score * 100) / $weighting, 2);
+					} else {
+						$score_percentage = null;
+					}
+
+					$weighting = 0;
+
+					$csv_content[] = array (
+						$exercices['title'],
+						$score_percentage . '%',
+						$essais['essais']
+					);
+
+					if ($i % 2 == 0) {
+						$css_class = "row_odd";
+					} else {
+						$css_class = "row_even";
+					}
+
+					$i++;
+
+					echo '<tr class="' . $css_class . '">
+													<td>
+										 ';
+					echo $exercices['title'];
+					echo "	</td>
+												 ";
+					echo "	<td align='center'>
+												  ";
+					if ($essais['essais'] > 0) {
+						echo $score_percentage . '%';
+					} else {
+						echo '/';
+						$score_percentage = 0;
+					}
+
+					echo "	</td>
+													<td align='center'>
+												 ";
+					echo $essais['essais'];
+					echo "	</td>
+													<td align='center'>
+												 ";
+
+					$sql_last_attempt = 'SELECT exe_id FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $exercices['id'] . '" AND exe_user_id="' . Security :: remove_XSS($_GET['student']) . '" AND exe_cours_id="' . $info_course['code'] . '" AND orig_lp_id = 0 AND orig_lp_item_id = 0 ORDER BY exe_date DESC LIMIT 1';
+					$result_last_attempt = Database::query($sql_last_attempt, __FILE__, __LINE__);
+					if (Database :: num_rows($result_last_attempt) > 0) {
+						$id_last_attempt = Database :: result($result_last_attempt, 0, 0);
+
+						if ($essais['essais'] > 0)
+							echo '<a href="../exercice/exercise_show.php?id=' . $id_last_attempt . '&cidReq=' . $info_course['code'] . '&student=' . Security :: remove_XSS($_GET['student']) . '&origin=' . (empty ($_GET['origin']) ? 'tracking' : Security :: remove_XSS($_GET['origin'])) . '"> <img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" border="0" /> </a>';
+					}
+					echo "	</td>
+												  </tr>
+												 ";
+					$data_exercices[$i][] = $exercices['title'];
+					$data_exercices[$i][] = $score_percentage . '%';
+					$data_exercices[$i][] = $essais['essais'];
+					//$data_exercices[$i][] =  corrections;
+					$i++;
+
+				}
+			} else {
+				echo "	<tr>
+												<td colspan='6'>
+													" . get_lang('NoExercise') . "
+												</td>
+											</tr>
+										 ";
+			}
+		} else {
+			echo "	<tr>
+										<td colspan='6'>
+											" . get_lang('NoExercise') . "
+										</td>
+									</tr>
+								 ";
+		}
+?>
+					</table>
+
+	<!-- line about other tools -->
+			<table class="data_table">
+	<tr>
+		<td>
+			<?php
+
+		$csv_content[] = array ();
+
+		$nb_assignments = Tracking :: count_student_assignments($info_user['user_id'], $info_course['code']);
+		$messages = Tracking :: count_student_messages($info_user['user_id'], $info_course['code']);
+		$links = Tracking :: count_student_visited_links($info_user['user_id'], $info_course['code']);
+		$documents = Tracking :: count_student_downloaded_documents($info_user['user_id'], $info_course['code']);
+		$chat_last_connection = Tracking :: chat_last_connection($info_user['user_id'], $info_course['code']);
+
+		$csv_content[] = array (
+			get_lang('Student_publication'),
+			$nb_assignments
+		);
+		$csv_content[] = array (
+			get_lang('Messages'),
+			$messages
+		);
+		$csv_content[] = array (
+			get_lang('LinksDetails'),
+			$links
+		);
+		$csv_content[] = array (
+			get_lang('DocumentsDetails'),
+			$documents
+		);
+		$csv_content[] = array (
+			get_lang('ChatLastConnection'),
+			$chat_last_connection
+		);
+?>
+				<tr>
+					<th colspan="2">
+						<?php echo get_lang('OtherTools'); ?>
+					</th>
+				</tr>
+				<tr><!-- assignments -->
+					<td width="40%">
+						<?php echo get_lang('Student_publication') ?>
+					</td>
+					<td>
+						<?php echo $nb_assignments ?>
+					</td>
+				</tr>
+				<tr><!-- messages -->
+					<td>
+						<?php echo get_lang('Messages') ?>
+					</td>
+					<td>
+						<?php echo $messages ?>
+					</td>
+				</tr>
+				<tr><!-- links -->
+					<td>
+						<?php echo get_lang('LinksDetails') ?>
+					</td>
+					<td>
+						<?php echo $links ?>
+					</td>
+				</tr>
+				<tr><!-- documents -->
+					<td>
+						<?php echo get_lang('DocumentsDetails') ?>
+					</td>
+					<td>
+						<?php echo $documents ?>
+					</td>
+				</tr>
+				<tr><!-- Chats -->
+					<td>
+						<?php echo get_lang('ChatLastConnection') ?>
+					</td>
+					<td>
+						<?php echo $chat_last_connection; ?>
+					</td>
+				</tr>
+			</table>
+			</td>
+		</tr>
+		</table>
+<?php
+
+	} else {
+?>
+		<tr>
+			<th>
+				<?php echo get_lang('Course'); ?>
+			</th>
+			<th>
+				<?php echo get_lang('Time'); ?>
+			</th>
+			<th>
+				<?php echo get_lang('Progress'); ?>
+			</th>
+			<th>
+				<?php echo get_lang('Score'); ?>
+			</th>
+			<th>
+				<?php echo get_lang('Details'); ?>
+			</th>
+		</tr>
+<?php
+
+		if (!api_is_platform_admin(true) && $_user['status'] != DRH) {
+			// courses followed by user where we are coach
+			if (!isset ($_GET['id_coach'])) {
+				$courses = Tracking :: get_courses_followed_by_coach($_user['user_id']);
+			} else {
+				$courses = Tracking :: get_courses_followed_by_coach(Security :: remove_XSS($_GET['id_coach']));
+			}
+		}
+		if (count($courses) > 0) {
+			$csv_content[] = array ();
+			$csv_content[] = array (
+				get_lang('Course', ''),
+				get_lang('Time', ''),
+				get_lang('Progress', ''),
+				get_lang('Score', '')
+			);
+			foreach ($courses as $course_code) {
+				if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
+					$course_info = CourseManager :: get_course_information($course_code);
+					$time_spent_on_course = api_time_to_hms(Tracking :: get_time_spent_on_the_course($info_user['user_id'], $course_code));
+					$progress = Tracking :: get_avg_student_progress($info_user['user_id'], $course_code);
+					$score = Tracking :: get_avg_student_score($info_user['user_id'], $course_code);
+					$progress = empty($progress) ? '0%' : $progress.'%';
+					$score = empty($score) ? '0%' : $score.'%';
+					$csv_content[] = array (
+						$course_info['title'],
+						$time_spent_on_course,
+						$progress,
+						$score
+					);
+					echo '
+										<tr>
+											<td align="right">
+												' . $course_info['title'] . '
+											</td>
+											<td align="right">
+												' . $time_spent_on_course . '
+											</td>
+											<td align="right">
+												' . $progress . '
+											</td>
+											<td align="right">
+												' . $score . '
+											</td>';
+					if (isset ($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
+						echo '<td align="center" width="10">
+														<a href="' . api_get_self() . '?student=' . $info_user['user_id'] . '&details=true&course=' . $course_info['code'] . '&id_coach=' . Security :: remove_XSS($_GET['id_coach']) . '&origin=' . Security :: remove_XSS($_GET['origin']) . '&id_session=' . Security :: remove_XSS($_GET['id_session']) . '#infosStudent"><img src="' . api_get_path(WEB_IMG_PATH) . '2rightarrow.gif" border="0" /></a>
+													</td>';
+					} else {
+						echo '<td align="center" width="10">
+														<a href="' . api_get_self() . '?student=' . $info_user['user_id'] . '&details=true&course=' . $course_info['code'] . '&origin=' . Security :: remove_XSS($_GET['origin']) . '&id_session=' . Security :: remove_XSS($_GET['id_session']) . '#infosStudent"><img src="' . api_get_path(WEB_IMG_PATH) . '2rightarrow.gif" border="0" /></a>
+													</td>';
+					}
+					echo '</tr>';
+				}
+
+			}
+		} else {
+			echo "<tr>
+								<td colspan='5'>
+									" . get_lang('NoCourse') . "
+								</td>
+							  </tr>
+							 ";
+		}
+	} //end of else !empty($details)
+?>
+	</table>
+	<br />
+<?php
+
+	if (!empty ($_GET['details']) && $_GET['origin'] != 'tracking_course' && $_GET['origin'] != 'user_course') {
+?>
+
+		<br /><br />
+<?php
+
+	}
+	if (!empty ($_GET['exe_id'])) {
+		$t_q = Database :: get_course_table(TABLE_QUIZ_TEST, $info_course['db_name']);
+		$t_qq = Database :: get_course_table(TABLE_QUIZ_QUESTION, $info_course['db_name']);
+		$t_qa = Database :: get_course_table(TABLE_QUIZ_ANSWER, $info_course['db_name']);
+		$t_qtq = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION, $info_course['db_name']);
+		$sql_exercice_details = "SELECT qq.question, qq.ponderation, qq.id
+						 				FROM " . $t_qq . " as qq
+										INNER JOIN " . $t_qtq . " as qrq
+											ON qrq.question_id = qq.id
+											AND qrq.exercice_id = " . intval($_GET['exe_id']);
+
+		$result_exercice_details = Database::query($sql_exercice_details, __FILE__, __LINE__);
+
+		$sql_ex_name = "SELECT quiz.title
+								FROM " . $t_q . " AS quiz
+							 	WHERE quiz.id = " . intval($_GET['exe_id']);
+		;
+
+		$resultExName = Database::query($sql_ex_name, __FILE__, __LINE__);
+		$exName = Database :: fetch_array($resultExName);
+
+		echo "<table class='data_table'>
+					 	<tr>
+							<th colspan='2'>
+								" . $exName['title'] . "
+							</th>
+						</tr>
+		             ";
+
+		while ($exerciceDetails = Database :: fetch_array($result_exercice_details)) {
+			$sqlAnswer = "	SELECT qa.comment, qa.answer
+										FROM  " . $t_qa . " as qa
+										WHERE qa.question_id = " . $exerciceDetails['id'];
+
+			$resultAnswer = Database::query($sqlAnswer, __FILE__, __LINE__);
+
+			echo "<a name='infosExe'></a>";
+
+			echo "
+						<tr>
+							<td colspan='2'>
+								<strong>" . $exerciceDetails['question'] . ' /' . $exerciceDetails['ponderation'] . "</strong>
+							</td>
+						</tr>
+						";
+			while ($answer = Database :: fetch_array($resultAnswer)) {
+				echo "
+								<tr>
+									<td>
+										" . $answer['answer'] . "
+									</td>
+									<td>
+								";
+				if (!empty ($answer['comment']))
+					echo $answer['comment'];
+				else
+					echo get_lang('NoComment');
+				echo "
+									</td>
+								</tr>
+								";
+			}
+		}
+		echo "</table>";
+	}
+	//YW - commented out because it doesn't seem to be used
+	//$header = array_merge($headerLearnpath,$headerExercices,$headerProductions);
+}
+if ($export_csv) {
+	ob_end_clean();
+	Export :: export_table_csv($csv_content, 'reporting_student');
+}
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display :: display_footer();

+ 43 - 43
main/mySpace/myspace.lib.php

@@ -1,43 +1,43 @@
-<?php
-
-/* For licensing terms, see /dokeos_license.txt */
-
-/**
- * This function serves exporting data in CSV format.
- * @param array $header			The header labels.
- * @param array $data			The data array.
- * @param string $file_name		The name of the file which contains exported data.
- * @return mixed				Returns a message (string) if an error occurred.
- */
-function export_csv($header, $data, $file_name = 'export.csv') {
-
-	$archive_path = api_get_path(SYS_ARCHIVE_PATH);
-	$archive_url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive=';
-
-	if (!$open = fopen($archive_path.$file_name, 'w+')) {
-		$message = get_lang('noOpen');
-	} else {
-		$info = '';
-
-		foreach ($header as $value) {
-			$info .= $value.';';
-		}
-		$info .= "\r\n";
-
-		foreach ($data as $row) {
-			foreach ($row as $value) {
-				$info .= $value.';';
-			}
-			$info .= "\r\n";
-		}
-
-		fwrite($open, $info);
-		fclose($open);
-		$perm = api_get_setting('permissions_for_new_files');
-		$perm = octdec(!empty($perm) ? $perm : '0660');
-		@chmod($file_name, $perm);
-
-		header("Location:".$archive_url.$file_name);
-	}
-	return $message;
-}
+<?php
+
+/* For licensing terms, see /dokeos_license.txt */
+
+/**
+ * This function serves exporting data in CSV format.
+ * @param array $header			The header labels.
+ * @param array $data			The data array.
+ * @param string $file_name		The name of the file which contains exported data.
+ * @return mixed				Returns a message (string) if an error occurred.
+ */
+function export_csv($header, $data, $file_name = 'export.csv') {
+
+	$archive_path = api_get_path(SYS_ARCHIVE_PATH);
+	$archive_url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive=';
+
+	if (!$open = fopen($archive_path.$file_name, 'w+')) {
+		$message = get_lang('noOpen');
+	} else {
+		$info = '';
+
+		foreach ($header as $value) {
+			$info .= $value.';';
+		}
+		$info .= "\r\n";
+
+		foreach ($data as $row) {
+			foreach ($row as $value) {
+				$info .= $value.';';
+			}
+			$info .= "\r\n";
+		}
+
+		fwrite($open, $info);
+		fclose($open);
+		$perm = api_get_setting('permissions_for_new_files');
+		$perm = octdec(!empty($perm) ? $perm : '0660');
+		@chmod($file_name, $perm);
+
+		header("Location:".$archive_url.$file_name);
+	}
+	return $message;
+}

+ 81 - 81
main/mySpace/progression.php

@@ -1,81 +1,81 @@
-<?php
-
-/*
- * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
- */
-
-// TODO: This file seems to be unfinished and unused.
-
-$language_file = array ('registration', 'index', 'tracking');
-
-require '../inc/global.inc.php';
-require_once api_get_path(SYS_CODE_PATH).'mySpace/myspace.lib.php';
-
-$nameTools = get_lang('Progression');
-
-$cidReset = true;
-
-$this_section = "session_my_space";
-
-api_block_anonymous_users();
-$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
-Display :: display_header($nameTools);
-
-// Database Table Definitions
-$tbl_course 		= Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_user 			= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session 		= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_track_exercice = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-
-/*
-===============================================================================
- 	MAIN CODE
-===============================================================================
-*/
-$sql_course = "SELECT 	title,code
-	FROM $tbl_course as course
-	ORDER BY title ASC";
-
-$result_course = Database::query($sql_course, __FILE__, __LINE__);
-
-if (Database::num_rows($result_course) > 0) {
-	if (isset($_POST['export'])) {
-		$export_result = export_csv($header, $data, 'test.csv'); // TODO: There is no data for exporting yet.
-		Display :: display_error_message($export_result);
-	}
-	echo '<table class="data_table"><tr><th>'.get_lang('Course').'</th><th>'.get_lang('TempsFrequentation').'</th><th>'.get_lang('Progression').'</th><th>'.get_lang('MoyenneTest').'</th></tr>';
-	$header = array(get_lang('Course', ''), get_lang('TempsFrequentation', ''), get_lang('Progression', ''), get_lang('MoyenneTest', ''));
-	while ($a_course = Database::fetch_array($result_course)) {
-		// TODO: This query is to be checked, there are no HotPotatoes tests results.
-		$sql_moy_test = "SELECT exe_result,exe_weighting
-			FROM $tbl_track_exercice
-			WHERE exe_cours_id = '".$a_course['code']."'";
-		$result_moy_test = Database::query($sql_moy_test, __FILE__, __LINE__);
-		$result = 0;
-		$weighting = 0;
-		while ($moy_test = Database::fetch_array($result_moy_test)) {
-			$result = $result + $moy_test['exe_result'];
-			$weighting = $weighting + $moy_test['exe_weighting'];
-		}
-		if ($weighting != 0) {
-			$moyenne_test = round(($result * 100) / $weighting);
-		} else {
-			$moyenne_test = null;
-		}
-		echo '<tr><td>'.$a_course['title'].'</td><td> </td><td> </td><td align="center">'.(is_null($moyenne_test) ? '' : $moyenne_test.'%').'</td> </tr>';
-	}
-	echo '</table>';
-	echo "<br /><br />";
-	echo "<form method='post'><input type='submit' name='export' value='".get_lang('exportExcel')."'/><form>";
-} else {
-	echo get_lang('NoCourse');
-}
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-
-Display :: display_footer();
+<?php
+
+/*
+ * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
+ */
+
+// TODO: This file seems to be unfinished and unused.
+
+$language_file = array ('registration', 'index', 'tracking');
+
+require '../inc/global.inc.php';
+require_once api_get_path(SYS_CODE_PATH).'mySpace/myspace.lib.php';
+
+$nameTools = get_lang('Progression');
+
+$cidReset = true;
+
+$this_section = "session_my_space";
+
+api_block_anonymous_users();
+$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
+Display :: display_header($nameTools);
+
+// Database Table Definitions
+$tbl_course 		= Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_user 			= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session 		= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_track_exercice = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+
+/*
+===============================================================================
+ 	MAIN CODE
+===============================================================================
+*/
+$sql_course = "SELECT 	title,code
+	FROM $tbl_course as course
+	ORDER BY title ASC";
+
+$result_course = Database::query($sql_course, __FILE__, __LINE__);
+
+if (Database::num_rows($result_course) > 0) {
+	if (isset($_POST['export'])) {
+		$export_result = export_csv($header, $data, 'test.csv'); // TODO: There is no data for exporting yet.
+		Display :: display_error_message($export_result);
+	}
+	echo '<table class="data_table"><tr><th>'.get_lang('Course').'</th><th>'.get_lang('TempsFrequentation').'</th><th>'.get_lang('Progression').'</th><th>'.get_lang('MoyenneTest').'</th></tr>';
+	$header = array(get_lang('Course', ''), get_lang('TempsFrequentation', ''), get_lang('Progression', ''), get_lang('MoyenneTest', ''));
+	while ($a_course = Database::fetch_array($result_course)) {
+		// TODO: This query is to be checked, there are no HotPotatoes tests results.
+		$sql_moy_test = "SELECT exe_result,exe_weighting
+			FROM $tbl_track_exercice
+			WHERE exe_cours_id = '".$a_course['code']."'";
+		$result_moy_test = Database::query($sql_moy_test, __FILE__, __LINE__);
+		$result = 0;
+		$weighting = 0;
+		while ($moy_test = Database::fetch_array($result_moy_test)) {
+			$result = $result + $moy_test['exe_result'];
+			$weighting = $weighting + $moy_test['exe_weighting'];
+		}
+		if ($weighting != 0) {
+			$moyenne_test = round(($result * 100) / $weighting);
+		} else {
+			$moyenne_test = null;
+		}
+		echo '<tr><td>'.$a_course['title'].'</td><td> </td><td> </td><td align="center">'.(is_null($moyenne_test) ? '' : $moyenne_test.'%').'</td> </tr>';
+	}
+	echo '</table>';
+	echo "<br /><br />";
+	echo "<form method='post'><input type='submit' name='export' value='".get_lang('exportExcel')."'/><form>";
+} else {
+	echo get_lang('NoCourse');
+}
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+
+Display :: display_footer();

+ 121 - 121
main/mySpace/reussite.php

@@ -1,121 +1,121 @@
-<?php
-/*
- * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
- */
-
-// TODO: Is this file used?
-
-$nameTools = 'Reussite';
-// name of the language file that needs to be included
-$language_file = array ('registration', 'index', 'trad4all', 'tracking');
-$cidReset = true;
-
-require '../inc/global.inc.php';
-
-$this_section = "session_my_space";
-
-api_block_anonymous_users();
-$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
-Display :: display_header($nameTools);
-
-// Database Table Definitions
-$tbl_course 		= Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_user 			= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session 		= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_track_exercice = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-
-/*
-===============================================================================
-	MAIN CODE
-===============================================================================
-*/
-if (!empty($_GET['session'])) {
-	$sql_session = "SELECT name,id
-		FROM $tbl_session
-		ORDER BY name ASC";
-	$result_session = Database::query($sql_session, __FILE__, __LINE__);
-
-	echo "<a href='".api_get_self()."'>".get_lang('MoyCourse')."</a>";
-	echo "<br /><br />";
-
-	if (Database::num_rows($result_session) > 0) {
-		echo '<table class="data_table"><tr><th>'.get_lang('Session').'</th><th>'.get_lang('MoyenneTest').'</th><th>'.get_lang('MoyenneExamen').'</th></tr>';
-		while ($session = Database::fetch_array($result_session)) {
-			$sql_course = "SELECT title,code
-				FROM $tbl_course as course
-				INNER JOIN $tbl_session_course AS rel_course
-				ON course.code = rel_course.course_code
-				AND rel_course.id_session = ".$session['id']."
-				ORDER BY title ASC";
-
-			$result_course = Database::query($sql_course, __FILE__, __LINE__);
-			$total_result = 0;
-			$total_weighting = 0;
-			while ($course = Database::fetch_array($result_course)) {
-				$sql_moy_test = "SELECT exe_result,exe_weighting
-					FROM $tbl_track_exercice
-					WHERE exe_cours_id = '".$course['code']."'";
-				$result_moy_test = Database::query($sql_moy_test);
-				$result = 0;
-				$weighting = 0;
-				while ($moy_test = Database::fetch_array($result_moy_test)) {
-					$result = $result + $moy_test['exe_result'];
-					$weighting = $weighting + $moy_test['exe_weighting'];
-				}
-				$total_result = $total_result + $result;
-				$total_weighting = $total_weighting + $weighting;
-			}
-			if ($total_weighting != 0) {
-				$moyenne_test = round(($total_result * 100) / $total_weighting);
-			} else {
-				$moyenne_test = null;
-			}
-
-			echo '<tr><td>'.$session['name'].'</td><td align="center">'.(is_null($moyenne_test) ? '' : $moyenne_test.'%').'</td><td> </td></tr>';
-		}
-		echo '</table>';
-	} else {
-		echo get_lang('NoSession');
-	}
-} else {
-	$sql_course = "SELECT 	title,code
-		FROM $tbl_course as course
-		ORDER BY title ASC";
-
-	$result_course = Database::query($sql_course, __FILE__, __LINE__);
-
-	echo "<a href='".api_get_self()."?session=true'>".get_lang('MoySession')."</a>";
-	echo "<br /><br />";
-	if (Database::num_rows($result_course) > 0) {
-		echo '<table class="data_table"><tr><th>'.get_lang('Course').'</th><th>'.get_lang('MoyenneTest').'</th><th>'.get_lang('MoyenneExamen').'</th></tr>';
-		while ($course= Database::fetch_array($result_course)) {
-			$sql_moy_test = "SELECT exe_result,exe_weighting
-				FROM $tbl_track_exercice
-				WHERE exe_cours_id = '".$course['code']."'";
-			$result_moy_test = Database::query($sql_moy_test, __FILE__, __LINE__);
-			$result = 0;
-			$weighting = 0;
-			while ($moy_test = Database::fetch_array($result_moy_test)) {
-				$result = $result + $moy_test['exe_result'];
-				$weighting = $weighting + $moy_test['exe_weighting'];
-			}
-			if ($weighting != 0) {
-				$moyenne_test = round(($result * 100) / $weighting);
-			} else {
-				$moyenne_test = null;
-			}
-			echo '<tr><td>'.$course['title'].'</td><td align="center">'.(is_null($moyenne_test) ? '' : $moyenne_test.'%').'</td><td> </td></tr>';
-		}
-		echo '</table>';
-	} else {
-		echo get_lang('NoCourse');
-	}
-}
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-
-Display :: display_footer();
+<?php
+/*
+ * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
+ */
+
+// TODO: Is this file used?
+
+$nameTools = 'Reussite';
+// name of the language file that needs to be included
+$language_file = array ('registration', 'index', 'trad4all', 'tracking');
+$cidReset = true;
+
+require '../inc/global.inc.php';
+
+$this_section = "session_my_space";
+
+api_block_anonymous_users();
+$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
+Display :: display_header($nameTools);
+
+// Database Table Definitions
+$tbl_course 		= Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_user 			= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session 		= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_track_exercice = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+
+/*
+===============================================================================
+	MAIN CODE
+===============================================================================
+*/
+if (!empty($_GET['session'])) {
+	$sql_session = "SELECT name,id
+		FROM $tbl_session
+		ORDER BY name ASC";
+	$result_session = Database::query($sql_session, __FILE__, __LINE__);
+
+	echo "<a href='".api_get_self()."'>".get_lang('MoyCourse')."</a>";
+	echo "<br /><br />";
+
+	if (Database::num_rows($result_session) > 0) {
+		echo '<table class="data_table"><tr><th>'.get_lang('Session').'</th><th>'.get_lang('MoyenneTest').'</th><th>'.get_lang('MoyenneExamen').'</th></tr>';
+		while ($session = Database::fetch_array($result_session)) {
+			$sql_course = "SELECT title,code
+				FROM $tbl_course as course
+				INNER JOIN $tbl_session_course AS rel_course
+				ON course.code = rel_course.course_code
+				AND rel_course.id_session = ".$session['id']."
+				ORDER BY title ASC";
+
+			$result_course = Database::query($sql_course, __FILE__, __LINE__);
+			$total_result = 0;
+			$total_weighting = 0;
+			while ($course = Database::fetch_array($result_course)) {
+				$sql_moy_test = "SELECT exe_result,exe_weighting
+					FROM $tbl_track_exercice
+					WHERE exe_cours_id = '".$course['code']."'";
+				$result_moy_test = Database::query($sql_moy_test);
+				$result = 0;
+				$weighting = 0;
+				while ($moy_test = Database::fetch_array($result_moy_test)) {
+					$result = $result + $moy_test['exe_result'];
+					$weighting = $weighting + $moy_test['exe_weighting'];
+				}
+				$total_result = $total_result + $result;
+				$total_weighting = $total_weighting + $weighting;
+			}
+			if ($total_weighting != 0) {
+				$moyenne_test = round(($total_result * 100) / $total_weighting);
+			} else {
+				$moyenne_test = null;
+			}
+
+			echo '<tr><td>'.$session['name'].'</td><td align="center">'.(is_null($moyenne_test) ? '' : $moyenne_test.'%').'</td><td> </td></tr>';
+		}
+		echo '</table>';
+	} else {
+		echo get_lang('NoSession');
+	}
+} else {
+	$sql_course = "SELECT 	title,code
+		FROM $tbl_course as course
+		ORDER BY title ASC";
+
+	$result_course = Database::query($sql_course, __FILE__, __LINE__);
+
+	echo "<a href='".api_get_self()."?session=true'>".get_lang('MoySession')."</a>";
+	echo "<br /><br />";
+	if (Database::num_rows($result_course) > 0) {
+		echo '<table class="data_table"><tr><th>'.get_lang('Course').'</th><th>'.get_lang('MoyenneTest').'</th><th>'.get_lang('MoyenneExamen').'</th></tr>';
+		while ($course= Database::fetch_array($result_course)) {
+			$sql_moy_test = "SELECT exe_result,exe_weighting
+				FROM $tbl_track_exercice
+				WHERE exe_cours_id = '".$course['code']."'";
+			$result_moy_test = Database::query($sql_moy_test, __FILE__, __LINE__);
+			$result = 0;
+			$weighting = 0;
+			while ($moy_test = Database::fetch_array($result_moy_test)) {
+				$result = $result + $moy_test['exe_result'];
+				$weighting = $weighting + $moy_test['exe_weighting'];
+			}
+			if ($weighting != 0) {
+				$moyenne_test = round(($result * 100) / $weighting);
+			} else {
+				$moyenne_test = null;
+			}
+			echo '<tr><td>'.$course['title'].'</td><td align="center">'.(is_null($moyenne_test) ? '' : $moyenne_test.'%').'</td><td> </td></tr>';
+		}
+		echo '</table>';
+	} else {
+		echo get_lang('NoCourse');
+	}
+}
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+
+Display :: display_footer();

+ 178 - 178
main/mySpace/session.php

@@ -1,178 +1,178 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2008 Dokeos SPRL
-	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
-
-==============================================================================
-*/
-/*
- * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
- * Somes fixes by Julio Montoya
- */
-ob_start();
-$nameTools= 'Sessions';
-// name of the language file that needs to be included
-$language_file = array ('registration', 'index', 'trad4all', 'tracking');
-$cidReset = true;
-
-require '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
-require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
-
-api_block_anonymous_users();
-
-$this_section = "session_my_space";
-
-api_block_anonymous_users();
-$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
-Display :: display_header($nameTools);
-
-// Database Table Definitions
-$tbl_course_user 		= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_sessions 			= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_course 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_course 			= Database :: get_main_table(TABLE_MAIN_COURSE);
-
-$export_csv = false;
-
-if (isset($_GET['export']) && $_GET['export'] == 'csv') {
-	$export_csv = true;
-}
-
-
-/*
-===============================================================================
-	FUNCTION
-===============================================================================
-*/
-
-function count_sessions_coached() {
-	global $nb_sessions;
-	return $nb_sessions;
-}
-
-function sort_sessions($a, $b) {
-	global $tracking_column;
-	if ($a[$tracking_column] > $b[$tracking_column]) {
-		return 1;
-	} else {
-		return -1;
-	}
-}
-
-function rsort_sessions($a, $b) {
-	global $tracking_column;
-	if ($b[$tracking_column] > $a[$tracking_column]) {
-		return 1;
-	} else {
-		return -1;
-	}
-}
-
-
-/*
-===============================================================================
-	MAIN CODE
-===============================================================================
-*/
-
-if (isset($_GET['id_coach']) && $_GET['id_coach'] != '') {
-	$id_coach = $_GET['id_coach'];
-} else {
-	$id_coach = $_user['user_id'];
-}
-
-$a_sessions = Tracking :: get_sessions_coached_by_user($id_coach);
-$nb_sessions = count($a_sessions);
-
-if ($export_csv) {
-	$csv_content = array();
-}
-
-if ($nb_sessions > 0) {
-	echo '<div align="right">
-			<a href="javascript: void(0);" onclick="javascript: window.print();"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a>
-			<a href="'.api_get_self().'?export=csv"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>
-		  </div>';
-	$table = new SortableTable('tracking', 'count_sessions_coached');
-	$table -> set_header(0, get_lang('Title'));
-	$table -> set_header(1, get_lang('Status'));
-	$table -> set_header(2, get_lang('Date'));
-	$table -> set_header(3, get_lang('Details'), false);
-
-	$all_data = array();
-	foreach ($a_sessions as $session) {
-		$row = array();
-		$row[] = $session['name'];
-		$row[] = $session['status'];
-
-		if ($session['date_start'] != '0000-00-00' && $session['date_end'] != '0000-00-00') {
-			$row[] = get_lang('From').' '.format_locale_date(get_lang('DateFormatLongWithoutDay'), strtotime($session['date_start'])).' '.get_lang('To').' '.format_locale_date(get_lang('DateFormatLongWithoutDay'), strtotime($session['date_end']));
-		} else {
-			$row[] = ' - ';
-		}
-
-		if ($export_csv) {
-			$csv_content[] = $row;
-		}
-
-		if (isset($_GET['id_coach']) && $_GET['id_coach'] != '') {
-			$row[] = '<a href="student.php?id_session='.$session['id'].'&id_coach='.$_GET['id_coach'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
-		} else {
-			$row[] = '<a href="course.php?id_session='.$session['id'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
-		}
-		$all_data[] = $row;
-	}
-
-	if (!isset($tracking_column)) {
-		$tracking_column = 0;
-	}
-
-	if ($_GET['tracking_direction'] == 'DESC') {
-		usort($all_data, 'rsort_sessions');
-	} else {
-		usort($all_data, 'sort_sessions');
-	}
-
-	if ($export_csv) {
-		usort($csv_content, 'sort_sessions');
-	}
-
-	foreach ($all_data as $row) {
-		$table -> addRow($row);
-	}
-
-	$table -> setColAttributes(3, array('align' => 'center'));
-	$table -> display();
-
-	if ($export_csv) {
-		ob_end_clean();
-		Export :: export_table_csv($csv_content, 'reporting_student_list');
-	}
-} else {
-	get_lang('NoSession');
-}
-
-/*
-==============================================================================
-	FOOTER
-==============================================================================
-*/
-
-Display::display_footer();
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos SPRL
+	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
+
+==============================================================================
+*/
+/*
+ * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
+ * Somes fixes by Julio Montoya
+ */
+ob_start();
+$nameTools= 'Sessions';
+// name of the language file that needs to be included
+$language_file = array ('registration', 'index', 'trad4all', 'tracking');
+$cidReset = true;
+
+require '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
+require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
+
+api_block_anonymous_users();
+
+$this_section = "session_my_space";
+
+api_block_anonymous_users();
+$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
+Display :: display_header($nameTools);
+
+// Database Table Definitions
+$tbl_course_user 		= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_sessions 			= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_course 			= Database :: get_main_table(TABLE_MAIN_COURSE);
+
+$export_csv = false;
+
+if (isset($_GET['export']) && $_GET['export'] == 'csv') {
+	$export_csv = true;
+}
+
+
+/*
+===============================================================================
+	FUNCTION
+===============================================================================
+*/
+
+function count_sessions_coached() {
+	global $nb_sessions;
+	return $nb_sessions;
+}
+
+function sort_sessions($a, $b) {
+	global $tracking_column;
+	if ($a[$tracking_column] > $b[$tracking_column]) {
+		return 1;
+	} else {
+		return -1;
+	}
+}
+
+function rsort_sessions($a, $b) {
+	global $tracking_column;
+	if ($b[$tracking_column] > $a[$tracking_column]) {
+		return 1;
+	} else {
+		return -1;
+	}
+}
+
+
+/*
+===============================================================================
+	MAIN CODE
+===============================================================================
+*/
+
+if (isset($_GET['id_coach']) && $_GET['id_coach'] != '') {
+	$id_coach = $_GET['id_coach'];
+} else {
+	$id_coach = $_user['user_id'];
+}
+
+$a_sessions = Tracking :: get_sessions_coached_by_user($id_coach);
+$nb_sessions = count($a_sessions);
+
+if ($export_csv) {
+	$csv_content = array();
+}
+
+if ($nb_sessions > 0) {
+	echo '<div align="right">
+			<a href="javascript: void(0);" onclick="javascript: window.print();"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a>
+			<a href="'.api_get_self().'?export=csv"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>
+		  </div>';
+	$table = new SortableTable('tracking', 'count_sessions_coached');
+	$table -> set_header(0, get_lang('Title'));
+	$table -> set_header(1, get_lang('Status'));
+	$table -> set_header(2, get_lang('Date'));
+	$table -> set_header(3, get_lang('Details'), false);
+
+	$all_data = array();
+	foreach ($a_sessions as $session) {
+		$row = array();
+		$row[] = $session['name'];
+		$row[] = $session['status'];
+
+		if ($session['date_start'] != '0000-00-00' && $session['date_end'] != '0000-00-00') {
+			$row[] = get_lang('From').' '.format_locale_date(get_lang('DateFormatLongWithoutDay'), strtotime($session['date_start'])).' '.get_lang('To').' '.format_locale_date(get_lang('DateFormatLongWithoutDay'), strtotime($session['date_end']));
+		} else {
+			$row[] = ' - ';
+		}
+
+		if ($export_csv) {
+			$csv_content[] = $row;
+		}
+
+		if (isset($_GET['id_coach']) && $_GET['id_coach'] != '') {
+			$row[] = '<a href="student.php?id_session='.$session['id'].'&id_coach='.$_GET['id_coach'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+		} else {
+			$row[] = '<a href="course.php?id_session='.$session['id'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+		}
+		$all_data[] = $row;
+	}
+
+	if (!isset($tracking_column)) {
+		$tracking_column = 0;
+	}
+
+	if ($_GET['tracking_direction'] == 'DESC') {
+		usort($all_data, 'rsort_sessions');
+	} else {
+		usort($all_data, 'sort_sessions');
+	}
+
+	if ($export_csv) {
+		usort($csv_content, 'sort_sessions');
+	}
+
+	foreach ($all_data as $row) {
+		$table -> addRow($row);
+	}
+
+	$table -> setColAttributes(3, array('align' => 'center'));
+	$table -> display();
+
+	if ($export_csv) {
+		ob_end_clean();
+		Export :: export_table_csv($csv_content, 'reporting_student_list');
+	}
+} else {
+	get_lang('NoSession');
+}
+
+/*
+==============================================================================
+	FOOTER
+==============================================================================
+*/
+
+Display::display_footer();

+ 282 - 282
main/mySpace/student.php

@@ -1,283 +1,283 @@
-<?php
-
-/*
- * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
- */
-
- // name of the language file that needs to be included
-$language_file = array ('registration', 'index', 'tracking');
-$cidReset = true;
-
-require '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
-require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
-require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-
-
-$export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
-if ($export_csv) {
-	ob_start();
-}
-$csv_content = array();
-
-if (isset($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
-	$nameTools = get_lang("CoachStudents");
-	$sql = 'SELECT lastname, firstname FROM '.Database::get_main_table(TABLE_MAIN_USER).' WHERE user_id='.intval($_GET['id_coach']);
-	$rs = Database::query($sql, __FILE__, __LINE__);
+<?php
+
+/*
+ * Created on 28 juil. 2006 by Elixir Interactive http://www.elixir-interactive.com
+ */
+
+ // name of the language file that needs to be included
+$language_file = array ('registration', 'index', 'tracking');
+$cidReset = true;
+
+require '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
+require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+
+
+$export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
+if ($export_csv) {
+	ob_start();
+}
+$csv_content = array();
+
+if (isset($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
+	$nameTools = get_lang("CoachStudents");
+	$sql = 'SELECT lastname, firstname FROM '.Database::get_main_table(TABLE_MAIN_USER).' WHERE user_id='.intval($_GET['id_coach']);
+	$rs = Database::query($sql, __FILE__, __LINE__);
 	$coach_name = api_get_person_name(Database::result($rs, 0, 1), Database::result($rs, 0, 0));
-	$title = get_lang('Probationers').' - '.$coach_name;
-} else {
-	$nameTools = get_lang("Students");
-	$title = get_lang('Probationers');
-}
-
-$this_section = "session_my_space";
-
-api_block_anonymous_users();
-
-$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
-
-if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && !isset($_GET["type"])) {
-	$interbreadcrumb[] = array ("url" => "teachers.php", "name" => get_lang('Teachers'));
-}
-
-if (isset($_GET["user_id"]) && $_GET["user_id"]!="" && isset($_GET["type"]) && $_GET["type"] == "coach") {
- 	$interbreadcrumb[] = array ("url" => "coaches.php", "name" => get_lang('Tutors'));
-}
-
-$isCoach = api_is_coach();
-
-Display :: display_header($nameTools);
-
-// Database Table Definitions
-$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_session 				= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_course 		= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-$tbl_session_rel_user 		= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
-
-/*
- ===============================================================================
- 	FUNCTION
- ===============================================================================
- */
-
-function count_student_coached() {
-	global $students;
-	return count($students);
-}
-
-function sort_users($a, $b) {
-	global $tracking_column;
-	if ($a[$tracking_column] > $b[$tracking_column]) {
-		return 1;
-	} else {
-		return -1;
-	}
-}
-
-function rsort_users($a, $b)
-{
-	global $tracking_column;
-	if ($b[$tracking_column] > $a[$tracking_column]) {
-		return 1;
-	} else {
-		return -1;
-	}
-}
-
-/*
- ===============================================================================
- 	MAIN CODE
- ===============================================================================
- */
-
-if ($isCoach || api_is_platform_admin() || $_user['status'] == DRH) {
-
-	if ($export_csv) {
-		$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-	} else {
-		$is_western_name_order = api_is_western_name_order();
-	}
-	$sort_by_first_name = api_sort_by_first_name();
-
-	echo '<div align="left" style="float:left"><h4>'.$title.'</h4></div>
-		  <div align="right">
-			<a href="javascript: void(0);" onclick="javascript: window.print();"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a>
-			<a href="'.api_get_self().'?export=csv"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>
-		  </div><div class="clear"></div>';
-
-	if (isset($_GET['id_coach'])) {
-		$coach_id = intval($_GET['id_coach']);
-	} else {
-		$coach_id = $_user['user_id'];
-	}
-
-	if (!isset($_GET['id_session'])) {
-		if ($isCoach) {
-			$courses = Tracking :: get_courses_followed_by_coach($coach_id);
-			$students = Tracking :: get_student_followed_by_coach($coach_id);
-		}
-		elseif ($_user['status'] == DRH) {
-			$students = Tracking :: get_student_followed_by_drh($_user['user_id']);
-			$courses_of_the_platform = CourseManager :: get_real_course_list();
-			foreach ($courses_of_the_platform as $course) {
-				$courses[$course['code']] = $course['code'];
-			}
-		}
-	} else {
-		$students = Tracking :: get_student_followed_by_coach_in_a_session($_GET['id_session'], $coach_id);
-	}
-
-	$tracking_column = isset($_GET['tracking_column']) ? $_GET['tracking_column'] : ($is_western_name_order xor $sort_by_first_name) ? 1 : 0;
-	$tracking_direction = isset($_GET['tracking_direction']) ? $_GET['tracking_direction'] : DESC;
-
-	if (count($students) > 0) {
-		$table = new SortableTable('tracking', 'count_student_coached', null, ($is_western_name_order xor $sort_by_first_name) ? 1 : 0);
-		if ($is_western_name_order) {
-			$table -> set_header(0, get_lang('FirstName'), true, 'align="center');
-			$table -> set_header(1, get_lang('LastName'), true, 'align="center');
-		} else {
-			$table -> set_header(0, get_lang('LastName'), true, 'align="center');
-			$table -> set_header(1, get_lang('FirstName'), true, 'align="center');
-		}
-		$table -> set_header(2, get_lang('Time'), false);
-		$table -> set_header(3, get_lang('Progress'), false);
-		$table -> set_header(4, get_lang('Score'), false);
-		$table -> set_header(5, get_lang('Student_publication'), false);
-		$table -> set_header(6, get_lang('Messages'), false);
-		$table -> set_header(7, get_lang('FirstLogin'), false);
-		$table -> set_header(8, get_lang('LatestLogin'), false);
-		$table -> set_header(9, get_lang('Details'), false);
-
-		if ($export_csv) {
-			if ($is_western_name_order) {
-				$csv_header[] = array (
-					get_lang('FirstName', ''),
-					get_lang('LastName', ''),
-					get_lang('Time', ''),
-					get_lang('Progress', ''),
-					get_lang('Score', ''),
-					get_lang('Student_publication', ''),
-					get_lang('Messages', ''),
-					get_lang('FirstLogin', ''),
-					get_lang('LatestLogin', '')
-				);
-			} else {
-				$csv_header[] = array (
-					get_lang('LastName', ''),
-					get_lang('FirstName', ''),
-					get_lang('Time', ''),
-					get_lang('Progress', ''),
-					get_lang('Score', ''),
-					get_lang('Student_publication', ''),
-					get_lang('Messages', ''),
-					get_lang('FirstLogin', ''),
-					get_lang('LatestLogin', '')
-				);
-			}
-		}
-
-	    $all_datas = array();
-		foreach ($students as $student_id) {
-			$student_data = UserManager :: get_user_info_by_id($student_id);
-			if(isset($_GET['id_session'])) {
-				$courses = Tracking :: get_course_list_in_session_from_student($student_id, $_GET['id_session']);
-			}
-
-			$avg_time_spent = $avg_student_score = $avg_student_progress = $total_assignments = $total_messages = 0;
-			$nb_courses_student = 0;
-			foreach ($courses as $course_code) {
-				if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
-					$avg_time_spent += Tracking :: get_time_spent_on_the_platform($student_id, $course_code);
-					$avg_student_score += Tracking :: get_avg_student_score($student_id, $course_code);
-					$avg_student_progress += Tracking :: get_avg_student_progress($student_id, $course_code);
-					$total_assignments += Tracking :: count_student_assignments($student_id, $course_code);
-					$total_messages += Tracking :: count_student_messages($student_id, $course_code);
-					$nb_courses_student++;
-				}
-			}
-
-			if ($nb_courses_student > 0) {
-				$avg_time_spent = $avg_time_spent / $nb_courses_student;
-				$avg_student_score = $avg_student_score / $nb_courses_student;
-				$avg_student_progress = $avg_student_progress / $nb_courses_student;
-			} else {
-				$avg_time_spent = null;
-				$avg_student_score = null;
-				$avg_student_progress = null;
-			}
-
-			$row = array();
-			if ($is_western_name_order) {
-				$row[] = $student_data['firstname'];
-				$row[] = $student_data['lastname'];
-			} else {
-				$row[] = $student_data['lastname'];
-				$row[] = $student_data['firstname'];
-			}
-			$row[] = api_time_to_hms($avg_time_spent);
-			$row[] = is_null($avg_student_progress) ? null : round($avg_student_progress, 2).'%';
-			$row[] = is_null($avg_student_score) ? null : round($avg_student_score, 2).'%';
-			$row[] = $total_assignments;
-			$row[] = $total_messages;
-
-			$string_date = Tracking :: get_last_connection_date($student_id, true);
-			$first_date = Tracking :: get_first_connection_date($student_id);
-			$row[] = $first_date;
-			$row[] = $string_date;
-
-			if ($export_csv) {
-				$csv_content[] = $row;
-			}
-
-			if (isset($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
-				$row[] = '<a href="myStudents.php?student='.$student_id.'&id_coach='.$coach_id.'&id_session='.$_GET['id_session'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
-			} else {
-				$row[] = '<a href="myStudents.php?student='.$student_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
-			}
-
-			$all_datas[] = $row;
-		}
-
-		if ($tracking_direction == 'ASC') {
-			usort($all_datas, 'rsort_users');
-		} else {
-			usort($all_datas, 'sort_users');
-		}
-
-		if ($export_csv) {
-			usort($csv_content, 'sort_users');
-			$csv_content = array_merge($csv_header, $csv_content);
-		}
-
-		foreach ($all_datas as $row) {
-			$table -> addRow($row, 'align="right"');
-		}
-		$table -> updateColAttributes(0, array('align' => 'left'));
-		$table -> updateColAttributes(1, array('align' => 'left'));
-		$table -> updateColAttributes(7, array('align' => 'left'));
-		$table -> updateColAttributes(8, array('align' => 'left'));
-		$table -> setColAttributes(9, array('align' => 'center'));
-		$table -> display();
-	} else {
-		echo get_lang('NoStudent');
-	}
-
-	// send the csv file if asked
-	if ($export_csv) {
-		ob_end_clean();
-		Export :: export_table_csv($csv_content, 'reporting_student_list');
-	}
-}
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-
-Display :: display_footer();
+	$title = get_lang('Probationers').' - '.$coach_name;
+} else {
+	$nameTools = get_lang("Students");
+	$title = get_lang('Probationers');
+}
+
+$this_section = "session_my_space";
+
+api_block_anonymous_users();
+
+$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
+
+if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && !isset($_GET["type"])) {
+	$interbreadcrumb[] = array ("url" => "teachers.php", "name" => get_lang('Teachers'));
+}
+
+if (isset($_GET["user_id"]) && $_GET["user_id"]!="" && isset($_GET["type"]) && $_GET["type"] == "coach") {
+ 	$interbreadcrumb[] = array ("url" => "coaches.php", "name" => get_lang('Tutors'));
+}
+
+$isCoach = api_is_coach();
+
+Display :: display_header($nameTools);
+
+// Database Table Definitions
+$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_session 				= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course 		= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+$tbl_session_rel_user 		= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
+
+/*
+ ===============================================================================
+ 	FUNCTION
+ ===============================================================================
+ */
+
+function count_student_coached() {
+	global $students;
+	return count($students);
+}
+
+function sort_users($a, $b) {
+	global $tracking_column;
+	if ($a[$tracking_column] > $b[$tracking_column]) {
+		return 1;
+	} else {
+		return -1;
+	}
+}
+
+function rsort_users($a, $b)
+{
+	global $tracking_column;
+	if ($b[$tracking_column] > $a[$tracking_column]) {
+		return 1;
+	} else {
+		return -1;
+	}
+}
+
+/*
+ ===============================================================================
+ 	MAIN CODE
+ ===============================================================================
+ */
+
+if ($isCoach || api_is_platform_admin() || $_user['status'] == DRH) {
+
+	if ($export_csv) {
+		$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+	} else {
+		$is_western_name_order = api_is_western_name_order();
+	}
+	$sort_by_first_name = api_sort_by_first_name();
+
+	echo '<div align="left" style="float:left"><h4>'.$title.'</h4></div>
+		  <div align="right">
+			<a href="javascript: void(0);" onclick="javascript: window.print();"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a>
+			<a href="'.api_get_self().'?export=csv"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>
+		  </div><div class="clear"></div>';
+
+	if (isset($_GET['id_coach'])) {
+		$coach_id = intval($_GET['id_coach']);
+	} else {
+		$coach_id = $_user['user_id'];
+	}
+
+	if (!isset($_GET['id_session'])) {
+		if ($isCoach) {
+			$courses = Tracking :: get_courses_followed_by_coach($coach_id);
+			$students = Tracking :: get_student_followed_by_coach($coach_id);
+		}
+		elseif ($_user['status'] == DRH) {
+			$students = Tracking :: get_student_followed_by_drh($_user['user_id']);
+			$courses_of_the_platform = CourseManager :: get_real_course_list();
+			foreach ($courses_of_the_platform as $course) {
+				$courses[$course['code']] = $course['code'];
+			}
+		}
+	} else {
+		$students = Tracking :: get_student_followed_by_coach_in_a_session($_GET['id_session'], $coach_id);
+	}
+
+	$tracking_column = isset($_GET['tracking_column']) ? $_GET['tracking_column'] : ($is_western_name_order xor $sort_by_first_name) ? 1 : 0;
+	$tracking_direction = isset($_GET['tracking_direction']) ? $_GET['tracking_direction'] : DESC;
+
+	if (count($students) > 0) {
+		$table = new SortableTable('tracking', 'count_student_coached', null, ($is_western_name_order xor $sort_by_first_name) ? 1 : 0);
+		if ($is_western_name_order) {
+			$table -> set_header(0, get_lang('FirstName'), true, 'align="center');
+			$table -> set_header(1, get_lang('LastName'), true, 'align="center');
+		} else {
+			$table -> set_header(0, get_lang('LastName'), true, 'align="center');
+			$table -> set_header(1, get_lang('FirstName'), true, 'align="center');
+		}
+		$table -> set_header(2, get_lang('Time'), false);
+		$table -> set_header(3, get_lang('Progress'), false);
+		$table -> set_header(4, get_lang('Score'), false);
+		$table -> set_header(5, get_lang('Student_publication'), false);
+		$table -> set_header(6, get_lang('Messages'), false);
+		$table -> set_header(7, get_lang('FirstLogin'), false);
+		$table -> set_header(8, get_lang('LatestLogin'), false);
+		$table -> set_header(9, get_lang('Details'), false);
+
+		if ($export_csv) {
+			if ($is_western_name_order) {
+				$csv_header[] = array (
+					get_lang('FirstName', ''),
+					get_lang('LastName', ''),
+					get_lang('Time', ''),
+					get_lang('Progress', ''),
+					get_lang('Score', ''),
+					get_lang('Student_publication', ''),
+					get_lang('Messages', ''),
+					get_lang('FirstLogin', ''),
+					get_lang('LatestLogin', '')
+				);
+			} else {
+				$csv_header[] = array (
+					get_lang('LastName', ''),
+					get_lang('FirstName', ''),
+					get_lang('Time', ''),
+					get_lang('Progress', ''),
+					get_lang('Score', ''),
+					get_lang('Student_publication', ''),
+					get_lang('Messages', ''),
+					get_lang('FirstLogin', ''),
+					get_lang('LatestLogin', '')
+				);
+			}
+		}
+
+	    $all_datas = array();
+		foreach ($students as $student_id) {
+			$student_data = UserManager :: get_user_info_by_id($student_id);
+			if(isset($_GET['id_session'])) {
+				$courses = Tracking :: get_course_list_in_session_from_student($student_id, $_GET['id_session']);
+			}
+
+			$avg_time_spent = $avg_student_score = $avg_student_progress = $total_assignments = $total_messages = 0;
+			$nb_courses_student = 0;
+			foreach ($courses as $course_code) {
+				if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
+					$avg_time_spent += Tracking :: get_time_spent_on_the_platform($student_id, $course_code);
+					$avg_student_score += Tracking :: get_avg_student_score($student_id, $course_code);
+					$avg_student_progress += Tracking :: get_avg_student_progress($student_id, $course_code);
+					$total_assignments += Tracking :: count_student_assignments($student_id, $course_code);
+					$total_messages += Tracking :: count_student_messages($student_id, $course_code);
+					$nb_courses_student++;
+				}
+			}
+
+			if ($nb_courses_student > 0) {
+				$avg_time_spent = $avg_time_spent / $nb_courses_student;
+				$avg_student_score = $avg_student_score / $nb_courses_student;
+				$avg_student_progress = $avg_student_progress / $nb_courses_student;
+			} else {
+				$avg_time_spent = null;
+				$avg_student_score = null;
+				$avg_student_progress = null;
+			}
+
+			$row = array();
+			if ($is_western_name_order) {
+				$row[] = $student_data['firstname'];
+				$row[] = $student_data['lastname'];
+			} else {
+				$row[] = $student_data['lastname'];
+				$row[] = $student_data['firstname'];
+			}
+			$row[] = api_time_to_hms($avg_time_spent);
+			$row[] = is_null($avg_student_progress) ? null : round($avg_student_progress, 2).'%';
+			$row[] = is_null($avg_student_score) ? null : round($avg_student_score, 2).'%';
+			$row[] = $total_assignments;
+			$row[] = $total_messages;
+
+			$string_date = Tracking :: get_last_connection_date($student_id, true);
+			$first_date = Tracking :: get_first_connection_date($student_id);
+			$row[] = $first_date;
+			$row[] = $string_date;
+
+			if ($export_csv) {
+				$csv_content[] = $row;
+			}
+
+			if (isset($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
+				$row[] = '<a href="myStudents.php?student='.$student_id.'&id_coach='.$coach_id.'&id_session='.$_GET['id_session'].'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+			} else {
+				$row[] = '<a href="myStudents.php?student='.$student_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+			}
+
+			$all_datas[] = $row;
+		}
+
+		if ($tracking_direction == 'ASC') {
+			usort($all_datas, 'rsort_users');
+		} else {
+			usort($all_datas, 'sort_users');
+		}
+
+		if ($export_csv) {
+			usort($csv_content, 'sort_users');
+			$csv_content = array_merge($csv_header, $csv_content);
+		}
+
+		foreach ($all_datas as $row) {
+			$table -> addRow($row, 'align="right"');
+		}
+		$table -> updateColAttributes(0, array('align' => 'left'));
+		$table -> updateColAttributes(1, array('align' => 'left'));
+		$table -> updateColAttributes(7, array('align' => 'left'));
+		$table -> updateColAttributes(8, array('align' => 'left'));
+		$table -> setColAttributes(9, array('align' => 'center'));
+		$table -> display();
+	} else {
+		echo get_lang('NoStudent');
+	}
+
+	// send the csv file if asked
+	if ($export_csv) {
+		ob_end_clean();
+		Export :: export_table_csv($csv_content, 'reporting_student_list');
+	}
+}
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+
+Display :: display_footer();

+ 136 - 136
main/mySpace/teachers.php

@@ -1,136 +1,136 @@
-<?php
-
-/*
- * Created on 18 October 2006 by Elixir Interactive http://www.elixir-interactive.com
- */
-
-ob_start();
-
-// names of the language file that needs to be included
-$language_file = array ('registration', 'index', 'trad4all', 'tracking', 'admin');
-$cidReset = true;
-
-require_once '../inc/global.inc.php';
-require_once api_get_path(SYS_CODE_PATH).'mySpace/myspace.lib.php';
-
-$this_section = "session_my_space";
-
-$nameTools = get_lang('Teachers');
-
-api_block_anonymous_users();
-$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
-Display :: display_header($nameTools);
-
-api_display_tool_title($nameTools);
-
-// Database Table Definitions
-$tbl_course 			= Database :: get_main_table(TABLE_MAIN_COURSE);
-$tbl_user 				= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_session 			= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_course 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_rel_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
-
-
-/**
- * MAIN PART
- */
-
-if (isset($_POST['export'])) {
-	$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-} else {
-	$is_western_name_order = api_is_western_name_order();
-}
-$sort_by_first_name = api_sort_by_first_name();
-
-$order_clause = $sort_by_first_name ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
-if (isset($_GET["teacher_id"]) && $_GET["teacher_id"] != 0) {
-	$teacher_id = $_GET["teacher_id"];
-	$sql_formateurs = "SELECT user_id,lastname,firstname,email
-		FROM $tbl_user
-		WHERE user_id='$teacher_id'".$order_clause;
-} else {
-	$sql_formateurs = "SELECT user_id,lastname,firstname,email
-		FROM $tbl_user
-		WHERE status = 1".$order_clause;
-}
-
-$result_formateurs = Database::query($sql_formateurs, __FILE__, __LINE__);
-
-if ($is_western_name_order) {
-	echo '<table class="data_table"><tr><th>'.get_lang('FirstName').'</th><th>'.get_lang('LastName').'</th><th>'.get_lang('Email').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
-} else {
-	echo '<table class="data_table"><tr><th>'.get_lang('LastName').'</th><th>'.get_lang('FirstName').'</th><th>'.get_lang('Email').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
-}
-
-if ($is_western_name_order) {
-	$header[] = get_lang('FirstName', '');
-	$header[] = get_lang('LastName', '');
-} else {
-	$header[] = get_lang('LastName', '');
-	$header[] = get_lang('FirstName', '');
-}
-$header[] = get_lang('Email', '');
-
-$data = array();
-
-if (Database::num_rows($result_formateurs) > 0) {
-
-	$i = 1;
-	while ($formateurs = Database::fetch_array($result_formateurs)) {
-
-		$user_id = $formateurs["user_id"];
-		$lastname = $formateurs["lastname"];
-		$firstname = $formateurs["firstname"];
-		$email = $formateurs["email"];
-
-		if ($i % 2 == 0) {
-			$css_class = "row_odd";
-
-			if ($i % 20 == 0 && $i != 0) {
-				if ($is_western_name_order) {
-					echo '<tr><th>'.get_lang('FirstName').'</th><th>'.get_lang('LastName').'</th><th>'.get_lang('Email').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
-				} else {
-					echo '<tr><th>'.get_lang('LastName').'</th><th>'.get_lang('FirstName').'</th><th>'.get_lang('Email').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
-				}
-			}
-		} else {
-			$css_class = "row_even";
-		}
-
-		$i++;
-
-		if ($is_western_name_order) {
-			$data[$user_id]["firstname"] = $firstname;
-			$data[$user_id]["lastname"] = $lastname;
-		} else {
-			$data[$user_id]["lastname"] = $lastname;
-			$data[$user_id]["firstname"] = $firstname;
-		}
-		$data[$user_id]["email"] = $email;
-
-		if ($is_western_name_order) {
-			echo '<tr class="'.$css_class.'"><td>'.$firstname.'</td><td>'.$lastname.'</td><td><a href="mailto:'.$email.'">'.$email.'</a></td><td><a href="course.php?user_id='.$user_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td><td><a href="student.php?user_id='.$user_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td></tr>';
-		} else {
-			echo '<tr class="'.$css_class.'"><td>'.$lastname.'</td><td>'.$firstname.'</td><td><a href="mailto:'.$email.'">'.$email.'</a></td><td><a href="course.php?user_id='.$user_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td><td><a href="student.php?user_id='.$user_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td></tr>';
-		}
-	}
-} else {
-	// No results
-	echo '<tr><td colspan="5" "align=center">'.get_lang("NoResults").'</td></tr>';
-}
-echo '</table>';
-
-if (isset($_POST['export'])) {
-	export_csv($header, $data, 'teachers.csv');
-}
-
-echo "<br /><br />";
-echo "<form method='post' action='teachers.php'><input type='submit' name='export' value='".get_lang('exportExcel')."'/><form>";
-
-/*
-==============================================================================
-	FOOTER
-==============================================================================
-*/
-
-Display::display_footer();
+<?php
+
+/*
+ * Created on 18 October 2006 by Elixir Interactive http://www.elixir-interactive.com
+ */
+
+ob_start();
+
+// names of the language file that needs to be included
+$language_file = array ('registration', 'index', 'trad4all', 'tracking', 'admin');
+$cidReset = true;
+
+require_once '../inc/global.inc.php';
+require_once api_get_path(SYS_CODE_PATH).'mySpace/myspace.lib.php';
+
+$this_section = "session_my_space";
+
+$nameTools = get_lang('Teachers');
+
+api_block_anonymous_users();
+$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
+Display :: display_header($nameTools);
+
+api_display_tool_title($nameTools);
+
+// Database Table Definitions
+$tbl_course 			= Database :: get_main_table(TABLE_MAIN_COURSE);
+$tbl_user 				= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_session 			= Database :: get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session_rel_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
+
+
+/**
+ * MAIN PART
+ */
+
+if (isset($_POST['export'])) {
+	$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+} else {
+	$is_western_name_order = api_is_western_name_order();
+}
+$sort_by_first_name = api_sort_by_first_name();
+
+$order_clause = $sort_by_first_name ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
+if (isset($_GET["teacher_id"]) && $_GET["teacher_id"] != 0) {
+	$teacher_id = $_GET["teacher_id"];
+	$sql_formateurs = "SELECT user_id,lastname,firstname,email
+		FROM $tbl_user
+		WHERE user_id='$teacher_id'".$order_clause;
+} else {
+	$sql_formateurs = "SELECT user_id,lastname,firstname,email
+		FROM $tbl_user
+		WHERE status = 1".$order_clause;
+}
+
+$result_formateurs = Database::query($sql_formateurs, __FILE__, __LINE__);
+
+if ($is_western_name_order) {
+	echo '<table class="data_table"><tr><th>'.get_lang('FirstName').'</th><th>'.get_lang('LastName').'</th><th>'.get_lang('Email').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
+} else {
+	echo '<table class="data_table"><tr><th>'.get_lang('LastName').'</th><th>'.get_lang('FirstName').'</th><th>'.get_lang('Email').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
+}
+
+if ($is_western_name_order) {
+	$header[] = get_lang('FirstName', '');
+	$header[] = get_lang('LastName', '');
+} else {
+	$header[] = get_lang('LastName', '');
+	$header[] = get_lang('FirstName', '');
+}
+$header[] = get_lang('Email', '');
+
+$data = array();
+
+if (Database::num_rows($result_formateurs) > 0) {
+
+	$i = 1;
+	while ($formateurs = Database::fetch_array($result_formateurs)) {
+
+		$user_id = $formateurs["user_id"];
+		$lastname = $formateurs["lastname"];
+		$firstname = $formateurs["firstname"];
+		$email = $formateurs["email"];
+
+		if ($i % 2 == 0) {
+			$css_class = "row_odd";
+
+			if ($i % 20 == 0 && $i != 0) {
+				if ($is_western_name_order) {
+					echo '<tr><th>'.get_lang('FirstName').'</th><th>'.get_lang('LastName').'</th><th>'.get_lang('Email').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
+				} else {
+					echo '<tr><th>'.get_lang('LastName').'</th><th>'.get_lang('FirstName').'</th><th>'.get_lang('Email').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
+				}
+			}
+		} else {
+			$css_class = "row_even";
+		}
+
+		$i++;
+
+		if ($is_western_name_order) {
+			$data[$user_id]["firstname"] = $firstname;
+			$data[$user_id]["lastname"] = $lastname;
+		} else {
+			$data[$user_id]["lastname"] = $lastname;
+			$data[$user_id]["firstname"] = $firstname;
+		}
+		$data[$user_id]["email"] = $email;
+
+		if ($is_western_name_order) {
+			echo '<tr class="'.$css_class.'"><td>'.$firstname.'</td><td>'.$lastname.'</td><td><a href="mailto:'.$email.'">'.$email.'</a></td><td><a href="course.php?user_id='.$user_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td><td><a href="student.php?user_id='.$user_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td></tr>';
+		} else {
+			echo '<tr class="'.$css_class.'"><td>'.$lastname.'</td><td>'.$firstname.'</td><td><a href="mailto:'.$email.'">'.$email.'</a></td><td><a href="course.php?user_id='.$user_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td><td><a href="student.php?user_id='.$user_id.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td></tr>';
+		}
+	}
+} else {
+	// No results
+	echo '<tr><td colspan="5" "align=center">'.get_lang("NoResults").'</td></tr>';
+}
+echo '</table>';
+
+if (isset($_POST['export'])) {
+	export_csv($header, $data, 'teachers.csv');
+}
+
+echo "<br /><br />";
+echo "<form method='post' action='teachers.php'><input type='submit' name='export' value='".get_lang('exportExcel')."'/><form>";
+
+/*
+==============================================================================
+	FOOTER
+==============================================================================
+*/
+
+Display::display_footer();

+ 15 - 15
main/newscorm/README.txt

@@ -1,15 +1,15 @@
-To use the new SCORM tool, first run the scorm_update_db.php from where it is in the (new)scorm directory.
-This will update all courses databases by adding 4 tables (lp, lp_item, lp_view and lp_item_view) and add an lp_type table in the main database.
-If you had installed a development version of the newscorm tool, it is a good idea to also run scorm_update_db_alter.php to make sure the latest changes are in.
-
-Then go to the database and modify the 'tool' table in each course to add the 'newscorm' tool (copy the tool row from 'learnpath' and change the name). Make sure to select newscorm/lp_list.php as a starting point for this tool (although index.php should work as well).
-You can do this by using the scorm_migrate_hometools.php script now.
-
-If you are using one of these scripts, it is vital you check by yourself that all the courses have been migrated accurately. For example, you will need to check that all links to learning paths in the course homepage are pointing towards the newscorm/ directory, not scorm/ or learnpath/.
-
-Go to one of your courses' homepage and try the new SCORM tool as you would normally do with the old SCORM tool.
-Please note this DOES NOT manage the Dokeos learnpaths yet.
-
-For more detailed development information, please read the corresponding Wiki page: http://www.dokeos.com/wiki/index.php/SCORM_tool_redesign
-
-For any problem contact me directly at <yannick.warnier@dokeos.com>
+To use the new SCORM tool, first run the scorm_update_db.php from where it is in the (new)scorm directory.
+This will update all courses databases by adding 4 tables (lp, lp_item, lp_view and lp_item_view) and add an lp_type table in the main database.
+If you had installed a development version of the newscorm tool, it is a good idea to also run scorm_update_db_alter.php to make sure the latest changes are in.
+
+Then go to the database and modify the 'tool' table in each course to add the 'newscorm' tool (copy the tool row from 'learnpath' and change the name). Make sure to select newscorm/lp_list.php as a starting point for this tool (although index.php should work as well).
+You can do this by using the scorm_migrate_hometools.php script now.
+
+If you are using one of these scripts, it is vital you check by yourself that all the courses have been migrated accurately. For example, you will need to check that all links to learning paths in the course homepage are pointing towards the newscorm/ directory, not scorm/ or learnpath/.
+
+Go to one of your courses' homepage and try the new SCORM tool as you would normally do with the old SCORM tool.
+Please note this DOES NOT manage the Dokeos learnpaths yet.
+
+For more detailed development information, please read the corresponding Wiki page: http://www.dokeos.com/wiki/index.php/SCORM_tool_redesign
+
+For any problem contact me directly at <yannick.warnier@dokeos.com>

+ 951 - 951
main/newscorm/aicc.class.php

@@ -1,980 +1,980 @@
-<?php //$id:$
-/**
- * Defines the AICC class, which is meant to contain the aicc items (nuclear elements)
- * @package dokeos.learnpath
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
- * Defines the "aicc" child of class "learnpath"
- * @package dokeos.learnpath.aicc
- */
-require_once('aiccItem.class.php');
-//require_once('aiccMetadata.class.php');
-//require_once('aiccOrganization.class.php');
-require_once('aiccResource.class.php');
-require_once('aiccBlock.class.php');
-class aicc extends learnpath {
-
-	var $config = array();
-	var $config_basename = '';  //the configuration files might be multiple and might have
-								//funny names. We need to keep the name of that file while we
-								//install the content.
-	var $config_files = array();
-	var $config_exts = array(
-			'crs'=>0, //Course description file (mandatory)
-			'au' =>0, //Assignable Unit file (mandatory)
-			'des'=>0, //Descriptor file (mandatory)
-			'cst'=>0, //Course structure file (mandatory)
-			'ore'=>0, //Objectives relationshops file (optional)
-			'pre'=>0, //Prerequisites file (optional)
-			'cmp'=>0  //Completion Requirements file (optional)
-	);
-	var $aulist = array();
-	var $au_order_list = array();
-	var $au_order_list_new_id = array();
-	var $deslist = array();
-	var $cstlist = array();
-	var $orelist = array();
-
-	var $subdir = ''; //path between the scorm/ directory and the config files e.g. maritime_nav/maritime_nav. This is the path that will be used in the lp_path when importing a package
-	var $zipname = ''; //keeps the zipfile safe for the object's life so that we can use it if no title avail
-	var $lastzipnameindex = 0; //keeps an index of the number of uses of the zipname so far
-	var $config_encoding = 'ISO-8859-1';
-	var $debug = 0;
-	/**
-	 * Class constructor. Based on the parent constructor.
-	 * @param	string	Course code
-	 * @param	integer	Learnpath ID in DB
-	 * @param	integer	User ID
-	 */
-    function aicc($course_code=null,$resource_id=null,$user_id=null) {
-    	if($this->debug>0){error_log('In aicc::aicc()',0);}
-    	if(!empty($course_code) and !empty($resource_id) and !empty($user_id))
-    	{
-    		parent::learnpath($course_code, $resource_id, $user_id);
-    	}else{
-    		//do nothing but still build the aicc object
-    	}
-    }
-    /**
-     * Opens a resource
-     * @param	integer	Database ID of the resource
-     */
-    function open($id)
-    {
-    	if($this->debug>0){error_log('In aicc::open()',0);}
-    	// redefine parent method
-    }
-    /**
-     * Parses a set of AICC config files and puts everything into the $config array
-     * @param	string	Path to the config files dir on the system. If not defined, uses the base path of the course's scorm dir
+<?php //$id:$
+/**
+ * Defines the AICC class, which is meant to contain the aicc items (nuclear elements)
+ * @package dokeos.learnpath
+ * @author	Yannick Warnier <ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * Defines the "aicc" child of class "learnpath"
+ * @package dokeos.learnpath.aicc
+ */
+require_once('aiccItem.class.php');
+//require_once('aiccMetadata.class.php');
+//require_once('aiccOrganization.class.php');
+require_once('aiccResource.class.php');
+require_once('aiccBlock.class.php');
+class aicc extends learnpath {
+
+	var $config = array();
+	var $config_basename = '';  //the configuration files might be multiple and might have
+								//funny names. We need to keep the name of that file while we
+								//install the content.
+	var $config_files = array();
+	var $config_exts = array(
+			'crs'=>0, //Course description file (mandatory)
+			'au' =>0, //Assignable Unit file (mandatory)
+			'des'=>0, //Descriptor file (mandatory)
+			'cst'=>0, //Course structure file (mandatory)
+			'ore'=>0, //Objectives relationshops file (optional)
+			'pre'=>0, //Prerequisites file (optional)
+			'cmp'=>0  //Completion Requirements file (optional)
+	);
+	var $aulist = array();
+	var $au_order_list = array();
+	var $au_order_list_new_id = array();
+	var $deslist = array();
+	var $cstlist = array();
+	var $orelist = array();
+
+	var $subdir = ''; //path between the scorm/ directory and the config files e.g. maritime_nav/maritime_nav. This is the path that will be used in the lp_path when importing a package
+	var $zipname = ''; //keeps the zipfile safe for the object's life so that we can use it if no title avail
+	var $lastzipnameindex = 0; //keeps an index of the number of uses of the zipname so far
+	var $config_encoding = 'ISO-8859-1';
+	var $debug = 0;
+	/**
+	 * Class constructor. Based on the parent constructor.
+	 * @param	string	Course code
+	 * @param	integer	Learnpath ID in DB
+	 * @param	integer	User ID
+	 */
+    function aicc($course_code=null,$resource_id=null,$user_id=null) {
+    	if($this->debug>0){error_log('In aicc::aicc()',0);}
+    	if(!empty($course_code) and !empty($resource_id) and !empty($user_id))
+    	{
+    		parent::learnpath($course_code, $resource_id, $user_id);
+    	}else{
+    		//do nothing but still build the aicc object
+    	}
+    }
+    /**
+     * Opens a resource
+     * @param	integer	Database ID of the resource
+     */
+    function open($id)
+    {
+    	if($this->debug>0){error_log('In aicc::open()',0);}
+    	// redefine parent method
+    }
+    /**
+     * Parses a set of AICC config files and puts everything into the $config array
+     * @param	string	Path to the config files dir on the system. If not defined, uses the base path of the course's scorm dir
 	 * @return	array	Structured array representing the config files' contents
-     */
-     function parse_config_files($dir='')
-     {
-    	if($this->debug>0){error_log('New LP - In aicc::parse_config_files('.$dir.')',0);}
-		if(empty($dir)){
-     		//get the path of the AICC config files dir
-			$dir = $this->subdir;
-     	}
-     	if(is_dir($dir) and is_readable($dir))
-     	{
-     		// Now go through all the config files one by one and parse everything into
-     		// AICC objects.
-
-     		// The basename for the config files is stored in $this->config_basename
-
-     		// Parse the Course Description File (.crs) - ini-type
-     		$crs_file = $dir.'/'.$this->config_files['crs'];
-     		$crs_params = $this->parse_ini_file_quotes_safe($crs_file);
-     		//echo '<pre>crs:'.print_r($crs_params,true).'</pre>';
-	    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$crs_file.' has been parsed',0);}
-
-			//CRS distribute crs params into the aicc object
-			if(!empty($crs_params['course']['course_creator'])){
-				$this->course_creator = mysql_real_escape_string($crs_params['course']['course_creator']);
-			}
-			if(!empty($crs_params['course']['course_id'])){
-				$this->course_id = mysql_real_escape_string($crs_params['course']['course_id']);
-			}
-			if(!empty($crs_params['course']['course_system'])){
-				$this->course_system = $crs_params['course']['course_system'];
-			}
-			if(!empty($crs_params['course']['course_title'])){
-				$this->course_title = mysql_real_escape_string($crs_params['course']['course_title']);
-			}
-			if(!empty($crs_params['course']['course_level'])){
-				$this->course_level = $crs_params['course']['course_level'];
-			}
-			if(!empty($crs_params['course']['max_fields_cst'])){
-				$this->course_max_fields_cst = $crs_params['course']['max_fields_cst'];
-			}
-			if(!empty($crs_params['course']['max_fields_ort'])){
-				$this->course_max_fields_ort = $crs_params['course']['max_fields_ort'];
-			}
-			if(!empty($crs_params['course']['total_aus'])){
-				$this->course_total_aus = $crs_params['course']['total_aus'];
-			}
-			if(!empty($crs_params['course']['total_blocks'])){
-				$this->course_total_blocks = $crs_params['course']['total_blocks'];
-			}
-			if(!empty($crs_params['course']['total_objectives'])){
-				$this->course_total_objectives = $crs_params['course']['total_objectives'];
-			}
-			if(!empty($crs_params['course']['total_complex_objectives'])){
-				$this->course_total_complex_objectives = $crs_params['course']['total_complex_objectives'];
-			}
-			if(!empty($crs_params['course']['version'])){
-				$this->course_version = $crs_params['course']['version'];
-			}
-			if(!empty($crs_params['course_description'])){
-				$this->course_description = mysql_real_escape_string($crs_params['course_description']);
-			}
-
-     		// Parse the Descriptor File (.des) - csv-type
-     		$des_file = $dir.'/'.$this->config_files['des'];
-    		$des_params = $this->parse_csv_file($des_file);
-     		//echo '<pre>des:'.print_r($des_params,true).'</pre>';
-	    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$des_file.' has been parsed',0);}
-			//distribute des params into the aicc object
-			foreach($des_params as $des){
-				//one AU in AICC is equivalent to one SCO in SCORM (scormItem class)
-				$oDes = new aiccResource('config',$des);
+     */
+     function parse_config_files($dir='')
+     {
+    	if($this->debug>0){error_log('New LP - In aicc::parse_config_files('.$dir.')',0);}
+		if(empty($dir)){
+     		//get the path of the AICC config files dir
+			$dir = $this->subdir;
+     	}
+     	if(is_dir($dir) and is_readable($dir))
+     	{
+     		// Now go through all the config files one by one and parse everything into
+     		// AICC objects.
+
+     		// The basename for the config files is stored in $this->config_basename
+
+     		// Parse the Course Description File (.crs) - ini-type
+     		$crs_file = $dir.'/'.$this->config_files['crs'];
+     		$crs_params = $this->parse_ini_file_quotes_safe($crs_file);
+     		//echo '<pre>crs:'.print_r($crs_params,true).'</pre>';
+	    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$crs_file.' has been parsed',0);}
+
+			//CRS distribute crs params into the aicc object
+			if(!empty($crs_params['course']['course_creator'])){
+				$this->course_creator = mysql_real_escape_string($crs_params['course']['course_creator']);
+			}
+			if(!empty($crs_params['course']['course_id'])){
+				$this->course_id = mysql_real_escape_string($crs_params['course']['course_id']);
+			}
+			if(!empty($crs_params['course']['course_system'])){
+				$this->course_system = $crs_params['course']['course_system'];
+			}
+			if(!empty($crs_params['course']['course_title'])){
+				$this->course_title = mysql_real_escape_string($crs_params['course']['course_title']);
+			}
+			if(!empty($crs_params['course']['course_level'])){
+				$this->course_level = $crs_params['course']['course_level'];
+			}
+			if(!empty($crs_params['course']['max_fields_cst'])){
+				$this->course_max_fields_cst = $crs_params['course']['max_fields_cst'];
+			}
+			if(!empty($crs_params['course']['max_fields_ort'])){
+				$this->course_max_fields_ort = $crs_params['course']['max_fields_ort'];
+			}
+			if(!empty($crs_params['course']['total_aus'])){
+				$this->course_total_aus = $crs_params['course']['total_aus'];
+			}
+			if(!empty($crs_params['course']['total_blocks'])){
+				$this->course_total_blocks = $crs_params['course']['total_blocks'];
+			}
+			if(!empty($crs_params['course']['total_objectives'])){
+				$this->course_total_objectives = $crs_params['course']['total_objectives'];
+			}
+			if(!empty($crs_params['course']['total_complex_objectives'])){
+				$this->course_total_complex_objectives = $crs_params['course']['total_complex_objectives'];
+			}
+			if(!empty($crs_params['course']['version'])){
+				$this->course_version = $crs_params['course']['version'];
+			}
+			if(!empty($crs_params['course_description'])){
+				$this->course_description = mysql_real_escape_string($crs_params['course_description']);
+			}
+
+     		// Parse the Descriptor File (.des) - csv-type
+     		$des_file = $dir.'/'.$this->config_files['des'];
+    		$des_params = $this->parse_csv_file($des_file);
+     		//echo '<pre>des:'.print_r($des_params,true).'</pre>';
+	    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$des_file.' has been parsed',0);}
+			//distribute des params into the aicc object
+			foreach($des_params as $des){
+				//one AU in AICC is equivalent to one SCO in SCORM (scormItem class)
+				$oDes = new aiccResource('config',$des);
 				$this->deslist[$oDes->identifier] = $oDes;
-			}
-
-     		// Parse the Assignable Unit File (.au) - csv-type
-     		$au_file = $dir.'/'.$this->config_files['au'];
-     		$au_params = $this->parse_csv_file($au_file);
-     		//echo '<pre>au:'.print_r($au_params,true).'</pre>';
-	    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$au_file.' has been parsed',0);}
-			//distribute au params into the aicc object
-			foreach($au_params as $au){
-				$oAu = new aiccItem('config',$au);
-				$this->aulist[$oAu->identifier] = $oAu;
-				$this->au_order_list[] = $oAu->identifier;
-			}
-
-     		// Parse the Course Structure File (.cst) - csv-type
-     		$cst_file = $dir.'/'.$this->config_files['cst'];
-     		$cst_params = $this->parse_csv_file($cst_file,',','"',true);
-     		//echo '<pre>cst:'.print_r($cst_params,true).'</pre>';
-	    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$cst_file.' has been parsed',0);}
-			//distribute cst params into the aicc object
-			foreach($cst_params as $cst){
-				$oCst = new aiccBlock('config',$cst);
-				$this->cstlist[$oCst->identifier] = $oCst;
-			}
-
-     		// Parse the Objectives Relationships File (.ore) - csv-type - if exists
-     		//TODO @TODO implement these objectives. For now they're just parsed
-     		if(!empty($this->config_files['ore'])){
-	     		$ore_file = $dir.'/'.$this->config_files['ore'];
-	     		$ore_params = $this->parse_csv_file($ore_file,',','"',true);
-	     		//echo '<pre>ore:'.print_r($ore_params,true).'</pre>';
-		    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$ore_file.' has been parsed',0);}
-				//distribute ore params into the aicc object
-				foreach($ore_params as $ore){
-					$oOre = new aiccObjective('config',$ore);
-					$this->orelist[$oOre->identifier] = $oOre;
-				}
-     		}
-
-     		// Parse the Prerequisites File (.pre) - csv-type - if exists
-     		if(!empty($this->config_files['pre'])){
-	     		$pre_file = $dir.'/'.$this->config_files['pre'];
-	     		$pre_params = $this->parse_csv_file($pre_file);
-	     		//echo '<pre>pre:'.print_r($pre_params,true).'</pre>';
-		    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$pre_file.' has been parsed',0);}
-				//distribute pre params into the aicc object
-				foreach($pre_params as $pre){
-					//place a constraint on the corresponding block or AU
-					if(in_array(strtolower($pre['structure_element']),array_keys($this->cstlist))){
-						//if this references a block element
-						$this->cstlist[strtolower($pre['structure_element'])]->prereq_string = strtolower($pre['prerequisite']);
-					}
-					if(in_array(strtolower($pre['structure_element']),array_keys($this->aulist))){
-						//if this references a block element
-						$this->aulist[strtolower($pre['structure_element'])]->prereq_string = strtolower($pre['prerequisite']);
-					}
-				}
+			}
+
+     		// Parse the Assignable Unit File (.au) - csv-type
+     		$au_file = $dir.'/'.$this->config_files['au'];
+     		$au_params = $this->parse_csv_file($au_file);
+     		//echo '<pre>au:'.print_r($au_params,true).'</pre>';
+	    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$au_file.' has been parsed',0);}
+			//distribute au params into the aicc object
+			foreach($au_params as $au){
+				$oAu = new aiccItem('config',$au);
+				$this->aulist[$oAu->identifier] = $oAu;
+				$this->au_order_list[] = $oAu->identifier;
+			}
+
+     		// Parse the Course Structure File (.cst) - csv-type
+     		$cst_file = $dir.'/'.$this->config_files['cst'];
+     		$cst_params = $this->parse_csv_file($cst_file,',','"',true);
+     		//echo '<pre>cst:'.print_r($cst_params,true).'</pre>';
+	    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$cst_file.' has been parsed',0);}
+			//distribute cst params into the aicc object
+			foreach($cst_params as $cst){
+				$oCst = new aiccBlock('config',$cst);
+				$this->cstlist[$oCst->identifier] = $oCst;
+			}
+
+     		// Parse the Objectives Relationships File (.ore) - csv-type - if exists
+     		//TODO @TODO implement these objectives. For now they're just parsed
+     		if(!empty($this->config_files['ore'])){
+	     		$ore_file = $dir.'/'.$this->config_files['ore'];
+	     		$ore_params = $this->parse_csv_file($ore_file,',','"',true);
+	     		//echo '<pre>ore:'.print_r($ore_params,true).'</pre>';
+		    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$ore_file.' has been parsed',0);}
+				//distribute ore params into the aicc object
+				foreach($ore_params as $ore){
+					$oOre = new aiccObjective('config',$ore);
+					$this->orelist[$oOre->identifier] = $oOre;
+				}
      		}
-
-     		// Parse the Completion Requirements File (.cmp) - csv-type - if exists
-     		//TODO @TODO implement this set of requirements (needs database changes)
-     		if(!empty($this->config_files['cmp'])){
-	     		$cmp_file = $dir.'/'.$this->config_files['cmp'];
-	     		$cmp_params = $this->parse_csv_file($cmp_file);
-	     		//echo '<pre>cmp:'.print_r($cmp_params,true).'</pre>';
-		    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$cmp_file.' has been parsed',0);}
-				//distribute cmp params into the aicc object
-				foreach($cmp_params as $cmp){
-					//$oCmp = new aiccCompletionRequirements('config',$cmp);
-					//$this->cmplist[$oCmp->identifier] =& $oCmp;
-				}
+
+     		// Parse the Prerequisites File (.pre) - csv-type - if exists
+     		if(!empty($this->config_files['pre'])){
+	     		$pre_file = $dir.'/'.$this->config_files['pre'];
+	     		$pre_params = $this->parse_csv_file($pre_file);
+	     		//echo '<pre>pre:'.print_r($pre_params,true).'</pre>';
+		    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$pre_file.' has been parsed',0);}
+				//distribute pre params into the aicc object
+				foreach($pre_params as $pre){
+					//place a constraint on the corresponding block or AU
+					if(in_array(strtolower($pre['structure_element']),array_keys($this->cstlist))){
+						//if this references a block element
+						$this->cstlist[strtolower($pre['structure_element'])]->prereq_string = strtolower($pre['prerequisite']);
+					}
+					if(in_array(strtolower($pre['structure_element']),array_keys($this->aulist))){
+						//if this references a block element
+						$this->aulist[strtolower($pre['structure_element'])]->prereq_string = strtolower($pre['prerequisite']);
+					}
+				}
+     		}
+
+     		// Parse the Completion Requirements File (.cmp) - csv-type - if exists
+     		//TODO @TODO implement this set of requirements (needs database changes)
+     		if(!empty($this->config_files['cmp'])){
+	     		$cmp_file = $dir.'/'.$this->config_files['cmp'];
+	     		$cmp_params = $this->parse_csv_file($cmp_file);
+	     		//echo '<pre>cmp:'.print_r($cmp_params,true).'</pre>';
+		    	if($this->debug>1){error_log('New LP - In aicc::parse_config_files() - '.$cmp_file.' has been parsed',0);}
+				//distribute cmp params into the aicc object
+				foreach($cmp_params as $cmp){
+					//$oCmp = new aiccCompletionRequirements('config',$cmp);
+					//$this->cmplist[$oCmp->identifier] =& $oCmp;
+				}
      		}
-     	}
-     	return $this->config;
-     }
-     /**
-      * Import the aicc object (as a result from the parse_config_files function) into the database structure
+     	}
+     	return $this->config;
+     }
+     /**
+      * Import the aicc object (as a result from the parse_config_files function) into the database structure
       * @param	string	Unique course code
-      * @return	bool	Returns -1 on error
-      */
-     function import_aicc($course_code){
-     	if($this->debug>0){error_log('New LP - In aicc::import_aicc('.$course_code.')',0);}
-     	//get table names
-     	$new_lp = 'lp';
-     	$new_lp_item = 'lp_item';
-
-     	//The previous method wasn't safe to get the database name, so do it manually with the course_code
-     	$sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE code='$course_code'";
-        $res = Database::query($sql,__FILE__,__LINE__);
-        if(Database::num_rows($res)<1){ error_log('New LP - Database for '.$course_code.' not found '.__FILE__.' '.__LINE__,0);return -1;}
-        $row = Database::fetch_array($res);
-        $dbname = Database::get_course_table_prefix().$row['db_name'].Database::get_database_glue();
-
-		$new_lp = Database::get_course_table(TABLE_LP_MAIN);
-		$new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-    	$get_max = "SELECT MAX(display_order) FROM $new_lp";
-    	$res_max = Database::query($get_max);
-    	if(Database::num_rows($res_max)<1){
-    		$dsp = 1;
-    	}else{
-    		$row = Database::fetch_array($res_max);
-    		$dsp = $row[0]+1;
-    	}
-
-		$this->config_encoding = "ISO-8859-1";
-
-		$sql = "INSERT INTO $new_lp " .
-				"(lp_type, name, ref, description, " .
-				"path, force_commit, default_view_mod, default_encoding, " .
-				"js_lib, content_maker,display_order)" .
-				"VALUES " .
-				"(3,'".$this->course_title."', '".$this->course_id."','".$this->course_description."'," .
-				"'".$this->subdir."', 0, 'embedded', '".$this->config_encoding."'," .
-				"'aicc_api.php','".$this->course_creator."',$dsp)";
-		if($this->debug>2){error_log('New LP - In import_aicc(), inserting path: '. $sql,0);}
-		$res = Database::query($sql);
-		$lp_id = Database::get_last_insert_id();
-		$this->lp_id = $lp_id;
-		api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'LearnpathAdded',api_get_user_id());
-		api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'visible',api_get_user_id());
-
-		$previous = 0;
-		foreach($this->aulist as $identifier => $dummy)
-		{
-			$oAu =& $this->aulist[$identifier];
-			//echo "Item ".$oAu->identifier;
-			$field_add = '';
-			$value_add = '';
-			if(!empty($oAu->masteryscore)){
-				$field_add = 'mastery_score, ';
-				$value_add = $oAu->masteryscore.',';
-			}
-			$title = $oAu->identifier;
-			if(is_object($this->deslist[$identifier])){
-				$title = $this->deslist[$identifier]->title;
-			}
-			$path = $oAu->path;
-			//$max_score = $oAu->max_score //TODO check if special constraint exists for this item
-			//$min_score = $oAu->min_score //TODO check if special constraint exists for this item
-			$parent = 0; //TODO deal with parent
-			$previous = 0;
-			$prereq = $oAu->prereq_string;
-			//$previous = (!empty($this->au_order_list_new_id[x])?$this->au_order_list_new_id[x]:0); //TODO deal with previous
-			$sql_item = "INSERT INTO $new_lp_item " .
-					"(lp_id,item_type,ref,title," .
-					"path,min_score,max_score, $field_add" .
-					"parent_item_id,previous_item_id,next_item_id," .
-					"prerequisite,display_order) " .
-					"VALUES " .
-					"($lp_id, 'au','".$oAu->identifier."','".$title."'," .
-					"'$path',0,100, $value_add" .
-					"$parent, $previous, 0, " .
-					"'$prereq', 0" .
-					")";
-			$res_item = Database::query($sql_item);
-			if($this->debug>1){error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : '.mysql_error(),0);}
-			$item_id = Database::get_last_insert_id();
-			//now update previous item to change next_item_id
-			if($previous != 0){
-				$upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE id = $previous";
-				$upd_res = Database::query($upd);
-				//update previous item id
-			}
-			$previous = $item_id;
-		}
-     }
- 	 /**
-	  * Intermediate to import_package only to allow import from local zip files
+      * @return	bool	Returns -1 on error
+      */
+     function import_aicc($course_code){
+     	if($this->debug>0){error_log('New LP - In aicc::import_aicc('.$course_code.')',0);}
+     	//get table names
+     	$new_lp = 'lp';
+     	$new_lp_item = 'lp_item';
+
+     	//The previous method wasn't safe to get the database name, so do it manually with the course_code
+     	$sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE code='$course_code'";
+        $res = Database::query($sql,__FILE__,__LINE__);
+        if(Database::num_rows($res)<1){ error_log('New LP - Database for '.$course_code.' not found '.__FILE__.' '.__LINE__,0);return -1;}
+        $row = Database::fetch_array($res);
+        $dbname = Database::get_course_table_prefix().$row['db_name'].Database::get_database_glue();
+
+		$new_lp = Database::get_course_table(TABLE_LP_MAIN);
+		$new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+    	$get_max = "SELECT MAX(display_order) FROM $new_lp";
+    	$res_max = Database::query($get_max);
+    	if(Database::num_rows($res_max)<1){
+    		$dsp = 1;
+    	}else{
+    		$row = Database::fetch_array($res_max);
+    		$dsp = $row[0]+1;
+    	}
+
+		$this->config_encoding = "ISO-8859-1";
+
+		$sql = "INSERT INTO $new_lp " .
+				"(lp_type, name, ref, description, " .
+				"path, force_commit, default_view_mod, default_encoding, " .
+				"js_lib, content_maker,display_order)" .
+				"VALUES " .
+				"(3,'".$this->course_title."', '".$this->course_id."','".$this->course_description."'," .
+				"'".$this->subdir."', 0, 'embedded', '".$this->config_encoding."'," .
+				"'aicc_api.php','".$this->course_creator."',$dsp)";
+		if($this->debug>2){error_log('New LP - In import_aicc(), inserting path: '. $sql,0);}
+		$res = Database::query($sql);
+		$lp_id = Database::get_last_insert_id();
+		$this->lp_id = $lp_id;
+		api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'LearnpathAdded',api_get_user_id());
+		api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'visible',api_get_user_id());
+
+		$previous = 0;
+		foreach($this->aulist as $identifier => $dummy)
+		{
+			$oAu =& $this->aulist[$identifier];
+			//echo "Item ".$oAu->identifier;
+			$field_add = '';
+			$value_add = '';
+			if(!empty($oAu->masteryscore)){
+				$field_add = 'mastery_score, ';
+				$value_add = $oAu->masteryscore.',';
+			}
+			$title = $oAu->identifier;
+			if(is_object($this->deslist[$identifier])){
+				$title = $this->deslist[$identifier]->title;
+			}
+			$path = $oAu->path;
+			//$max_score = $oAu->max_score //TODO check if special constraint exists for this item
+			//$min_score = $oAu->min_score //TODO check if special constraint exists for this item
+			$parent = 0; //TODO deal with parent
+			$previous = 0;
+			$prereq = $oAu->prereq_string;
+			//$previous = (!empty($this->au_order_list_new_id[x])?$this->au_order_list_new_id[x]:0); //TODO deal with previous
+			$sql_item = "INSERT INTO $new_lp_item " .
+					"(lp_id,item_type,ref,title," .
+					"path,min_score,max_score, $field_add" .
+					"parent_item_id,previous_item_id,next_item_id," .
+					"prerequisite,display_order) " .
+					"VALUES " .
+					"($lp_id, 'au','".$oAu->identifier."','".$title."'," .
+					"'$path',0,100, $value_add" .
+					"$parent, $previous, 0, " .
+					"'$prereq', 0" .
+					")";
+			$res_item = Database::query($sql_item);
+			if($this->debug>1){error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : '.mysql_error(),0);}
+			$item_id = Database::get_last_insert_id();
+			//now update previous item to change next_item_id
+			if($previous != 0){
+				$upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE id = $previous";
+				$upd_res = Database::query($upd);
+				//update previous item id
+			}
+			$previous = $item_id;
+		}
+     }
+ 	 /**
+	  * Intermediate to import_package only to allow import from local zip files
 	  * @param	string	Path to the zip file, from the dokeos sys root
-	  * @param	string	Current path (optional)
-	  * @return string	Absolute path to the AICC description files or empty string on error
-	  */
-	 function import_local_package($file_path,$current_dir='')
-	 {
-	 	//todo prepare info as given by the $_FILES[''] vector
-	 	$file_info = array();
-	 	$file_info['tmp_name'] = $file_path;
-	 	$file_info['name'] = basename($file_path);
-	 	//call the normal import_package function
+	  * @param	string	Current path (optional)
+	  * @return string	Absolute path to the AICC description files or empty string on error
+	  */
+	 function import_local_package($file_path,$current_dir='')
+	 {
+	 	//todo prepare info as given by the $_FILES[''] vector
+	 	$file_info = array();
+	 	$file_info['tmp_name'] = $file_path;
+	 	$file_info['name'] = basename($file_path);
+	 	//call the normal import_package function
 	 	return $this->import_package($file_info,$current_dir);
-	 }
-     /**
-      * Imports a zip file (presumably AICC) into the Dokeos structure
-      * @param	string	Zip file info as given by $_FILES['userFile']
-      * @return	string	Absolute path to the AICC config files directory or empty string on error
-      */
-     function import_package($zip_file_info,$current_dir = '')
-     {
-     	if($this->debug>0){error_log('In aicc::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method',0);}
-     	//ini_set('error_log','E_ALL');
-     	$maxFilledSpace = 1000000000;
-     	$zip_file_path = $zip_file_info['tmp_name'];
-     	$zip_file_name = $zip_file_info['name'];
-
-     	if($this->debug>0){error_log('New LP - aicc::import_package() - Zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name,0);}
-     	$course_rel_dir  = api_get_course_path().'/scorm'; //scorm dir web path starting from /courses
-		$course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; //absolute system path for this course
-		$current_dir = replace_dangerous_char(trim($current_dir),'strict'); //current dir we are in, inside scorm/
-     	if($this->debug>0){error_log('New LP - aicc::import_package() - Current_dir = '.$current_dir,0);}
-
- 		//$uploaded_filename = $_FILES['userFile']['name'];
-		//get name of the zip file without the extension
-		if($this->debug>0){error_log('New LP - aicc::import_package() - Received zip file name: '.$zip_file_path,0);}
-		$file_info = pathinfo($zip_file_name);
-		$filename = $file_info['basename'];
-		$extension = $file_info['extension'];
-		$file_base_name = str_replace('.'.$extension,'',$filename); //filename without its extension
-		$this->zipname = $file_base_name; //save for later in case we don't have a title
-
-		if($this->debug>0){error_log('New LP - aicc::import_package() - Base file name is : '.$file_base_name,0);}
-		$new_dir = replace_dangerous_char(trim($file_base_name),'strict');
-		$this->subdir = $new_dir;
-		if($this->debug>0){error_log('New LP - aicc::import_package() - Subdir is first set to : '.$this->subdir,0);}
+	 }
+     /**
+      * Imports a zip file (presumably AICC) into the Dokeos structure
+      * @param	string	Zip file info as given by $_FILES['userFile']
+      * @return	string	Absolute path to the AICC config files directory or empty string on error
+      */
+     function import_package($zip_file_info,$current_dir = '')
+     {
+     	if($this->debug>0){error_log('In aicc::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method',0);}
+     	//ini_set('error_log','E_ALL');
+     	$maxFilledSpace = 1000000000;
+     	$zip_file_path = $zip_file_info['tmp_name'];
+     	$zip_file_name = $zip_file_info['name'];
+
+     	if($this->debug>0){error_log('New LP - aicc::import_package() - Zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name,0);}
+     	$course_rel_dir  = api_get_course_path().'/scorm'; //scorm dir web path starting from /courses
+		$course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; //absolute system path for this course
+		$current_dir = replace_dangerous_char(trim($current_dir),'strict'); //current dir we are in, inside scorm/
+     	if($this->debug>0){error_log('New LP - aicc::import_package() - Current_dir = '.$current_dir,0);}
+
+ 		//$uploaded_filename = $_FILES['userFile']['name'];
+		//get name of the zip file without the extension
+		if($this->debug>0){error_log('New LP - aicc::import_package() - Received zip file name: '.$zip_file_path,0);}
+		$file_info = pathinfo($zip_file_name);
+		$filename = $file_info['basename'];
+		$extension = $file_info['extension'];
+		$file_base_name = str_replace('.'.$extension,'',$filename); //filename without its extension
+		$this->zipname = $file_base_name; //save for later in case we don't have a title
+
+		if($this->debug>0){error_log('New LP - aicc::import_package() - Base file name is : '.$file_base_name,0);}
+		$new_dir = replace_dangerous_char(trim($file_base_name),'strict');
+		$this->subdir = $new_dir;
+		if($this->debug>0){error_log('New LP - aicc::import_package() - Subdir is first set to : '.$this->subdir,0);}
 
 /*
-		if( check_name_exist($course_sys_dir.$current_dir."/".$new_dir) )
-		{
-			$dialogBox = get_lang('FileExists');
-			$stopping_error = true;
-		}
-*/
-		$zipFile = new pclZip($zip_file_path);
-
-		// Check the zip content (real size and file extension)
-
-		$zipContentArray = $zipFile->listContent();
-
-		$package_type=''; //the type of the package. Should be 'aicc' after the next few lines
-		$package = ''; //the basename of the config files (if 'courses.crs' => 'courses')
-		$at_root = false; //check if the config files are at zip root
-		$config_dir = ''; //the directory in which the config files are. May remain empty
-		$files_found = array();
-		$subdir_isset = false;
-		//the following loop should be stopped as soon as we found the right config files (.crs, .au, .des and .cst)
-		foreach($zipContentArray as $thisContent)
-		{
-			if ( preg_match('~.(php.*|phtml)$~i', $thisContent['filename']) )
-			{
-				//if a php file is found, do not authorize (security risk)
+		if( check_name_exist($course_sys_dir.$current_dir."/".$new_dir) )
+		{
+			$dialogBox = get_lang('FileExists');
+			$stopping_error = true;
+		}
+*/
+		$zipFile = new pclZip($zip_file_path);
+
+		// Check the zip content (real size and file extension)
+
+		$zipContentArray = $zipFile->listContent();
+
+		$package_type=''; //the type of the package. Should be 'aicc' after the next few lines
+		$package = ''; //the basename of the config files (if 'courses.crs' => 'courses')
+		$at_root = false; //check if the config files are at zip root
+		$config_dir = ''; //the directory in which the config files are. May remain empty
+		$files_found = array();
+		$subdir_isset = false;
+		//the following loop should be stopped as soon as we found the right config files (.crs, .au, .des and .cst)
+		foreach($zipContentArray as $thisContent)
+		{
+			if ( preg_match('~.(php.*|phtml)$~i', $thisContent['filename']) )
+			{
+				//if a php file is found, do not authorize (security risk)
 				if($this->debug>1){error_log('New LP - aicc::import_package() - Found unauthorized file: '.$thisContent['filename'],0);}
-				return api_failure::set_failure('php_file_in_zip_file');
-			}elseif(preg_match('?.*/aicc/$?',$thisContent['filename'])){
-				//if a directory named 'aicc' is found, package type = aicc, but continue
+				return api_failure::set_failure('php_file_in_zip_file');
+			}elseif(preg_match('?.*/aicc/$?',$thisContent['filename'])){
+				//if a directory named 'aicc' is found, package type = aicc, but continue
 				//because we need to find the right AICC files
 				if($this->debug>1){error_log('New LP - aicc::import_package() - Found aicc directory: '.$thisContent['filename'],0);}
-				$package_type = 'aicc';
-			}else{
-				//else, look for one of the files we're searching for (something.crs case insensitive)
-				$res = array();
-				if(preg_match('?^(.*)\.(crs|au|des|cst|ore|pre|cmp)$?i',$thisContent['filename'],$res))
-				{
-					if($this->debug>1){error_log('New LP - aicc::import_package() - Found AICC config file: '.$thisContent['filename'].'. Now splitting: '.$res[1].' and '.$res[2],0);}
-					if($thisContent['filename'] == basename($thisContent['filename'])){
-						if($this->debug>2){error_log('New LP - aicc::import_package() - '.$thisContent['filename'].' is at root level',0);}
-						$at_root = true;
-						if(!is_array($files_found[$res[1]])){
-							$files_found[$res[1]] = $this->config_exts; //initialise list of expected extensions (defined in class definition)
-						}
-						$files_found[$res[1]][strtolower($res[2])] = $thisContent['filename'];
-						$subdir_isset = true;
-					}else{
-						if(!$subdir_isset){
-							if(preg_match('?^.*/aicc$?i',dirname($thisContent['filename']))){
-								//echo "Cutting subdir<br/>";
+				$package_type = 'aicc';
+			}else{
+				//else, look for one of the files we're searching for (something.crs case insensitive)
+				$res = array();
+				if(preg_match('?^(.*)\.(crs|au|des|cst|ore|pre|cmp)$?i',$thisContent['filename'],$res))
+				{
+					if($this->debug>1){error_log('New LP - aicc::import_package() - Found AICC config file: '.$thisContent['filename'].'. Now splitting: '.$res[1].' and '.$res[2],0);}
+					if($thisContent['filename'] == basename($thisContent['filename'])){
+						if($this->debug>2){error_log('New LP - aicc::import_package() - '.$thisContent['filename'].' is at root level',0);}
+						$at_root = true;
+						if(!is_array($files_found[$res[1]])){
+							$files_found[$res[1]] = $this->config_exts; //initialise list of expected extensions (defined in class definition)
+						}
+						$files_found[$res[1]][strtolower($res[2])] = $thisContent['filename'];
+						$subdir_isset = true;
+					}else{
+						if(!$subdir_isset){
+							if(preg_match('?^.*/aicc$?i',dirname($thisContent['filename']))){
+								//echo "Cutting subdir<br/>";
 								$this->subdir .= '/'.substr(dirname($thisContent['filename']),0,-5);
-							}else{
-								//echo "Not cutting subdir<br/>";
-								$this->subdir .= '/'.dirname($thisContent['filename']);
-							}
-							$subdir_isset = true;
-						}
-						if($this->debug>2){error_log('New LP - aicc::import_package() - '.$thisContent['filename'].' is not at root level - recording subdir '.$this->subdir,0);}
-						$config_dir = dirname($thisContent['filename']); //just the relative directory inside scorm/
-						if(!is_array($files_found[basename($res[1])])){
-							$files_found[basename($res[1])] = $this->config_exts;
-						}
-						$files_found[basename($res[1])][strtolower($res[2])] = basename($thisContent['filename']);
-					}
-					$package_type = 'aicc';
-				}else{
+							}else{
+								//echo "Not cutting subdir<br/>";
+								$this->subdir .= '/'.dirname($thisContent['filename']);
+							}
+							$subdir_isset = true;
+						}
+						if($this->debug>2){error_log('New LP - aicc::import_package() - '.$thisContent['filename'].' is not at root level - recording subdir '.$this->subdir,0);}
+						$config_dir = dirname($thisContent['filename']); //just the relative directory inside scorm/
+						if(!is_array($files_found[basename($res[1])])){
+							$files_found[basename($res[1])] = $this->config_exts;
+						}
+						$files_found[basename($res[1])][strtolower($res[2])] = basename($thisContent['filename']);
+					}
+					$package_type = 'aicc';
+				}else{
 					if($this->debug>3){error_log('New LP - aicc::import_package() - File '.$thisContent['filename'].' didnt match any check',0);}
-				}
-			}
-			$realFileSize += $thisContent['size'];
-		}
-		if($this->debug>2){error_log('New LP - aicc::import_package() - $files_found: '.print_r($files_found,true),0);}
-		if($this->debug>1){error_log('New LP - aicc::import_package() - Package type is now '.$package_type,0);}
-		$mandatory = false;
-		foreach($files_found as $file_name => $file_exts){
-			$temp = (
-				!empty($files_found[$file_name]['crs'])
+				}
+			}
+			$realFileSize += $thisContent['size'];
+		}
+		if($this->debug>2){error_log('New LP - aicc::import_package() - $files_found: '.print_r($files_found,true),0);}
+		if($this->debug>1){error_log('New LP - aicc::import_package() - Package type is now '.$package_type,0);}
+		$mandatory = false;
+		foreach($files_found as $file_name => $file_exts){
+			$temp = (
+				!empty($files_found[$file_name]['crs'])
 				AND !empty($files_found[$file_name]['au'])
-				AND !empty($files_found[$file_name]['des'])
-				AND !empty($files_found[$file_name]['cst'])
-			);
-			if($temp){
-				if($this->debug>1){error_log('New LP - aicc::import_package() - Found all config files for '.$file_name,0);}
-				$mandatory = true;
-				$package = $file_name;
-				//store base config file name for reuse in parse_config_files()
-				$this->config_basename = $file_name;
-				//store filenames for reuse in parse_config_files()
-				$this->config_files = $files_found[$file_name];
-				//get out, we only want one config files set
-				break;
-			}
-		}
-
-		if($package_type== '' OR $mandatory!=true)
-		 // && defined('CHECK_FOR_AICC') && CHECK_FOR_AICC)
-		{
-			return api_failure::set_failure('not_aicc_content');
-		}
-
-		if (! enough_size($realFileSize, $course_sys_dir, $maxFilledSpace) )
-		{
-			return api_failure::set_failure('not_enough_space');
-		}
-
-		// it happens on Linux that $new_dir sometimes doesn't start with '/'
-		if($new_dir[0] != '/')
-		{
-			$new_dir='/'.$new_dir;
-		}
-		//cut trailing slash
-		if($new_dir[strlen($new_dir)-1] == '/')
-		{
-			$new_dir=substr($new_dir,0,-1);
-		}
-
-		/*
-		--------------------------------------
-			Uncompressing phase
-		--------------------------------------
-		*/
-		/*
-			We need to process each individual file in the zip archive to
-			- add it to the database
-			- parse & change relative html links
-			- make sure the filenames are secure (filter funny characters or php extensions)
-		*/
-		if(is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir))
-		{
-			// PHP method - slower...
-			if($this->debug>=1){error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir,0);}
-			$saved_dir = getcwd();
-			chdir($course_sys_dir.$new_dir);
-			$unzippingState = $zipFile->extract();
-			for($j=0;$j<count($unzippingState);$j++)
-			{
-				$state=$unzippingState[$j];
-
-				//TODO fix relative links in html files (?)
-				$extension = strrchr($state["stored_filename"], ".");
-				//if($this->debug>1){error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'],0);}
-
-			}
-
-			if(!empty($new_dir))
-			{
-				$new_dir = $new_dir.'/';
-			}
-			//rename files, for example with \\ in it
-			if($dir=@opendir($course_sys_dir.$new_dir))
-			{
-				if($this->debug==1){error_log('New LP - Opened dir '.$course_sys_dir.$new_dir,0);}
-				while($file=readdir($dir))
-				{
-					if($file != '.' && $file != '..')
-					{
-						$filetype="file";
-
-						if(is_dir($course_sys_dir.$new_dir.$file)) $filetype="folder";
-
-						//TODO RENAMING FILES CAN BE VERY DANGEROUS AICC-WISE, avoid that as much as possible!
-						//$safe_file=replace_dangerous_char($file,'strict');
-						$find_str = array('\\','.php','.phtml');
-						$repl_str = array('/', '.txt','.txt');
-						$safe_file = str_replace($find_str,$repl_str,$file);
-
-						if($safe_file != $file){
-							//@rename($course_sys_dir.$new_dir,$course_sys_dir.'/'.$safe_file);
-							$mydir = dirname($course_sys_dir.$new_dir.$safe_file);
-							if(!is_dir($mydir)){
-								$mysubdirs = split('/',$mydir);
-								$mybasedir = '/';
-								foreach($mysubdirs as $mysubdir){
-									if(!empty($mysubdir)){
-										$mybasedir = $mybasedir.$mysubdir.'/';
-										if(!is_dir($mybasedir)){
-											@mkdir($mybasedir);
-											if($this->debug==1){error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.',0);}
-										}
-									}
-								}
-							}
-							@rename($course_sys_dir.$new_dir.$file,$course_sys_dir.$new_dir.$safe_file);
-							if($this->debug==1){error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file,0);}
+				AND !empty($files_found[$file_name]['des'])
+				AND !empty($files_found[$file_name]['cst'])
+			);
+			if($temp){
+				if($this->debug>1){error_log('New LP - aicc::import_package() - Found all config files for '.$file_name,0);}
+				$mandatory = true;
+				$package = $file_name;
+				//store base config file name for reuse in parse_config_files()
+				$this->config_basename = $file_name;
+				//store filenames for reuse in parse_config_files()
+				$this->config_files = $files_found[$file_name];
+				//get out, we only want one config files set
+				break;
+			}
+		}
+
+		if($package_type== '' OR $mandatory!=true)
+		 // && defined('CHECK_FOR_AICC') && CHECK_FOR_AICC)
+		{
+			return api_failure::set_failure('not_aicc_content');
+		}
+
+		if (! enough_size($realFileSize, $course_sys_dir, $maxFilledSpace) )
+		{
+			return api_failure::set_failure('not_enough_space');
+		}
+
+		// it happens on Linux that $new_dir sometimes doesn't start with '/'
+		if($new_dir[0] != '/')
+		{
+			$new_dir='/'.$new_dir;
+		}
+		//cut trailing slash
+		if($new_dir[strlen($new_dir)-1] == '/')
+		{
+			$new_dir=substr($new_dir,0,-1);
+		}
+
+		/*
+		--------------------------------------
+			Uncompressing phase
+		--------------------------------------
+		*/
+		/*
+			We need to process each individual file in the zip archive to
+			- add it to the database
+			- parse & change relative html links
+			- make sure the filenames are secure (filter funny characters or php extensions)
+		*/
+		if(is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir))
+		{
+			// PHP method - slower...
+			if($this->debug>=1){error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir,0);}
+			$saved_dir = getcwd();
+			chdir($course_sys_dir.$new_dir);
+			$unzippingState = $zipFile->extract();
+			for($j=0;$j<count($unzippingState);$j++)
+			{
+				$state=$unzippingState[$j];
+
+				//TODO fix relative links in html files (?)
+				$extension = strrchr($state["stored_filename"], ".");
+				//if($this->debug>1){error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'],0);}
+
+			}
+
+			if(!empty($new_dir))
+			{
+				$new_dir = $new_dir.'/';
+			}
+			//rename files, for example with \\ in it
+			if($dir=@opendir($course_sys_dir.$new_dir))
+			{
+				if($this->debug==1){error_log('New LP - Opened dir '.$course_sys_dir.$new_dir,0);}
+				while($file=readdir($dir))
+				{
+					if($file != '.' && $file != '..')
+					{
+						$filetype="file";
+
+						if(is_dir($course_sys_dir.$new_dir.$file)) $filetype="folder";
+
+						//TODO RENAMING FILES CAN BE VERY DANGEROUS AICC-WISE, avoid that as much as possible!
+						//$safe_file=replace_dangerous_char($file,'strict');
+						$find_str = array('\\','.php','.phtml');
+						$repl_str = array('/', '.txt','.txt');
+						$safe_file = str_replace($find_str,$repl_str,$file);
+
+						if($safe_file != $file){
+							//@rename($course_sys_dir.$new_dir,$course_sys_dir.'/'.$safe_file);
+							$mydir = dirname($course_sys_dir.$new_dir.$safe_file);
+							if(!is_dir($mydir)){
+								$mysubdirs = split('/',$mydir);
+								$mybasedir = '/';
+								foreach($mysubdirs as $mysubdir){
+									if(!empty($mysubdir)){
+										$mybasedir = $mybasedir.$mysubdir.'/';
+										if(!is_dir($mybasedir)){
+											@mkdir($mybasedir);
+											if($this->debug==1){error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.',0);}
+										}
+									}
+								}
+							}
+							@rename($course_sys_dir.$new_dir.$file,$course_sys_dir.$new_dir.$safe_file);
+							if($this->debug==1){error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file,0);}
 						}
-						//set_default_settings($course_sys_dir,$safe_file,$filetype);
-					}
-				}
-
-				closedir($dir);
-				chdir($saved_dir);
-			}
-		}else{
-			return '';
-		}
-		return $course_sys_dir.$new_dir.$config_dir;
-	}
-	/**
-	 * Sets the proximity setting in the database
-	 * @param	string	Proximity setting
-	 */
-	 function set_proximity($proxy=''){
-		if($this->debug>0){error_log('In aicc::set_proximity('.$proxy.') method',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
-
-	 /**
-	 * Sets the theme setting in the database
-	 * @param	string	Theme setting
-	 */
-	 function set_theme($theme=''){
-		if($this->debug>0){error_log('In aicc::set_theme('.$theme.') method',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
-
-	 /**
-	 * Sets the image LP in the database
-	 * @param	string	Theme setting
-	 */
-	 function set_preview_image($preview_image=''){
-		if($this->debug>0){error_log('In aicc::set_preview_image('.$preview_image.') method',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET preview_image = '$preview_image' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
-
-		/**
-	 * Sets the Author LP in the database
-	 * @param	string	Theme setting
-	 */
-	 function set_author($author=''){
-		if($this->debug>0){error_log('In aicc::set_author('.$author.') method',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET author = '$author' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
-
-
-
-	/**
-	 * Sets the content maker setting in the database
-	 * @param	string	Proximity setting
-	 */
-	 function set_maker($maker=''){
-		if($this->debug>0){error_log('In aicc::set_maker method('.$maker.')',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
-	 /**
-	  * Exports the current AICC object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
-	  * @param	integer	Learnpath ID (optional, taken from object context if not defined)
-	  */
-	  function export_zip($lp_id=null){
-		if($this->debug>0){error_log('In aicc::export_zip method('.$lp_id.')',0);}
-	 	if(empty($lp_id)){
-			if(!is_object($this))
-			{
-				return false;
-			}
-			else{
-				$id = $this->get_id();
-				if(empty($id)){
-					return false;
-				}
-	 			else{
-	 				$lp_id = $this->get_id();
-	 			}
-			}
-	 	}
-	 	//error_log('New LP - in export_zip()',0);
-	 	//zip everything that is in the corresponding scorm dir
-	 	//write the zip file somewhere (might be too big to return)
-		require_once (api_get_path(LIBRARY_PATH)."fileUpload.lib.php");
-		require_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
-		require_once (api_get_path(LIBRARY_PATH)."document.lib.php");
-		require_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
-		require_once ("learnpath_functions.inc.php");
-		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-		$_course = Database::get_course_info(api_get_course_id());
-
-		$sql = "SELECT * FROM $tbl_lp WHERE id=".$lp_id;
-		$result = Database::query($sql, __FILE__, __LINE__);
-		$row = mysql_fetch_array($result);
-		$LPname = $row['path'];
-		$list = split('/',$LPname);
-		$LPnamesafe = $list[0];
-		//$zipfoldername = '/tmp';
-		//$zipfoldername = '../../courses/'.$_course['directory']."/temp/".$LPnamesafe;
-		$zipfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/temp/".$LPnamesafe;
-		$scormfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/scorm/".$LPnamesafe;
-		$zipfilename = $zipfoldername."/".$LPnamesafe.".zip";
+						//set_default_settings($course_sys_dir,$safe_file,$filetype);
+					}
+				}
+
+				closedir($dir);
+				chdir($saved_dir);
+			}
+		}else{
+			return '';
+		}
+		return $course_sys_dir.$new_dir.$config_dir;
+	}
+	/**
+	 * Sets the proximity setting in the database
+	 * @param	string	Proximity setting
+	 */
+	 function set_proximity($proxy=''){
+		if($this->debug>0){error_log('In aicc::set_proximity('.$proxy.') method',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
+
+	 /**
+	 * Sets the theme setting in the database
+	 * @param	string	Theme setting
+	 */
+	 function set_theme($theme=''){
+		if($this->debug>0){error_log('In aicc::set_theme('.$theme.') method',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
+
+	 /**
+	 * Sets the image LP in the database
+	 * @param	string	Theme setting
+	 */
+	 function set_preview_image($preview_image=''){
+		if($this->debug>0){error_log('In aicc::set_preview_image('.$preview_image.') method',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET preview_image = '$preview_image' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
+
+		/**
+	 * Sets the Author LP in the database
+	 * @param	string	Theme setting
+	 */
+	 function set_author($author=''){
+		if($this->debug>0){error_log('In aicc::set_author('.$author.') method',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET author = '$author' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
+
+
+
+	/**
+	 * Sets the content maker setting in the database
+	 * @param	string	Proximity setting
+	 */
+	 function set_maker($maker=''){
+		if($this->debug>0){error_log('In aicc::set_maker method('.$maker.')',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
+	 /**
+	  * Exports the current AICC object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
+	  * @param	integer	Learnpath ID (optional, taken from object context if not defined)
+	  */
+	  function export_zip($lp_id=null){
+		if($this->debug>0){error_log('In aicc::export_zip method('.$lp_id.')',0);}
+	 	if(empty($lp_id)){
+			if(!is_object($this))
+			{
+				return false;
+			}
+			else{
+				$id = $this->get_id();
+				if(empty($id)){
+					return false;
+				}
+	 			else{
+	 				$lp_id = $this->get_id();
+	 			}
+			}
+	 	}
+	 	//error_log('New LP - in export_zip()',0);
+	 	//zip everything that is in the corresponding scorm dir
+	 	//write the zip file somewhere (might be too big to return)
+		require_once (api_get_path(LIBRARY_PATH)."fileUpload.lib.php");
+		require_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
+		require_once (api_get_path(LIBRARY_PATH)."document.lib.php");
+		require_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
+		require_once ("learnpath_functions.inc.php");
+		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+		$_course = Database::get_course_info(api_get_course_id());
+
+		$sql = "SELECT * FROM $tbl_lp WHERE id=".$lp_id;
+		$result = Database::query($sql, __FILE__, __LINE__);
+		$row = mysql_fetch_array($result);
+		$LPname = $row['path'];
+		$list = split('/',$LPname);
+		$LPnamesafe = $list[0];
+		//$zipfoldername = '/tmp';
+		//$zipfoldername = '../../courses/'.$_course['directory']."/temp/".$LPnamesafe;
+		$zipfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/temp/".$LPnamesafe;
+		$scormfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/scorm/".$LPnamesafe;
+		$zipfilename = $zipfoldername."/".$LPnamesafe.".zip";
 
 		//Get a temporary dir for creating the zip file
 
-		//error_log('New LP - cleaning dir '.$zipfoldername,0);
-		deldir($zipfoldername); //make sure the temp dir is cleared
-		$res = mkdir($zipfoldername);
-		//error_log('New LP - made dir '.$zipfoldername,0);
-
-		//create zipfile of given directory
-		$zip_folder = new PclZip($zipfilename);
-		$zip_folder->create($scormfoldername.'/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername.'/');
-
-		//$zipfilename = '/var/www/dokeos-comp/courses/TEST2/scorm/example_document.html';
-		//this file sending implies removing the default mime-type from php.ini
-		//DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.".zip");
-		DocumentManager :: file_send_for_download($zipfilename, true);
-
-		// Delete the temporary zip file and directory in fileManage.lib.php
-		my_delete($zipfilename);
-		my_delete($zipfoldername);
-
-		return true;
-	}
-	/**
-	  * Gets a resource's path if available, otherwise return empty string
-	  * @param	string	Resource ID as used in resource array
-	  * @return string	The resource's path as declared in config file course.crs
-	  */
-	  function get_res_path($id){
-		if($this->debug>0){error_log('In aicc::get_res_path('.$id.') method',0);}
-	  	$path = '';
-	  	if(isset($this->resources[$id])){
-			$oRes =& $this->resources[$id];
-			$path = @$oRes->get_path();
-		}
-		return $path;
-	  }
-	 /**
-	  * Gets a resource's type if available, otherwise return empty string
-	  * @param	string	Resource ID as used in resource array
-	  * @return string	The resource's type as declared in the assignable unit (.au) file
-	  */
-	  function get_res_type($id){
-		if($this->debug>0){error_log('In aicc::get_res_type('.$id.') method',0);}
-	  	$type = '';
-		if(isset($this->resources[$id])){
-			$oRes =& $this->resources[$id];
-			$temptype = $oRes->get_scorm_type();
-			if(!empty($temptype)){
-				$type = $temptype;
-			}
-		}
-		return $type;
-	  }
-	  /**
-	   * Gets the default organisation's title
-	   * @return	string	The organization's title
-	   */
-	  function get_title(){
-		if($this->debug>0){error_log('In aicc::get_title() method',0);}
-	  	$title = '';
-	  	if(isset($this->config['organizations']['default'])){
-	  		$title = $this->organizations[$this->config['organizations']['default']]->get_name();
-	  	}elseif(count($this->organizations)==1){
-	  		//this will only get one title but so we don't need to know the index
-	  		foreach($this->organizations as $id => $value){
-	  			$title = $this->organizations[$id]->get_name();
-	  			break;
-	  		}
-	  	}
-	  	return $title;
-	  }
-	  /**
-	   * //TODO @TODO implement this function to restore items data from a set of AICC config files,
-	   * updating the existing table... This will prove very useful in case initial data
-	   * from config files were not imported well enough
-	   */
-	  function reimport_aicc(){
-		if($this->debug>0){error_log('In aicc::reimport_aicc() method',0);}
-	  	//query current items list
-	  	//get the identifiers
-	  	//parse the config files
-	  	//match both
-	  	//update DB accordingly
-	  	return true;
-	  }
-	  /**
-	   * Static function to parse AICC ini files.
-	   * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file())
-	   * @param	string	File path
-	   * @return	array	Structured array
-	   */
-		function parse_ini_file_quotes_safe($f)
-		{
-			$null = "";
-			$r=$null;
-			$sec=$null;
-			$f=@file($f);
-			for ($i=0;$i<@count($f);$i++)
-			{
-				$newsec=0;
-				$w=@trim($f[$i]);
-				if ($w)
-				{
-					if ((!$r) or ($sec))
-					{
+		//error_log('New LP - cleaning dir '.$zipfoldername,0);
+		deldir($zipfoldername); //make sure the temp dir is cleared
+		$res = mkdir($zipfoldername);
+		//error_log('New LP - made dir '.$zipfoldername,0);
+
+		//create zipfile of given directory
+		$zip_folder = new PclZip($zipfilename);
+		$zip_folder->create($scormfoldername.'/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername.'/');
+
+		//$zipfilename = '/var/www/dokeos-comp/courses/TEST2/scorm/example_document.html';
+		//this file sending implies removing the default mime-type from php.ini
+		//DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.".zip");
+		DocumentManager :: file_send_for_download($zipfilename, true);
+
+		// Delete the temporary zip file and directory in fileManage.lib.php
+		my_delete($zipfilename);
+		my_delete($zipfoldername);
+
+		return true;
+	}
+	/**
+	  * Gets a resource's path if available, otherwise return empty string
+	  * @param	string	Resource ID as used in resource array
+	  * @return string	The resource's path as declared in config file course.crs
+	  */
+	  function get_res_path($id){
+		if($this->debug>0){error_log('In aicc::get_res_path('.$id.') method',0);}
+	  	$path = '';
+	  	if(isset($this->resources[$id])){
+			$oRes =& $this->resources[$id];
+			$path = @$oRes->get_path();
+		}
+		return $path;
+	  }
+	 /**
+	  * Gets a resource's type if available, otherwise return empty string
+	  * @param	string	Resource ID as used in resource array
+	  * @return string	The resource's type as declared in the assignable unit (.au) file
+	  */
+	  function get_res_type($id){
+		if($this->debug>0){error_log('In aicc::get_res_type('.$id.') method',0);}
+	  	$type = '';
+		if(isset($this->resources[$id])){
+			$oRes =& $this->resources[$id];
+			$temptype = $oRes->get_scorm_type();
+			if(!empty($temptype)){
+				$type = $temptype;
+			}
+		}
+		return $type;
+	  }
+	  /**
+	   * Gets the default organisation's title
+	   * @return	string	The organization's title
+	   */
+	  function get_title(){
+		if($this->debug>0){error_log('In aicc::get_title() method',0);}
+	  	$title = '';
+	  	if(isset($this->config['organizations']['default'])){
+	  		$title = $this->organizations[$this->config['organizations']['default']]->get_name();
+	  	}elseif(count($this->organizations)==1){
+	  		//this will only get one title but so we don't need to know the index
+	  		foreach($this->organizations as $id => $value){
+	  			$title = $this->organizations[$id]->get_name();
+	  			break;
+	  		}
+	  	}
+	  	return $title;
+	  }
+	  /**
+	   * //TODO @TODO implement this function to restore items data from a set of AICC config files,
+	   * updating the existing table... This will prove very useful in case initial data
+	   * from config files were not imported well enough
+	   */
+	  function reimport_aicc(){
+		if($this->debug>0){error_log('In aicc::reimport_aicc() method',0);}
+	  	//query current items list
+	  	//get the identifiers
+	  	//parse the config files
+	  	//match both
+	  	//update DB accordingly
+	  	return true;
+	  }
+	  /**
+	   * Static function to parse AICC ini files.
+	   * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file())
+	   * @param	string	File path
+	   * @return	array	Structured array
+	   */
+		function parse_ini_file_quotes_safe($f)
+		{
+			$null = "";
+			$r=$null;
+			$sec=$null;
+			$f=@file($f);
+			for ($i=0;$i<@count($f);$i++)
+			{
+				$newsec=0;
+				$w=@trim($f[$i]);
+				if ($w)
+				{
+					if ((!$r) or ($sec))
+					{
 						if ((@substr($w,0,1)=="[") and (@substr($w,-1,1))=="]")
-						{
-							$sec=@substr($w,1,@strlen($w)-2);
-							$newsec=1;
-						}
-					}
-					if (!$newsec)
-					{
-						$w=@explode("=",$w);
-						$k=@trim($w[0]);
+						{
+							$sec=@substr($w,1,@strlen($w)-2);
+							$newsec=1;
+						}
+					}
+					if (!$newsec)
+					{
+						$w=@explode("=",$w);
+						$k=@trim($w[0]);
 						unset($w[0]);
-						$v=@trim(@implode("=",$w));
+						$v=@trim(@implode("=",$w));
 						if ((@substr($v,0,1)=="\"") and (@substr($v,-1,1)=="\""))
-						{
-							$v=@substr($v,1,@strlen($v)-2);
-						}
+						{
+							$v=@substr($v,1,@strlen($v)-2);
+						}
 						if ($sec)
-						{
-							if(strtolower($sec)=='course_description'){//special case
-								$r[strtolower($sec)]=$k;
-							}else{
-								$r[strtolower($sec)][strtolower($k)]=$v;
-							}
+						{
+							if(strtolower($sec)=='course_description'){//special case
+								$r[strtolower($sec)]=$k;
+							}else{
+								$r[strtolower($sec)][strtolower($k)]=$v;
+							}
 						} else
-						{
-							$r[strtolower($k)]=$v;
-						}
-					}
-				}
-			}
-			return $r;
-		}
-	  /**
-	   * Static function to parse AICC ini strings.
-	   * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file())
-	   * @param		string	INI File string
-	   * @param		array	List of names of sections that should be considered as containing only hard string data (no variables), provided in lower case
-	   * @return	array	Structured array
-	   */
-		function parse_ini_string_quotes_safe($s,$pure_strings=array())
-		{
-			$null = "";
-			$r=$null;
-			$sec=$null;
-			$f = split("\r\n",$s);
-			for ($i=0;$i<@count($f);$i++)
-			{
-				$newsec=0;
-				$w=@trim($f[$i]);
-				if ($w)
-				{
-					if ((!$r) or ($sec))
-					{
+						{
+							$r[strtolower($k)]=$v;
+						}
+					}
+				}
+			}
+			return $r;
+		}
+	  /**
+	   * Static function to parse AICC ini strings.
+	   * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file())
+	   * @param		string	INI File string
+	   * @param		array	List of names of sections that should be considered as containing only hard string data (no variables), provided in lower case
+	   * @return	array	Structured array
+	   */
+		function parse_ini_string_quotes_safe($s,$pure_strings=array())
+		{
+			$null = "";
+			$r=$null;
+			$sec=$null;
+			$f = split("\r\n",$s);
+			for ($i=0;$i<@count($f);$i++)
+			{
+				$newsec=0;
+				$w=@trim($f[$i]);
+				if ($w)
+				{
+					if ((!$r) or ($sec))
+					{
 						if ((@substr($w,0,1)=="[") and (@substr($w,-1,1))=="]")
-						{
-							$sec=@substr($w,1,@strlen($w)-2);
-							$pure_data = 0;
-							if(in_array(strtolower($sec),$pure_strings)){
-								//this section can only be considered as pure string data (until the next section)
-								$pure_data = 1;
-								$r[strtolower($sec)] = '';
-							}
-							$newsec=1;
-						}
-					}
-					if (!$newsec)
-					{
-						$w=@explode("=",$w);
-						$k=@trim($w[0]);
+						{
+							$sec=@substr($w,1,@strlen($w)-2);
+							$pure_data = 0;
+							if(in_array(strtolower($sec),$pure_strings)){
+								//this section can only be considered as pure string data (until the next section)
+								$pure_data = 1;
+								$r[strtolower($sec)] = '';
+							}
+							$newsec=1;
+						}
+					}
+					if (!$newsec)
+					{
+						$w=@explode("=",$w);
+						$k=@trim($w[0]);
 						unset($w[0]);
-						$v=@trim(@implode("=",$w));
+						$v=@trim(@implode("=",$w));
 						if ((@substr($v,0,1)=="\"") and (@substr($v,-1,1)=="\""))
-						{
-							$v=@substr($v,1,@strlen($v)-2);
-						}
+						{
+							$v=@substr($v,1,@strlen($v)-2);
+						}
 						if ($sec)
-						{
-							if($pure_data){
-								$r[strtolower($sec)] .= $f[$i];
-							}else{
-								if(strtolower($sec)=='course_description'){//special case
-									$r[strtolower($sec)]=$k;
-								}else{
-									$r[strtolower($sec)][strtolower($k)]=$v;
-								}
-							}
+						{
+							if($pure_data){
+								$r[strtolower($sec)] .= $f[$i];
+							}else{
+								if(strtolower($sec)=='course_description'){//special case
+									$r[strtolower($sec)]=$k;
+								}else{
+									$r[strtolower($sec)][strtolower($k)]=$v;
+								}
+							}
 						} else
-						{
-							$r[strtolower($k)]=$v;
-						}
-					}
-				}
-			}
-			return $r;
-		}
-	  /**
-	   * Static function that parses CSV files into simple arrays, based on a function
-	   * by spam at cyber-space dot nl published on php.net (fgetcsv())
-	   * @param	string	Filepath
-	   * @param	string	CSV delimiter
-	   * @param	string	CSV enclosure
-	   * @param	boolean	Might one field name happen more than once on the same line? (then split by comma in the values)
-	   * @return array	Simple structured array
-	   */
-		function parse_csv_file($f,$delim=',',$enclosure='"',$multiples=false)
-		{
-			$data = file_get_contents($f);
-			$enclosed=false;
-			$fldcount=0;
-			$linecount=0;
-			$fldval='';
-			for($i=0;$i<strlen($data);$i++)
-			{
-				$chr=$data{$i};
-				switch($chr)
-				{
-					case $enclosure:
-					   if($enclosed&&$data{$i+1}==$enclosure)
-					   {
-						   $fldval.=$chr;
-						   ++$i; //skip next char
-					   }
-					   else
-					     $enclosed=!$enclosed;
-					   break;
-					case $delim:
-					   if(!$enclosed)
-					   {
-					     $ret_array[$linecount][$fldcount++]=$fldval;
-					     $fldval='';
-					   }
-					   else
-					     $fldval.=$chr;
-					   break;
-					case "\r":
-					   if(!$enclosed&&$data{$i+1}=="\n")
-					     continue;
-					case "\n":
-						if(!$enclosed)
-						{
-							$ret_array[$linecount++][$fldcount]=$fldval;
-							$fldcount=0;
-							$fldval='';
-						}
-						else
-							$fldval.=$chr;
-						break;
-					case "\\r":
-					   if(!$enclosed&&$data{$i+1}=="\\n")
-					     continue;
-					case "\\n":
-						if(!$enclosed)
-						{
-							$ret_array[$linecount++][$fldcount]=$fldval;
-							$fldcount=0;
-							$fldval='';
-						}
-						else
-							$fldval.=$chr;
-						break;
-					default:
-						$fldval.=$chr;
-				}
-			}
-			if($fldval){
-				$ret_array[$linecount][$fldcount]=$fldval;
-			}
-			//transform the array to use the first line as titles
-			$titles = array();
-			$ret_ret_array = array();
-			foreach($ret_array as $line_idx => $line){
-				if($line_idx == 0){
-					$titles = $line;
-				}else{
-					$ret_ret_array[$line_idx] = array();
-					foreach($line as $idx=>$val)
-					{
-						if($multiples && !empty($ret_ret_array[$line_idx][strtolower($titles[$idx])])){
-							$ret_ret_array[$line_idx][strtolower($titles[$idx])].=",".$val;
-						}else{
-							$ret_ret_array[$line_idx][strtolower($titles[$idx])]=$val;
-						}
-					}
-				}
-			}
-			return $ret_ret_array;
-		}
-
-}
-?>
+						{
+							$r[strtolower($k)]=$v;
+						}
+					}
+				}
+			}
+			return $r;
+		}
+	  /**
+	   * Static function that parses CSV files into simple arrays, based on a function
+	   * by spam at cyber-space dot nl published on php.net (fgetcsv())
+	   * @param	string	Filepath
+	   * @param	string	CSV delimiter
+	   * @param	string	CSV enclosure
+	   * @param	boolean	Might one field name happen more than once on the same line? (then split by comma in the values)
+	   * @return array	Simple structured array
+	   */
+		function parse_csv_file($f,$delim=',',$enclosure='"',$multiples=false)
+		{
+			$data = file_get_contents($f);
+			$enclosed=false;
+			$fldcount=0;
+			$linecount=0;
+			$fldval='';
+			for($i=0;$i<strlen($data);$i++)
+			{
+				$chr=$data{$i};
+				switch($chr)
+				{
+					case $enclosure:
+					   if($enclosed&&$data{$i+1}==$enclosure)
+					   {
+						   $fldval.=$chr;
+						   ++$i; //skip next char
+					   }
+					   else
+					     $enclosed=!$enclosed;
+					   break;
+					case $delim:
+					   if(!$enclosed)
+					   {
+					     $ret_array[$linecount][$fldcount++]=$fldval;
+					     $fldval='';
+					   }
+					   else
+					     $fldval.=$chr;
+					   break;
+					case "\r":
+					   if(!$enclosed&&$data{$i+1}=="\n")
+					     continue;
+					case "\n":
+						if(!$enclosed)
+						{
+							$ret_array[$linecount++][$fldcount]=$fldval;
+							$fldcount=0;
+							$fldval='';
+						}
+						else
+							$fldval.=$chr;
+						break;
+					case "\\r":
+					   if(!$enclosed&&$data{$i+1}=="\\n")
+					     continue;
+					case "\\n":
+						if(!$enclosed)
+						{
+							$ret_array[$linecount++][$fldcount]=$fldval;
+							$fldcount=0;
+							$fldval='';
+						}
+						else
+							$fldval.=$chr;
+						break;
+					default:
+						$fldval.=$chr;
+				}
+			}
+			if($fldval){
+				$ret_array[$linecount][$fldcount]=$fldval;
+			}
+			//transform the array to use the first line as titles
+			$titles = array();
+			$ret_ret_array = array();
+			foreach($ret_array as $line_idx => $line){
+				if($line_idx == 0){
+					$titles = $line;
+				}else{
+					$ret_ret_array[$line_idx] = array();
+					foreach($line as $idx=>$val)
+					{
+						if($multiples && !empty($ret_ret_array[$line_idx][strtolower($titles[$idx])])){
+							$ret_ret_array[$line_idx][strtolower($titles[$idx])].=",".$val;
+						}else{
+							$ret_ret_array[$line_idx][strtolower($titles[$idx])]=$val;
+						}
+					}
+				}
+			}
+			return $ret_ret_array;
+		}
+
+}
+?>

+ 54 - 54
main/newscorm/aiccBlock.class.php

@@ -1,59 +1,59 @@
-<?php //$id:$
-/**
+<?php //$id:$
+/**
  * Container for the aiccResource class that deals with elemens from AICC Course Structure file
- * @package	dokeos.learnpath
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
- * Class defining the Block elements in an AICC Course Structure file
+ * @package	dokeos.learnpath
+ * @author	Yannick Warnier <ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * Class defining the Block elements in an AICC Course Structure file
  *
- */
-require_once('learnpathItem.class.php');
-class aiccBlock extends learnpathItem{
-	var $identifier = '';
-	var $members = array();
+ */
+require_once('learnpathItem.class.php');
+class aiccBlock extends learnpathItem{
+	var $identifier = '';
+	var $members = array();
 
-    /**
-     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormResource
-     * object from database records or from the array given as second param
-     * @param	string	Type of construction needed ('db' or 'config', default = 'config')
-     * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
-     */
-    function aiccBlock($type='config',$params) {
-
-    	if(isset($params))
-    	{
-    		switch($type){
-    			case 'db':
-    				//TODO implement this way of object creation
-    				return false;
-    			case 'config': //do the same as the default
-    			default:
-			     	foreach($params as $a => $value)
-			     	{
-			     		switch($a)
-			     		{
-   			     			case 'system_id':
-   			     				$this->identifier = strtolower($value);
-			     				break;
-			     			case 'member':
-			     				if(strstr($value,',')!==false){
-			     					$temp = split(',',$value);
-			     					foreach($temp as $val){
-			     						if(!empty($val)){
-			     							$this->members[] = $val;
-			     						}
-			     					}
-			     				}
-			     				break;
-			     		}
-			     	}
-					return true;
+    /**
+     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormResource
+     * object from database records or from the array given as second param
+     * @param	string	Type of construction needed ('db' or 'config', default = 'config')
+     * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
+     */
+    function aiccBlock($type='config',$params) {
 
-    		}
-    	}
-    	return false;
-     }
-}
+    	if(isset($params))
+    	{
+    		switch($type){
+    			case 'db':
+    				//TODO implement this way of object creation
+    				return false;
+    			case 'config': //do the same as the default
+    			default:
+			     	foreach($params as $a => $value)
+			     	{
+			     		switch($a)
+			     		{
+   			     			case 'system_id':
+   			     				$this->identifier = strtolower($value);
+			     				break;
+			     			case 'member':
+			     				if(strstr($value,',')!==false){
+			     					$temp = split(',',$value);
+			     					foreach($temp as $val){
+			     						if(!empty($val)){
+			     							$this->members[] = $val;
+			     						}
+			     					}
+			     				}
+			     				break;
+			     		}
+			     	}
+					return true;
+
+    		}
+    	}
+    	return false;
+     }
+}
 ?>

+ 134 - 134
main/newscorm/aiccItem.class.php

@@ -1,137 +1,137 @@
-<?php //$id:$
-/**
- * Container for the aiccItem class that deals with AICC Assignable Units (AUs)
- * @package	dokeos.learnpath
- * @author	Yannick Warnier	<ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
- * This class handles the elements from an AICC Descriptor file.
- */
-require_once('learnpathItem.class.php');
-class aiccItem extends learnpathItem{
-	var $identifier = '';//AICC AU's system_id
-	var $identifierref = '';
-	var $parameters = ''; //AICC AU's web_launch
-	var $title = ''; //no AICC equivalent
-	var $sub_items = array(); //AICC elements (des)
-	//var $prerequisites = ''; - defined in learnpathItem.class.php
-	//var $max_score = ''; //defined in learnpathItem
+<?php //$id:$
+/**
+ * Container for the aiccItem class that deals with AICC Assignable Units (AUs)
+ * @package	dokeos.learnpath
+ * @author	Yannick Warnier	<ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * This class handles the elements from an AICC Descriptor file.
+ */
+require_once('learnpathItem.class.php');
+class aiccItem extends learnpathItem{
+	var $identifier = '';//AICC AU's system_id
+	var $identifierref = '';
+	var $parameters = ''; //AICC AU's web_launch
+	var $title = ''; //no AICC equivalent
+	var $sub_items = array(); //AICC elements (des)
+	//var $prerequisites = ''; - defined in learnpathItem.class.php
+	//var $max_score = ''; //defined in learnpathItem
 	//var $path = ''; //defined in learnpathItem
-	var $maxtimeallowed = '00:00:00'; //AICC AU's max_time_allowed
-	var $timelimitaction = ''; //AICC AU's time_limit_action
-	var $masteryscore = ''; //AICC AU's mastery_score
-	var $core_vendor = ''; //AICC AU's core_vendor
-	var $system_vendor = ''; //AICC AU's system_vendor
-	var $au_type = ''; //AICC AU's type
-	var $command_line = ''; //AICC AU's command_line
-	var $debug=0;
-
-    /**
-     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormItem
-     * object from database records or from the array given as second parameter
-     * @param	string	Type of construction needed ('db' or 'config', default = 'config')
-     * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
-     */
-    function aiccItem($type='config',$params) {
-    	if(isset($params))
-    	{
-    		switch($type){
-    			case 'db':
-    				parent::learnpathItem($params,api_get_user_id());
-    				$this->aicc_contact = false;
-    				//TODO implement this way of metadata object creation
-    				return false;
-    			case 'config': //do the same as the default
-    			default:
-			     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
-			     	foreach($params as $a => $value)
-			     	{
-			     		switch($a)
-			     		{
-            				case 'system_id':
-            					$this->identifier = mysql_real_escape_string(strtolower($value));
-            					break;
-            				case 'type':
-            					$this->au_type = mysql_real_escape_string($value);
-            					break;
-            				case 'command_line':
-            					$this->command_line = mysql_real_escape_string($value);
-            					break;
-            				case 'max_time_allowed':
-            					$this->maxtimeallowed = mysql_real_escape_string($value);
-            					break;
-            				case 'time_limit_action':
-            					$this->timelimitaction = mysql_real_escape_string($value);
-            					break;
-            				case 'max_score':
-            					$this->max_score = mysql_real_escape_string($value);
-            					break;
-            				case 'core_vendor':
-            					$this->core_vendor = mysql_real_escape_string($value);
-            					break;
-            				case 'system_vendor':
-            					$this->system_vendor = mysql_real_escape_string($value);
-            					break;
-            				case 'file_name':
-            					$this->path = mysql_real_escape_string($value);
-            					break;
-            				case 'mastery_score':
-            					$this->masteryscore = mysql_real_escape_string($value);
-            					break;
-            				case 'web_launch':
-            					$this->parameters = mysql_real_escape_string($value);
-            					break;
-			     		}
-			     	}
-					return true;
-    		}
-    	}
-    	return false;
-    }
-    /**
-     * Builds a flat list with the current item and calls itself recursively on all children
-     * @param	array	Reference to the array to complete with the current item
-     * @param	integer	Optional absolute order (pointer) of the item in this learning path
-     * @param	integer	Optional relative order of the item at this level
-     * @param	integer	Optional level. If not given, assumes it's level 0
-     */
-    function get_flat_list(&$list,&$abs_order,$rel_order=1,$level=0)
-    {
-    	$list[] = array(
-    		'au_type' => $this->au_type,
-			'command_line' => $this->command_line,
-			'core_vendor'	=> $this->core_vendor,
-			'identifier' => $this->identifier,
-			'identifierref' => $this->identifierref,
-			'masteryscore' => $this->masteryscore,
-			'maxtimeallowed' => $this->maxtimeallowed,
-			'level' => $level,
-			'parameters' => $this->parameters,
-			'prerequisites' => (!empty($this->prereq_string)?$this->prereq_string:''),
-			'timelimitaction' => $this->timelimitaction,
-			);
-		$abs_order++;
-		$i = 1;
-		foreach($this->sub_items as $id => $dummy)
-		{
-			$oSubitem =& $this->sub_items[$id];
-			$oSubitem->get_flat_list($list,$abs_order,$i,$level+1);
-			$i++;
-		}
-    }
-    /**
-     * Save function. Uses the parent save function and adds a layer for AICC.
-     * @param	boolean	Save from URL params (1) or from object attributes (0)
-     */
-    function save($from_outside=true, $prereqs_complete=false)
-    {
-    	parent::save($from_outside, $prereqs_complete=false);
-    	//under certain conditions, the scorm_contact should not be set, because no scorm signal was sent
-    	$this->aicc_contact = true;
-    	if(!$this->aicc_contact){
+	var $maxtimeallowed = '00:00:00'; //AICC AU's max_time_allowed
+	var $timelimitaction = ''; //AICC AU's time_limit_action
+	var $masteryscore = ''; //AICC AU's mastery_score
+	var $core_vendor = ''; //AICC AU's core_vendor
+	var $system_vendor = ''; //AICC AU's system_vendor
+	var $au_type = ''; //AICC AU's type
+	var $command_line = ''; //AICC AU's command_line
+	var $debug=0;
+
+    /**
+     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormItem
+     * object from database records or from the array given as second parameter
+     * @param	string	Type of construction needed ('db' or 'config', default = 'config')
+     * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
+     */
+    function aiccItem($type='config',$params) {
+    	if(isset($params))
+    	{
+    		switch($type){
+    			case 'db':
+    				parent::learnpathItem($params,api_get_user_id());
+    				$this->aicc_contact = false;
+    				//TODO implement this way of metadata object creation
+    				return false;
+    			case 'config': //do the same as the default
+    			default:
+			     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
+			     	foreach($params as $a => $value)
+			     	{
+			     		switch($a)
+			     		{
+            				case 'system_id':
+            					$this->identifier = mysql_real_escape_string(strtolower($value));
+            					break;
+            				case 'type':
+            					$this->au_type = mysql_real_escape_string($value);
+            					break;
+            				case 'command_line':
+            					$this->command_line = mysql_real_escape_string($value);
+            					break;
+            				case 'max_time_allowed':
+            					$this->maxtimeallowed = mysql_real_escape_string($value);
+            					break;
+            				case 'time_limit_action':
+            					$this->timelimitaction = mysql_real_escape_string($value);
+            					break;
+            				case 'max_score':
+            					$this->max_score = mysql_real_escape_string($value);
+            					break;
+            				case 'core_vendor':
+            					$this->core_vendor = mysql_real_escape_string($value);
+            					break;
+            				case 'system_vendor':
+            					$this->system_vendor = mysql_real_escape_string($value);
+            					break;
+            				case 'file_name':
+            					$this->path = mysql_real_escape_string($value);
+            					break;
+            				case 'mastery_score':
+            					$this->masteryscore = mysql_real_escape_string($value);
+            					break;
+            				case 'web_launch':
+            					$this->parameters = mysql_real_escape_string($value);
+            					break;
+			     		}
+			     	}
+					return true;
+    		}
+    	}
+    	return false;
+    }
+    /**
+     * Builds a flat list with the current item and calls itself recursively on all children
+     * @param	array	Reference to the array to complete with the current item
+     * @param	integer	Optional absolute order (pointer) of the item in this learning path
+     * @param	integer	Optional relative order of the item at this level
+     * @param	integer	Optional level. If not given, assumes it's level 0
+     */
+    function get_flat_list(&$list,&$abs_order,$rel_order=1,$level=0)
+    {
+    	$list[] = array(
+    		'au_type' => $this->au_type,
+			'command_line' => $this->command_line,
+			'core_vendor'	=> $this->core_vendor,
+			'identifier' => $this->identifier,
+			'identifierref' => $this->identifierref,
+			'masteryscore' => $this->masteryscore,
+			'maxtimeallowed' => $this->maxtimeallowed,
+			'level' => $level,
+			'parameters' => $this->parameters,
+			'prerequisites' => (!empty($this->prereq_string)?$this->prereq_string:''),
+			'timelimitaction' => $this->timelimitaction,
+			);
+		$abs_order++;
+		$i = 1;
+		foreach($this->sub_items as $id => $dummy)
+		{
+			$oSubitem =& $this->sub_items[$id];
+			$oSubitem->get_flat_list($list,$abs_order,$i,$level+1);
+			$i++;
+		}
+    }
+    /**
+     * Save function. Uses the parent save function and adds a layer for AICC.
+     * @param	boolean	Save from URL params (1) or from object attributes (0)
+     */
+    function save($from_outside=true, $prereqs_complete=false)
+    {
+    	parent::save($from_outside, $prereqs_complete=false);
+    	//under certain conditions, the scorm_contact should not be set, because no scorm signal was sent
+    	$this->aicc_contact = true;
+    	if(!$this->aicc_contact){
     		//error_log('New LP - was expecting SCORM message but none received',0);
-    	}
-    }
-}
+    	}
+    }
+}
 ?>

+ 54 - 54
main/newscorm/aiccObjective.class.php

@@ -1,59 +1,59 @@
-<?php //$id:$
-/**
+<?php //$id:$
+/**
  * Container for the aiccResource class that deals with elemens from AICC Objectives file
- * @package	dokeos.learnpath
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
- * Class defining the Block elements in an AICC Course Structure file
+ * @package	dokeos.learnpath
+ * @author	Yannick Warnier <ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * Class defining the Block elements in an AICC Course Structure file
  *
- */
-require_once('learnpathItem.class.php');
-class aiccObjective extends learnpathItem{
-	var $identifier = '';
-	var $members = array();
+ */
+require_once('learnpathItem.class.php');
+class aiccObjective extends learnpathItem{
+	var $identifier = '';
+	var $members = array();
 
-    /**
-     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormResource
-     * object from database records or from the array given as second param
-     * @param	string	Type of construction needed ('db' or 'config', default = 'config')
-     * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
-     */
-    function aiccObjective($type='config',$params) {
-
-    	if(isset($params))
-    	{
-    		switch($type){
-    			case 'db':
-    				//TODO implement this way of object creation
-    				return false;
-    			case 'config': //do the same as the default
-    			default:
-			     	foreach($params as $a => $value)
-			     	{
-			     		switch($a)
-			     		{
-   			     			case 'system_id':
-   			     				$this->identifier = strtolower($value);
-			     				break;
-			     			case 'member':
-			     				if(strstr($value,',')!==false){
-			     					$temp = split(',',$value);
-			     					foreach($temp as $val){
-			     						if(!empty($val)){
-			     							$this->members[] = $val;
-			     						}
-			     					}
-			     				}
-			     				break;
-			     		}
-			     	}
-					return true;
+    /**
+     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormResource
+     * object from database records or from the array given as second param
+     * @param	string	Type of construction needed ('db' or 'config', default = 'config')
+     * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
+     */
+    function aiccObjective($type='config',$params) {
 
-    		}
-    	}
-    	return false;
-     }
-}
+    	if(isset($params))
+    	{
+    		switch($type){
+    			case 'db':
+    				//TODO implement this way of object creation
+    				return false;
+    			case 'config': //do the same as the default
+    			default:
+			     	foreach($params as $a => $value)
+			     	{
+			     		switch($a)
+			     		{
+   			     			case 'system_id':
+   			     				$this->identifier = strtolower($value);
+			     				break;
+			     			case 'member':
+			     				if(strstr($value,',')!==false){
+			     					$temp = split(',',$value);
+			     					foreach($temp as $val){
+			     						if(!empty($val)){
+			     							$this->members[] = $val;
+			     						}
+			     					}
+			     				}
+			     				break;
+			     		}
+			     	}
+					return true;
+
+    		}
+    	}
+    	return false;
+     }
+}
 ?>

+ 51 - 51
main/newscorm/aiccResource.class.php

@@ -1,57 +1,57 @@
-<?php //$id:$
-/**
+<?php //$id:$
+/**
  * Container for the aiccResource class that deals with elemens from AICC Descriptor file
- * @package	dokeos.learnpath
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
+ * @package	dokeos.learnpath
+ * @author	Yannick Warnier <ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
  * Class defining the elements from an AICC Descriptor file
- */
-class aiccResource {
-	var $identifier = '';
-	var $title = '';
+ */
+class aiccResource {
+	var $identifier = '';
+	var $title = '';
 	var $description = '';
-	var $developer_id = '';
+	var $developer_id = '';
 
-    /**
-     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormResource
-     * object from database records or from the array given as second param
-     * @param	string	Type of construction needed ('db' or 'config', default = 'config')
-     * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
-     */
-    function aiccResource($type='config',$params) {
-
-    	if(isset($params))
-    	{
-    		switch($type){
-    			case 'db':
-    				//TODO implement this way of object creation
-    				return false;
-    			case 'config': //do the same as the default
-    			default:
-			     	foreach($params as $a => $value)
-			     	{
-			     		switch($a)
-			     		{
-   			     			case 'system_id':
-   			     				$this->identifier = strtolower($value);
-			     				break;
-			     			case 'title':
-			     				$this->title = $value;
-			     			case 'description':
-			     				$this->description = $value;
-			     				break;
-			     			case 'developer_id':
-			     				$this->developer_id = $value;
-			     				break;
-			     		}
-			     	}
-					return true;
+    /**
+     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormResource
+     * object from database records or from the array given as second param
+     * @param	string	Type of construction needed ('db' or 'config', default = 'config')
+     * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
+     */
+    function aiccResource($type='config',$params) {
 
-    		}
-    	}
-    	return false;
-     }
-}
+    	if(isset($params))
+    	{
+    		switch($type){
+    			case 'db':
+    				//TODO implement this way of object creation
+    				return false;
+    			case 'config': //do the same as the default
+    			default:
+			     	foreach($params as $a => $value)
+			     	{
+			     		switch($a)
+			     		{
+   			     			case 'system_id':
+   			     				$this->identifier = strtolower($value);
+			     				break;
+			     			case 'title':
+			     				$this->title = $value;
+			     			case 'description':
+			     				$this->description = $value;
+			     				break;
+			     			case 'developer_id':
+			     				$this->developer_id = $value;
+			     				break;
+			     		}
+			     	}
+					return true;
+
+    		}
+    	}
+    	return false;
+     }
+}
 ?>

+ 716 - 716
main/newscorm/aicc_api.php

@@ -1,770 +1,770 @@
 <?php // $Id: $
-/**
+/**
 ==============================================================================
-*	API event handler functions for AICC / CMIv4 in API communication mode
-*
-*	@author   Denes Nagy <darkden@freemail.hu>
-*   @author   Yannick Warnier <ywarnier@beeznest.org>
-*	@version  v 1.0
-*	@access   public
-*	@package  dokeos.learnpath
-* 	@license	GNU/GPL - See Dokeos license directory for details
+*	API event handler functions for AICC / CMIv4 in API communication mode
+*
+*	@author   Denes Nagy <darkden@freemail.hu>
+*   @author   Yannick Warnier <ywarnier@beeznest.org>
+*	@version  v 1.0
+*	@access   public
+*	@package  dokeos.learnpath
+* 	@license	GNU/GPL - See Dokeos license directory for details
 ==============================================================================
-*/
-/**
+*/
+/**
  * This script is divided into three sections.
- * The first section (below) is the initialisation part.
- * The second section is the AICC object part
- * The third section defines the event handlers for Dokeos' internal messaging
- * and frames refresh
+ * The first section (below) is the initialisation part.
+ * The second section is the AICC object part
+ * The third section defines the event handlers for Dokeos' internal messaging
+ * and frames refresh
  *
- * This script implements the API messaging for AICC. The HACP messaging is
- * made by another set of scripts.
- */
-/*
+ * This script implements the API messaging for AICC. The HACP messaging is
+ * made by another set of scripts.
+ */
+/*
 ==============================================================================
-	   INIT SECTION
+	   INIT SECTION
 ==============================================================================
 */
-
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-//Load common libraries using a compatibility script to bridge between 1.6 and 1.8
+
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+//Load common libraries using a compatibility script to bridge between 1.6 and 1.8
 require_once('back_compat.inc.php');
-//Load learning path libraries so we can use the objects to define the initial values
-//of the API
-require_once('learnpath.class.php');
-require_once('learnpathItem.class.php');
-require_once('aicc.class.php');
-
-// Is this needed? This is probabaly done in the header file
-// $_user							= $_SESSION['_user'];
-$file							= $_SESSION['file'];
-$oLP							= unserialize($_SESSION['lpobject']);
-$oItem 							= $oLP->items[$oLP->current];
-if(!is_object($oItem)){
-	error_log('New LP - scorm_api - Could not load oItem item',0);
-	exit;
-}
-$autocomplete_when_80pct = 0;
-
-/*
+//Load learning path libraries so we can use the objects to define the initial values
+//of the API
+require_once('learnpath.class.php');
+require_once('learnpathItem.class.php');
+require_once('aicc.class.php');
+
+// Is this needed? This is probabaly done in the header file
+// $_user							= $_SESSION['_user'];
+$file							= $_SESSION['file'];
+$oLP							= unserialize($_SESSION['lpobject']);
+$oItem 							= $oLP->items[$oLP->current];
+if(!is_object($oItem)){
+	error_log('New LP - scorm_api - Could not load oItem item',0);
+	exit;
+}
+$autocomplete_when_80pct = 0;
+
+/*
 ==============================================================================
-		JavaScript Functions
+		JavaScript Functions
 ==============================================================================
 */
-?>var scorm_logs=<?php echo (empty($oLP->scorm_debug)?'0':'3');?>; //debug log level for SCORM. 0 = none, 1=light, 2=a lot, 3=all - displays logs in log frame
-var lms_logs=0; //debug log level for LMS actions. 0=none, 1=light, 2=a lot, 3=all
-//logit_lms('scormfunctions.php included',0);
-
-function APIobject() {
-  this.LMSInitialize=LMSInitialize;
-  this.LMSGetValue=LMSGetValue;
-  this.LMSSetValue=LMSSetValue;
-  this.LMSCommit=LMSCommit;
-  this.LMSFinish=LMSFinish;
-  this.LMSGetLastError=LMSGetLastError;
-  this.LMSGetErrorString=LMSGetErrorString;
-  this.LMSGetDiagnostic=LMSGetDiagnostic;
-}
-
-//it is not sure that the scos use the above declarations
-
-API = new APIobject(); //for scorm 1.2
-
-var G_NoError = 0;
-var G_GeneralException = 101;
-var G_ServerBusy = 102;
-var G_InvalidArgumentError = 201;
-var G_ElementCannotHaveChildren = 202;
-var G_ElementIsNotAnArray = 203;
-var G_NotInitialized = 301;
-var G_NotImplementedError = 401;
-var G_InvalidSetValue = 402;
-var G_ElementIsReadOnly = 403;
-var G_ElementIsWriteOnly = 404;
-var G_IncorrectDataType = 405;
-
-var G_LastError = G_NoError ;
-
-var commit = false ;
-
-//Strictly scorm variables
-var score=<?php echo $oItem->get_score();?>;
-var max=<?php echo $oItem->get_max();?>;
-var min=<?php echo $oItem->get_min();?>;
-var lesson_status='<?php echo $oItem->get_status();?>';
-var session_time='<?php echo $oItem->get_scorm_time('js');?>';
-var suspend_data = '<?php echo $oItem->get_suspend_data();?>';
-var lesson_location = '<?php echo $oItem->get_lesson_location();?>';
-var total_time = '<?php echo $oItem->get_scorm_time('js');?>';
-
-//Dokeos internal variables
-var saved_lesson_status = 'not attempted';
-var lms_lp_id = <?php echo $oLP->get_id();?>;
-var lms_item_id = <?php echo $oItem->get_id();?>;
-//var lms_new_item_id = 0; //temporary value (only there between a load_item() and a LMSInitialize())
-var lms_been_synchronized = 0;
-var lms_initialized = 0;
-var lms_total_lessons = <?php echo $oLP->get_total_items_count(); ?>;
-var lms_complete_lessons = <?php echo $oLP->get_complete_items_count();?>;
-var lms_progress_bar_mode = '<?php echo $oLP->progress_bar_mode;?>';
-if(lms_progress_bar_mode == ''){lms_progress_bar_mode='%';}
-var lms_view_id = '<?php echo $oLP->get_view();?>';
-if(lms_view_id == ''){ lms_view_id = 1;}
-var lms_user_id = '<?php echo $_user['user_id'];?>';
-var lms_next_item = '<?php echo $oLP->get_next_item_id();?>';
-var lms_previous_item = '<?php echo $oLP->get_previous_item_id();?>';
-var lms_lp_type = '<?php echo $oLP->get_type();?>';
-var lms_item_type = '<?php echo $oItem->get_type();?>';
-
-//Backup for old values
-var old_score = 0;
-var old_max = 0;
-var old_min = 0;
-var old_lesson_status = '';
-var old_session_time = '';
-var old_suspend_data = '';
-var lms_old_item_id = 0;
-
-function LMSInitialize() {  //this is the initialize function of all APIobjects
-	logit_scorm('LMSInitialise()',0);
-	lms_initialized=1;
-	return('true');
-}
-function LMSGetValue(param) {
-	//logit_scorm("LMSGetValue('"+param+"')",1);
-	var result='';
-	if(param=='cmi.core._children' || param=='cmi.core_children'){
-		result='entry, exit, lesson_status, student_id, student_name, lesson_location, total_time, credit, lesson_mode, score, session_time';
-	}else if(param == 'cmi.core.entry'){
-		result='';
-	}else if(param == 'cmi.core.exit'){
-		result='';
-	}else if(param == 'cmi.core.lesson_status'){
-	    if(lesson_status != '') {
-	    	result=lesson_status;
-	    }
-	    else{
-	    	result='not attempted';
-	    }
-	}else if(param == 'cmi.core.student_id'){
-		result='<?php echo $_user['user_id']; ?>';
-	}else if(param == 'cmi.core.student_name'){
-		  <?php
-			$who=addslashes(api_get_person_name($_user['firstName'], $_user['lastName']));
+?>var scorm_logs=<?php echo (empty($oLP->scorm_debug)?'0':'3');?>; //debug log level for SCORM. 0 = none, 1=light, 2=a lot, 3=all - displays logs in log frame
+var lms_logs=0; //debug log level for LMS actions. 0=none, 1=light, 2=a lot, 3=all
+//logit_lms('scormfunctions.php included',0);
+
+function APIobject() {
+  this.LMSInitialize=LMSInitialize;
+  this.LMSGetValue=LMSGetValue;
+  this.LMSSetValue=LMSSetValue;
+  this.LMSCommit=LMSCommit;
+  this.LMSFinish=LMSFinish;
+  this.LMSGetLastError=LMSGetLastError;
+  this.LMSGetErrorString=LMSGetErrorString;
+  this.LMSGetDiagnostic=LMSGetDiagnostic;
+}
+
+//it is not sure that the scos use the above declarations
+
+API = new APIobject(); //for scorm 1.2
+
+var G_NoError = 0;
+var G_GeneralException = 101;
+var G_ServerBusy = 102;
+var G_InvalidArgumentError = 201;
+var G_ElementCannotHaveChildren = 202;
+var G_ElementIsNotAnArray = 203;
+var G_NotInitialized = 301;
+var G_NotImplementedError = 401;
+var G_InvalidSetValue = 402;
+var G_ElementIsReadOnly = 403;
+var G_ElementIsWriteOnly = 404;
+var G_IncorrectDataType = 405;
+
+var G_LastError = G_NoError ;
+
+var commit = false ;
+
+//Strictly scorm variables
+var score=<?php echo $oItem->get_score();?>;
+var max=<?php echo $oItem->get_max();?>;
+var min=<?php echo $oItem->get_min();?>;
+var lesson_status='<?php echo $oItem->get_status();?>';
+var session_time='<?php echo $oItem->get_scorm_time('js');?>';
+var suspend_data = '<?php echo $oItem->get_suspend_data();?>';
+var lesson_location = '<?php echo $oItem->get_lesson_location();?>';
+var total_time = '<?php echo $oItem->get_scorm_time('js');?>';
+
+//Dokeos internal variables
+var saved_lesson_status = 'not attempted';
+var lms_lp_id = <?php echo $oLP->get_id();?>;
+var lms_item_id = <?php echo $oItem->get_id();?>;
+//var lms_new_item_id = 0; //temporary value (only there between a load_item() and a LMSInitialize())
+var lms_been_synchronized = 0;
+var lms_initialized = 0;
+var lms_total_lessons = <?php echo $oLP->get_total_items_count(); ?>;
+var lms_complete_lessons = <?php echo $oLP->get_complete_items_count();?>;
+var lms_progress_bar_mode = '<?php echo $oLP->progress_bar_mode;?>';
+if(lms_progress_bar_mode == ''){lms_progress_bar_mode='%';}
+var lms_view_id = '<?php echo $oLP->get_view();?>';
+if(lms_view_id == ''){ lms_view_id = 1;}
+var lms_user_id = '<?php echo $_user['user_id'];?>';
+var lms_next_item = '<?php echo $oLP->get_next_item_id();?>';
+var lms_previous_item = '<?php echo $oLP->get_previous_item_id();?>';
+var lms_lp_type = '<?php echo $oLP->get_type();?>';
+var lms_item_type = '<?php echo $oItem->get_type();?>';
+
+//Backup for old values
+var old_score = 0;
+var old_max = 0;
+var old_min = 0;
+var old_lesson_status = '';
+var old_session_time = '';
+var old_suspend_data = '';
+var lms_old_item_id = 0;
+
+function LMSInitialize() {  //this is the initialize function of all APIobjects
+	logit_scorm('LMSInitialise()',0);
+	lms_initialized=1;
+	return('true');
+}
+function LMSGetValue(param) {
+	//logit_scorm("LMSGetValue('"+param+"')",1);
+	var result='';
+	if(param=='cmi.core._children' || param=='cmi.core_children'){
+		result='entry, exit, lesson_status, student_id, student_name, lesson_location, total_time, credit, lesson_mode, score, session_time';
+	}else if(param == 'cmi.core.entry'){
+		result='';
+	}else if(param == 'cmi.core.exit'){
+		result='';
+	}else if(param == 'cmi.core.lesson_status'){
+	    if(lesson_status != '') {
+	    	result=lesson_status;
+	    }
+	    else{
+	    	result='not attempted';
+	    }
+	}else if(param == 'cmi.core.student_id'){
+		result='<?php echo $_user['user_id']; ?>';
+	}else if(param == 'cmi.core.student_name'){
+		  <?php
+			$who=addslashes(api_get_person_name($_user['firstName'], $_user['lastName']));
 		    echo "result='$who';";
-		  ?>
-	}else if(param == 'cmi.core.lesson_location'){
-		result=lesson_location;
-	}else if(param == 'cmi.core.total_time'){
-		result=total_time;
-	}else if(param == 'cmi.core.score._children'){
-		result='raw,min,max';
-	}else if(param == 'cmi.core.score.raw'){
-		result=score;
-	}else if(param == 'cmi.core.score.max'){
-		result=max;
-	}else if(param == 'cmi.core.score.min'){
-		result=min;
-	}else if(param == 'cmi.core.score'){
-		result=score;
-	}else if(param == 'cmi.core.credit'){
-		result='no-credit';
-	}else if(param == 'cmi.core.lesson_mode'){
-		result='normal';
-	}else if(param == 'cmi.suspend_data'){
-		result='<?php echo $oItem->get_suspend_data();?>';
-	}else if(param == 'cmi.launch_data'){
-		result='';
-	}else if(param == 'cmi.objectives._count'){
-		result='<?php echo $oItem->get_view_count();?>';
-	}
-	/*
-	//Switch not working??? WTF???
-	switch(param) {
-		case 'cmi.core._children'		:
-			result='entry, exit, lesson_status, student_id, student_name, lesson_location, total_time, credit, lesson_mode, score, session_time';
-			break;
-		case 'cmi.core_children'		:
-			result='entry, exit, lesson_status, student_id, student_name, lesson_location, total_time, credit, lesson_mode, score, session_time';
-			break;
-		case 'cmi.core.entry'			:
-			result='';
-			break;
+		  ?>
+	}else if(param == 'cmi.core.lesson_location'){
+		result=lesson_location;
+	}else if(param == 'cmi.core.total_time'){
+		result=total_time;
+	}else if(param == 'cmi.core.score._children'){
+		result='raw,min,max';
+	}else if(param == 'cmi.core.score.raw'){
+		result=score;
+	}else if(param == 'cmi.core.score.max'){
+		result=max;
+	}else if(param == 'cmi.core.score.min'){
+		result=min;
+	}else if(param == 'cmi.core.score'){
+		result=score;
+	}else if(param == 'cmi.core.credit'){
+		result='no-credit';
+	}else if(param == 'cmi.core.lesson_mode'){
+		result='normal';
+	}else if(param == 'cmi.suspend_data'){
+		result='<?php echo $oItem->get_suspend_data();?>';
+	}else if(param == 'cmi.launch_data'){
+		result='';
+	}else if(param == 'cmi.objectives._count'){
+		result='<?php echo $oItem->get_view_count();?>';
+	}
+	/*
+	//Switch not working??? WTF???
+	switch(param) {
+		case 'cmi.core._children'		:
+			result='entry, exit, lesson_status, student_id, student_name, lesson_location, total_time, credit, lesson_mode, score, session_time';
+			break;
+		case 'cmi.core_children'		:
+			result='entry, exit, lesson_status, student_id, student_name, lesson_location, total_time, credit, lesson_mode, score, session_time';
+			break;
+		case 'cmi.core.entry'			:
+			result='';
+			break;
 		case 'cmi.core.exit'			:
-			result='';
-			break;
+			result='';
+			break;
 		case 'cmi.core.lesson_status'	:
-		    if(lesson_status != '') {
-		    	result=lesson_status;
-		    }
-		    else{
-		    	result='not attempted';
-		    }
-		    break;
+		    if(lesson_status != '') {
+		    	result=lesson_status;
+		    }
+		    else{
+		    	result='not attempted';
+		    }
+		    break;
 		case 'cmi.core.student_id'	   :
-			result='<?php echo $_user['user_id']; ?>';
-			break;
+			result='<?php echo $_user['user_id']; ?>';
+			break;
 		case 'cmi.core.student_name'	:
-		  <?php
-		    $who=addslashes(api_get_person_name($_user['firstName'], $_user['lastName']));
+		  <?php
+		    $who=addslashes(api_get_person_name($_user['firstName'], $_user['lastName']));
 		    echo "result='$who';";
-		  ?>	break;
-		case 'cmi.core.lesson_location'	:
-			result='';
-			break;
+		  ?>	break;
+		case 'cmi.core.lesson_location'	:
+			result='';
+			break;
 		case 'cmi.core.total_time'	:
-			result=total_time;
-			break;
+			result=total_time;
+			break;
 		case 'cmi.core.score._children'	:
-			result='raw,min,max';
-			break;
+			result='raw,min,max';
+			break;
 		case 'cmi.core.score.raw'	:
-			result=score;
-			break;
-		case 'cmi.core.score.max'	:
-			result=max;
-			break;
+			result=score;
+			break;
+		case 'cmi.core.score.max'	:
+			result=max;
+			break;
 		case 'cmi.core.score.min'	:
-			result=min;
-			break;
+			result=min;
+			break;
 		case 'cmi.core.score'		:
-			result=score;
-			break;
+			result=score;
+			break;
 		case 'cmi.core.credit'		:
-			result='no-credit';
-			break;
+			result='no-credit';
+			break;
 		case 'cmi.core.lesson_mode'	:
-			result='normal';
-			break;
+			result='normal';
+			break;
 		case 'cmi.suspend_data'		:
-			result='<?php echo $oItem->get_suspend_data();?>';
-			break;
+			result='<?php echo $oItem->get_suspend_data();?>';
+			break;
 		case 'cmi.launch_data'		:
-			result='';
-			break;
+			result='';
+			break;
 		case 'cmi.objectives._count':
-			result='<?php echo $oItem->get_view_count();?>';
-			break;
+			result='<?php echo $oItem->get_view_count();?>';
+			break;
 		default 					:
-			result='';
-			break;
-	}
-	*/
-	logit_scorm("LMSGetValue('"+param+"') returned '"+result+"'",1);
-	return result;
-}
-function LMSSetValue(param, val) {
-	logit_scorm("LMSSetValue('"+param+"','"+val+"')",0);
-	switch(param) {
-	case 'cmi.core.score.raw'		: score= val ;			break;
-	case 'cmi.core.score.max'		: max = val;			break;
-	case 'cmi.core.score.min'		: min = val;			break;
-	case 'cmi.core.lesson_location' : lesson_location = val;break;
+			result='';
+			break;
+	}
+	*/
+	logit_scorm("LMSGetValue('"+param+"') returned '"+result+"'",1);
+	return result;
+}
+function LMSSetValue(param, val) {
+	logit_scorm("LMSSetValue('"+param+"','"+val+"')",0);
+	switch(param) {
+	case 'cmi.core.score.raw'		: score= val ;			break;
+	case 'cmi.core.score.max'		: max = val;			break;
+	case 'cmi.core.score.min'		: min = val;			break;
+	case 'cmi.core.lesson_location' : lesson_location = val;break;
 	case 'cmi.core.lesson_status'	:
-		saved_lesson_status = lesson_status;
-		lesson_status = val;
-		<?php if($oLP->mode != 'fullscreen'){ ?>
-	    //var update = update_toc(lesson_status,lms_item_id);
-	    <?php } ?>
-		break;
-	case 'cmi.completion_status'	: lesson_status = val;	break; //1.3
-	case 'cmi.core.session_time'	: session_time = val;	break;
-	case 'cmi.score.scaled'			: score = val ;			break; //1.3
-	case 'cmi.success_status'		: success_status = val; break; //1.3
-	case 'cmi.suspend_data'			: suspend_data = val;   break;
-	}
-    //var update = update_toc();
-	//var update_progress = update_progress_bar();
+		saved_lesson_status = lesson_status;
+		lesson_status = val;
+		<?php if($oLP->mode != 'fullscreen'){ ?>
+	    //var update = update_toc(lesson_status,lms_item_id);
+	    <?php } ?>
+		break;
+	case 'cmi.completion_status'	: lesson_status = val;	break; //1.3
+	case 'cmi.core.session_time'	: session_time = val;	break;
+	case 'cmi.score.scaled'			: score = val ;			break; //1.3
+	case 'cmi.success_status'		: success_status = val; break; //1.3
+	case 'cmi.suspend_data'			: suspend_data = val;   break;
+	}
+    //var update = update_toc();
+	//var update_progress = update_progress_bar();
 	<?php
-	if ($oLP->force_commit == 1){
-		echo "    var mycommit = LMSCommit('force');";
-	}
-	?>
-	return(true);
-}
-function savedata(origin) { //origin can be 'commit', 'finish' or 'terminate'
-    <?php if ($autocomplete_when_80pct){ ?>
-    if( ( lesson_status == 'incomplete') && (score >= (0.8*max) ) ){
-      lesson_status = 'completed';
-    }
-    <?php }?>
-    param = 'id='+lms_item_id+'&origin='+origin+'&score='+score+'&max='+max+'&min='+min+'&lesson_status='+lesson_status+'&time='+session_time+'&suspend_data='+suspend_data;
+	if ($oLP->force_commit == 1){
+		echo "    var mycommit = LMSCommit('force');";
+	}
+	?>
+	return(true);
+}
+function savedata(origin) { //origin can be 'commit', 'finish' or 'terminate'
+    <?php if ($autocomplete_when_80pct){ ?>
+    if( ( lesson_status == 'incomplete') && (score >= (0.8*max) ) ){
+      lesson_status = 'completed';
+    }
+    <?php }?>
+    param = 'id='+lms_item_id+'&origin='+origin+'&score='+score+'&max='+max+'&min='+min+'&lesson_status='+lesson_status+'&time='+session_time+'&suspend_data='+suspend_data;
+
+    url="http://<?php
+    $self=api_get_self();
+    $url=$_SERVER['HTTP_HOST'].$self;
+    $url=substr($url,0,-14);//14 is the length of this file's name (/scorm_api.php)
+    echo $url;
+    ?>/lp_controller.php?cidReq=<?php echo api_get_course_id();?>&action=save&lp_id=<?php echo $oLP->get_id();?>&" + param + "";
+	logit_lms('saving data (status='+lesson_status+')',1);
+	xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location);
+	//xajax_update_pgs();
+	//xajax_update_toc();
+}
 
-    url="http://<?php
-    $self=api_get_self();
-    $url=$_SERVER['HTTP_HOST'].$self;
-    $url=substr($url,0,-14);//14 is the length of this file's name (/scorm_api.php)
-    echo $url;
-    ?>/lp_controller.php?cidReq=<?php echo api_get_course_id();?>&action=save&lp_id=<?php echo $oLP->get_id();?>&" + param + "";
-	logit_lms('saving data (status='+lesson_status+')',1);
-	xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location);
-	//xajax_update_pgs();
-	//xajax_update_toc();
-}
-
-function LMSCommit(val) {
-	logit_scorm('LMSCommit()',0);
-    commit = true ;
-	savedata('commit');
-	return('true');
-}
-function LMSFinish(val) {
+function LMSCommit(val) {
+	logit_scorm('LMSCommit()',0);
+    commit = true ;
+	savedata('commit');
+	return('true');
+}
+function LMSFinish(val) {
 	if (( commit == false )) {
 		logit_scorm('LMSFinish() (no LMSCommit())',1);
-	}
-	if ( commit == true ) {
+	}
+	if ( commit == true ) {
 		logit_scorm('LMSFinish() called',1);
-		savedata('finish');
-	}
-	return('true');
-}
-function LMSGetLastError() {
-	logit_scorm('LMSGetLastError()',1);
-	return(G_LastError);
-}
-function LMSGetErrorString(errCode){
-	logit_scorm('LMSGetErrorString()',1);
-	return('No error !');
-}
-function LMSGetDiagnostic(errCode){
-	logit_scorm('LMSGetDiagnostic()',1);
-	return(API.LMSGetLastError());
-}
-<?php
-//--------------------------------------------------------------------//
-/**
- * Dokeos-specific code that deals with event handling and inter-frames
- * messaging/refreshing.
- * Note that from now on, the Dokeos JS code in this library will act as
- * a controller, of the MVC pattern, and receive all requests for frame
- * updates, then redispatch to any frame concerned.
- */
-?>
-/**
- * Defining the AJAX-object class to be made available from other frames
- */
-function XAJAXobject() {
-  this.xajax_switch_item_details=xajax_switch_item_details;
-  this.switch_item=switch_item;
-}
-
-//it is not sure that the scos use the above declarations
-
-oXAJAX = new XAJAXobject();
-oxajax = new XAJAXobject();
-
-/**
- * Cross-browser event handling by Scott Andrew
- * @param	element	Element that needs an event attached
- * @param   string	Event type (load, unload, click, keyDown, ...)
- * @param   string	Function name (the event handler)
- * @param   string	used in addEventListener
- */
-function addEvent(elm, evType, fn, useCapture){
-	if(elm.addEventListener){
-		elm.addEventListener(evType, fn, useCapture);
-		return true;
-	}else if (elm.attachEvent){
-		var r = elm.attachEvent('on' + evType, fn);
-	}else{
-		elm['on'+evType] = fn;
-	}
-}
-/**
- * Add listeners to the page objects. This has to be defined for
- * the current context as it acts on objects that should exist
+		savedata('finish');
+	}
+	return('true');
+}
+function LMSGetLastError() {
+	logit_scorm('LMSGetLastError()',1);
+	return(G_LastError);
+}
+function LMSGetErrorString(errCode){
+	logit_scorm('LMSGetErrorString()',1);
+	return('No error !');
+}
+function LMSGetDiagnostic(errCode){
+	logit_scorm('LMSGetDiagnostic()',1);
+	return(API.LMSGetLastError());
+}
+<?php
+//--------------------------------------------------------------------//
+/**
+ * Dokeos-specific code that deals with event handling and inter-frames
+ * messaging/refreshing.
+ * Note that from now on, the Dokeos JS code in this library will act as
+ * a controller, of the MVC pattern, and receive all requests for frame
+ * updates, then redispatch to any frame concerned.
+ */
+?>
+/**
+ * Defining the AJAX-object class to be made available from other frames
+ */
+function XAJAXobject() {
+  this.xajax_switch_item_details=xajax_switch_item_details;
+  this.switch_item=switch_item;
+}
+
+//it is not sure that the scos use the above declarations
+
+oXAJAX = new XAJAXobject();
+oxajax = new XAJAXobject();
+
+/**
+ * Cross-browser event handling by Scott Andrew
+ * @param	element	Element that needs an event attached
+ * @param   string	Event type (load, unload, click, keyDown, ...)
+ * @param   string	Function name (the event handler)
+ * @param   string	used in addEventListener
+ */
+function addEvent(elm, evType, fn, useCapture){
+	if(elm.addEventListener){
+		elm.addEventListener(evType, fn, useCapture);
+		return true;
+	}else if (elm.attachEvent){
+		var r = elm.attachEvent('on' + evType, fn);
+	}else{
+		elm['on'+evType] = fn;
+	}
+}
+/**
+ * Add listeners to the page objects. This has to be defined for
+ * the current context as it acts on objects that should exist
  * on the page
- */
-function addListeners(){
-	//exit if the browser doesn't support ID or tag retrieval
-	logit_lms('Entering addListeners()',2);
-	if(!document.getElementsByTagName){
-		logit_lms("getElementsByTagName not available",2);
-		return;
-	}
-	if(!document.getElementById){
-		logit_lms("getElementById not available",2);
-		return;
-	}
-	//assign event handlers to objects
-	if(lms_lp_type==1 || lms_item_type=='asset'){
-		logit_lms('Dokeos LP or asset',2);
-		//if this path is a Dokeos learnpath, then start manual save
-		//when something is loaded in there
-		var myelem = document.getElementById('content_id');
-		if(!myelem){logit_lms("Impossible to find content_id element in document",2);}
-		addEvent(myelem,'unload',dokeos_save_asset,false);
-		logit_lms('Added event listener on content_id for unload',2);
-	}
-	logit_lms('Quitting addListeners()',2);
-}
-/**
- * Load an item into the content frame:
- * - making sure the previous item status have been saved
+ */
+function addListeners(){
+	//exit if the browser doesn't support ID or tag retrieval
+	logit_lms('Entering addListeners()',2);
+	if(!document.getElementsByTagName){
+		logit_lms("getElementsByTagName not available",2);
+		return;
+	}
+	if(!document.getElementById){
+		logit_lms("getElementById not available",2);
+		return;
+	}
+	//assign event handlers to objects
+	if(lms_lp_type==1 || lms_item_type=='asset'){
+		logit_lms('Dokeos LP or asset',2);
+		//if this path is a Dokeos learnpath, then start manual save
+		//when something is loaded in there
+		var myelem = document.getElementById('content_id');
+		if(!myelem){logit_lms("Impossible to find content_id element in document",2);}
+		addEvent(myelem,'unload',dokeos_save_asset,false);
+		logit_lms('Added event listener on content_id for unload',2);
+	}
+	logit_lms('Quitting addListeners()',2);
+}
+/**
+ * Load an item into the content frame:
+ * - making sure the previous item status have been saved
  * - first updating the current item ID (to save the right item)
- * - updating the frame src
- */
-function load_item(item_id,url){
-	if(document.getElementById('content_id'))
-	{
-		logit_lms('Loading item '+item_id,2);
-		var cont_f = document.getElementById('content_id');
-		if(cont_f.src){
-			lms_old_item_id = lms_item_id;
-			var lms_new_item_id = item_id;
-			//load new content page into content frame
-			if(lms_lp_type==1 || lms_item_type=='asset'){
-				dokeos_save_asset();
-			}
-			cont_f.src = url;
-			update_toc('unhighlight',lms_old_item_id);
-			update_toc('highlight',item_id);
-			/* legacy code
-			lms_been_synchronized = 0;
-			lms_initialized = 0;
-			if(lms_lp_type==1 || lms_item_type=='asset'){
-				lms_item_id = lms_new_item_id;
-			}*/
-			return true;
-		}
-		logit_lms('cont_f.src has no properties',0);
-	}
-	logit_lms('content_id has no properties',0);
-	return false;
-}
-/**
- * Save a Dokeos learnpath item's time and mark as completed upon
- * leaving it
- */
-function dokeos_save_asset(){
-    //var linkparams = 'id='+lms_item_id+'&score='+score+'&max='+max+'&min='+min+'&lesson_status='+lesson_status+'&time='+session_time+'&suspend_data='+suspend_data;
-    //var url = "<?php echo api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php' ?>?action=save&" + linkparams + "";
-	logit_lms('dokeos_save_asset: '+url,0);
-    //frames["message_name"].src = url;
-    xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location);
-}
-/**
- * Logs information about SCORM messages into the log frame
- * @param	string	Message to log
- * @param	integer Priority (0 for top priority, 3 for lowest)
- */
-function logit_scorm(message,priority){
-	if(frames["lp_log_name"] && scorm_logs>priority){
-		frames["lp_log_name"].document.getElementById("log_content").innerHTML += "AICC: " + message + "<br/>";
-	}
-}
-/**
- * Logs information about LMS activity into the log frame
- * @param	string	Message to log
- * @param	integer Priority (0 for top priority, 3 for lowest)
- */
-function logit_lms(message,priority){
-	if(frames["lp_log_name"] && lms_logs>priority){
-		frames["lp_log_name"].document.getElementById("log_content").innerHTML += "LMS: " + message + "<br/>";
-	}
-}
-
-/**
- * update the Table Of Contents frame, by changing CSS styles, mostly
- * @param	string	Action to be taken
- * @param	integer	Item id to update
- */
-function update_toc(update_action,update_id)
-{
-	<?php if($oLP->mode != 'fullscreen'){ ?>
-		var myframe = frames["toc_name"];
-		var myelem = myframe.document.getElementById("toc_"+update_id);
-		var myelemimg = myframe.document.getElementById("toc_img_"+update_id);
-		logit_lms('update_toc('+update_action+','+update_id+')',2);
-		if(update_id != 0){
-			switch(update_action){
-				case 'unhighlight':
-					myelem.className = "scorm_item";
-					break;
-				case 'highlight':
-					myelem.className = "scorm_item_highlight";
-					break;
-				case 'not attempted':
-					if(myelemimg.src != '../img/notattempted.gif'){
-						myelemimg.src = "../img/notattempted.gif";
-						myelemimg.alt = "not attempted";
-					}
-					break;
-				case 'incomplete':
-					if(myelemimg.src != '../img/incomplete.gif'){
-						myelemimg.src = "../img/incomplete.gif";
-						myelemimg.alt = "incomplete";
-					}
-					break;
-				case 'completed':
-					if(myelemimg.src != '../img/completed.gif'){
-						myelemimg.src = "../img/completed.gif";
-						myelemimg.alt = "completed";
-					}
-					break;
-				case 'failed':
-					if(myelemimg.src != '../img/failed.gif'){
-						myelemimg.src = "../img/failed.gif";
-						myelemimg.alt = "failed";
-					}
-					break;
-				case 'passed':
-					if(myelemimg.src != '../img/completed.gif' && myelemimg.alt != 'passed'){
-						myelemimg.src = "../img/completed.gif";
-						myelemimg.alt = "passed";
-					}
-					break;
-				case 'browsed':
-					if(myelemimg.src != '../img/completed.gif' && myelemimg.alt != 'browsed'){
-						myelemimg.src = "../img/completed.gif";
-						myelemimg.alt = "browsed";
-					}
-					break;
-				default:
-					logit_lms('Update action unknown',2);
-					break;
-			}
-		}
-		return true;
-    <?php } ?>
-	return true;
-}
-/**
- * Updates the progress bar with the new status. Prevents the need of a page refresh and flickering
- * @param	integer	Number of completed items
- * @param	integer	Number of items in total
- * @param	string  Display mode (absolute 'abs' or percentage '%').Defaults to %
- */
-function update_progress_bar(nbr_complete, nbr_total, mode)
-{
-	logit_lms('update_progress_bar('+nbr_complete+','+nbr_total+','+mode+')',2);
-	logit_lms('could update with data: '+lms_lp_id+','+lms_view_id+','+lms_user_id,2);
-	var myframe = frames["nav_name"];
-	if(myframe){
-		if(mode == ''){mode='%';}
-		if(nbr_total == 0){nbr_total=1;}
-		var percentage = (nbr_complete/nbr_total)*100;
-		percentage = Math.round(percentage);
-		var pr_text  = myframe.document.getElementById('progress_text');
-		var pr_full  = myframe.document.getElementById('progress_img_full');
+ * - updating the frame src
+ */
+function load_item(item_id,url){
+	if(document.getElementById('content_id'))
+	{
+		logit_lms('Loading item '+item_id,2);
+		var cont_f = document.getElementById('content_id');
+		if(cont_f.src){
+			lms_old_item_id = lms_item_id;
+			var lms_new_item_id = item_id;
+			//load new content page into content frame
+			if(lms_lp_type==1 || lms_item_type=='asset'){
+				dokeos_save_asset();
+			}
+			cont_f.src = url;
+			update_toc('unhighlight',lms_old_item_id);
+			update_toc('highlight',item_id);
+			/* legacy code
+			lms_been_synchronized = 0;
+			lms_initialized = 0;
+			if(lms_lp_type==1 || lms_item_type=='asset'){
+				lms_item_id = lms_new_item_id;
+			}*/
+			return true;
+		}
+		logit_lms('cont_f.src has no properties',0);
+	}
+	logit_lms('content_id has no properties',0);
+	return false;
+}
+/**
+ * Save a Dokeos learnpath item's time and mark as completed upon
+ * leaving it
+ */
+function dokeos_save_asset(){
+    //var linkparams = 'id='+lms_item_id+'&score='+score+'&max='+max+'&min='+min+'&lesson_status='+lesson_status+'&time='+session_time+'&suspend_data='+suspend_data;
+    //var url = "<?php echo api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php' ?>?action=save&" + linkparams + "";
+	logit_lms('dokeos_save_asset: '+url,0);
+    //frames["message_name"].src = url;
+    xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location);
+}
+/**
+ * Logs information about SCORM messages into the log frame
+ * @param	string	Message to log
+ * @param	integer Priority (0 for top priority, 3 for lowest)
+ */
+function logit_scorm(message,priority){
+	if(frames["lp_log_name"] && scorm_logs>priority){
+		frames["lp_log_name"].document.getElementById("log_content").innerHTML += "AICC: " + message + "<br/>";
+	}
+}
+/**
+ * Logs information about LMS activity into the log frame
+ * @param	string	Message to log
+ * @param	integer Priority (0 for top priority, 3 for lowest)
+ */
+function logit_lms(message,priority){
+	if(frames["lp_log_name"] && lms_logs>priority){
+		frames["lp_log_name"].document.getElementById("log_content").innerHTML += "LMS: " + message + "<br/>";
+	}
+}
 
-		var pr_empty = myframe.document.getElementById('progress_img_empty');
-		pr_full.width = percentage;
-		pr_empty.width = 100-percentage;
-		var mytext = '';
-		switch(mode){
-			case 'abs':
-				mytext = nbr_complete + '/' + nbr_total;
-				break;
-			case '%':
-			default:
+/**
+ * update the Table Of Contents frame, by changing CSS styles, mostly
+ * @param	string	Action to be taken
+ * @param	integer	Item id to update
+ */
+function update_toc(update_action,update_id)
+{
+	<?php if($oLP->mode != 'fullscreen'){ ?>
+		var myframe = frames["toc_name"];
+		var myelem = myframe.document.getElementById("toc_"+update_id);
+		var myelemimg = myframe.document.getElementById("toc_img_"+update_id);
+		logit_lms('update_toc('+update_action+','+update_id+')',2);
+		if(update_id != 0){
+			switch(update_action){
+				case 'unhighlight':
+					myelem.className = "scorm_item";
+					break;
+				case 'highlight':
+					myelem.className = "scorm_item_highlight";
+					break;
+				case 'not attempted':
+					if(myelemimg.src != '../img/notattempted.gif'){
+						myelemimg.src = "../img/notattempted.gif";
+						myelemimg.alt = "not attempted";
+					}
+					break;
+				case 'incomplete':
+					if(myelemimg.src != '../img/incomplete.gif'){
+						myelemimg.src = "../img/incomplete.gif";
+						myelemimg.alt = "incomplete";
+					}
+					break;
+				case 'completed':
+					if(myelemimg.src != '../img/completed.gif'){
+						myelemimg.src = "../img/completed.gif";
+						myelemimg.alt = "completed";
+					}
+					break;
+				case 'failed':
+					if(myelemimg.src != '../img/failed.gif'){
+						myelemimg.src = "../img/failed.gif";
+						myelemimg.alt = "failed";
+					}
+					break;
+				case 'passed':
+					if(myelemimg.src != '../img/completed.gif' && myelemimg.alt != 'passed'){
+						myelemimg.src = "../img/completed.gif";
+						myelemimg.alt = "passed";
+					}
+					break;
+				case 'browsed':
+					if(myelemimg.src != '../img/completed.gif' && myelemimg.alt != 'browsed'){
+						myelemimg.src = "../img/completed.gif";
+						myelemimg.alt = "browsed";
+					}
+					break;
+				default:
+					logit_lms('Update action unknown',2);
+					break;
+			}
+		}
+		return true;
+    <?php } ?>
+	return true;
+}
+/**
+ * Updates the progress bar with the new status. Prevents the need of a page refresh and flickering
+ * @param	integer	Number of completed items
+ * @param	integer	Number of items in total
+ * @param	string  Display mode (absolute 'abs' or percentage '%').Defaults to %
+ */
+function update_progress_bar(nbr_complete, nbr_total, mode)
+{
+	logit_lms('update_progress_bar('+nbr_complete+','+nbr_total+','+mode+')',2);
+	logit_lms('could update with data: '+lms_lp_id+','+lms_view_id+','+lms_user_id,2);
+	var myframe = frames["nav_name"];
+	if(myframe){
+		if(mode == ''){mode='%';}
+		if(nbr_total == 0){nbr_total=1;}
+		var percentage = (nbr_complete/nbr_total)*100;
+		percentage = Math.round(percentage);
+		var pr_text  = myframe.document.getElementById('progress_text');
+		var pr_full  = myframe.document.getElementById('progress_img_full');
+
+		var pr_empty = myframe.document.getElementById('progress_img_empty');
+		pr_full.width = percentage;
+		pr_empty.width = 100-percentage;
+		var mytext = '';
+		switch(mode){
+			case 'abs':
+				mytext = nbr_complete + '/' + nbr_total;
+				break;
+			case '%':
+			default:
 				mytext = percentage + '%';
-				break;
-		}
-		pr_text.innerHTML = mytext;
-	}
-	return true;
-}
-function update_stats_page()
-{
-	var myframe = document.getElementById('content_id');
-	var mysrc = myframe.location.href;
-	if(mysrc == 'lp_controller.php?action=stats'){
-		if(myframe && myframe.src){
-			var mysrc = myframe.src;
-			myframe.src = mysrc;
-		}
-		// = mysrc; //refresh page
-	}
-	return true;
-}
-/**
- * Updates the message frame with the given string
- */
-function update_message_frame(msg_msg)
-{
-	if(msg_msg==null){msg_msg='';}
-	var msg_f = frames["message_name"];
-	if(!msg_f.document || !msg_f.document.getElementById('msg_div_id')){
-		logit_lms('In update_message_frame() - message frame has no document property',0);
-	}else{
-		logit_lms('In update_message_frame() - updating frame',0);
-		msg_f.document.getElementById('msg_div_id').innerHTML= msg_msg;
-	}
-}
-/**
- * Function that handles the saving of an item and switching from an item to another.
- * Once called, this function should be able to do the whole process of (1) saving the
+				break;
+		}
+		pr_text.innerHTML = mytext;
+	}
+	return true;
+}
+function update_stats_page()
+{
+	var myframe = document.getElementById('content_id');
+	var mysrc = myframe.location.href;
+	if(mysrc == 'lp_controller.php?action=stats'){
+		if(myframe && myframe.src){
+			var mysrc = myframe.src;
+			myframe.src = mysrc;
+		}
+		// = mysrc; //refresh page
+	}
+	return true;
+}
+/**
+ * Updates the message frame with the given string
+ */
+function update_message_frame(msg_msg)
+{
+	if(msg_msg==null){msg_msg='';}
+	var msg_f = frames["message_name"];
+	if(!msg_f.document || !msg_f.document.getElementById('msg_div_id')){
+		logit_lms('In update_message_frame() - message frame has no document property',0);
+	}else{
+		logit_lms('In update_message_frame() - updating frame',0);
+		msg_f.document.getElementById('msg_div_id').innerHTML= msg_msg;
+	}
+}
+/**
+ * Function that handles the saving of an item and switching from an item to another.
+ * Once called, this function should be able to do the whole process of (1) saving the
  * current item, (2) refresh all the values inside the SCORM API object, (3) open the
  * new item into the content_id frame, (4) refresh the table of contents, (5) refresh
- * the progress bar (completion), (6) refresh the message frame
- * @param	integer		Dokeos ID for the current item
+ * the progress bar (completion), (6) refresh the message frame
+ * @param	integer		Dokeos ID for the current item
  * @param	string		This parameter can be a string specifying the next
  *						item (like 'next', 'previous', 'first' or 'last') or the id to the next item
- */
-function switch_item(current_item, next_item){
-	/*
-	if(!current_item){
-		logit_lms('In switch - no current_item defined',0);
-	}
-	if(!next_item){
-		logit_lms('In switch - no next_item defined',0);
-	}
-	*/
-	if(lms_item_id == next_item){
-		return; //nothing to switch
-	}
-	//(1) save the current item
-	logit_lms('Called switch_item with params '+lms_item_id+' and '+next_item+'',0);
-	xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location);
+ */
+function switch_item(current_item, next_item){
+	/*
+	if(!current_item){
+		logit_lms('In switch - no current_item defined',0);
+	}
+	if(!next_item){
+		logit_lms('In switch - no next_item defined',0);
+	}
+	*/
+	if(lms_item_id == next_item){
+		return; //nothing to switch
+	}
+	//(1) save the current item
+	logit_lms('Called switch_item with params '+lms_item_id+' and '+next_item+'',0);
+	xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location);
 
-	//(2) Refresh all the values inside this SCORM API object - use AJAX
-	xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,next_item);
+	//(2) Refresh all the values inside this SCORM API object - use AJAX
+	xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,next_item);
 
-	//(3) open the new item in the content_id frame
-	var cont_f = document.getElementById('content_id');
-	if(!cont_f){logit_lms('In switch - content frame not found',0);return false;}
-	switch(next_item){
-		case 'next':
-			next_item = lms_next_item;
-			break;
-		case 'previous':
-			next_item = lms_previous_item;
-			break;
-		default:
-			break;
-	}
-	cont_f.src = 'lp_controller.php?action=content&lp_id='+lms_lp_id+'&item_id='+next_item;
+	//(3) open the new item in the content_id frame
+	var cont_f = document.getElementById('content_id');
+	if(!cont_f){logit_lms('In switch - content frame not found',0);return false;}
+	switch(next_item){
+		case 'next':
+			next_item = lms_next_item;
+			break;
+		case 'previous':
+			next_item = lms_previous_item;
+			break;
+		default:
+			break;
+	}
+	cont_f.src = 'lp_controller.php?action=content&lp_id='+lms_lp_id+'&item_id='+next_item;
 
-	//(4) refresh table of contents
-	/*
-	var toc_f = document.getElementById('toc_id');
-	if(!toc_f){logit_lms('In switch - toc frame not found',0);return false;}
-	var myrefresh = toc_f.src;
-	toc_f.src = myrefresh;
-	*/
+	//(4) refresh table of contents
+	/*
+	var toc_f = document.getElementById('toc_id');
+	if(!toc_f){logit_lms('In switch - toc frame not found',0);return false;}
+	var myrefresh = toc_f.src;
+	toc_f.src = myrefresh;
+	*/
 
-	//(5) refresh the progress bar
-	/*
-	var prg_f = document.getElementById('nav_id');
-	if(!prg_f){logit_lms('In switch - navigation frame not found',0);return false;}
-	var myrefresh = prg_f.src;
-	prg_f.src = myrefresh;
-	*/
+	//(5) refresh the progress bar
+	/*
+	var prg_f = document.getElementById('nav_id');
+	if(!prg_f){logit_lms('In switch - navigation frame not found',0);return false;}
+	var myrefresh = prg_f.src;
+	prg_f.src = myrefresh;
+	*/
 
-	//(6) refresh the message box (included in switch_item_details)
-	return true;
-}
-/**
- * Save a specific item (with its interactions, if any) into the LMS through
- * an AJAX call. Originally, we used the xajax library. Now we use jQuery.
- * Because of the need to pass an array, we have to build the parameters
- * manually into GET[]
- */
-function xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location, interactions, lms_item_core_exit) {
-        params='';
-        params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id;
-        params += '&iid='+lms_item_id+'&s='+score+'&max='+max+'&min='+min;
-        params += '&status='+lesson_status+'&t='+session_time;
-        params += '&suspend='+suspend_data+'&loc='+lesson_location;
-        params += '&core_exit='+lms_item_core_exit;
-        interact_string = '';
-        for (i in interactions){
-            interact_string += '&interact['+i+']=';
-            interact_temp = '[';
-            for (j in interactions[i]) {
-                interact_temp += interactions[i][j]+',';
-            }
-            interact_temp = interact_temp.substr(0,(interact_temp.length-2)) + ']';
-            interact_string += encodeURIComponent(interact_temp);
-        }
-        //interact_string = encodeURIComponent(interact_string.substr(0,(interact_string.length-1)));
-        params += interact_string;
-        /*params = {
-            'lid': lms_lp_id,
-            'uid': lms_user_id,
-            'vid': lms_view_id,
-            'iid': lms_item_id,
-            's': score,
-            'max': max,
-            'min': min,
+	//(6) refresh the message box (included in switch_item_details)
+	return true;
+}
+/**
+ * Save a specific item (with its interactions, if any) into the LMS through
+ * an AJAX call. Originally, we used the xajax library. Now we use jQuery.
+ * Because of the need to pass an array, we have to build the parameters
+ * manually into GET[]
+ */
+function xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location, interactions, lms_item_core_exit) {
+        params='';
+        params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id;
+        params += '&iid='+lms_item_id+'&s='+score+'&max='+max+'&min='+min;
+        params += '&status='+lesson_status+'&t='+session_time;
+        params += '&suspend='+suspend_data+'&loc='+lesson_location;
+        params += '&core_exit='+lms_item_core_exit;
+        interact_string = '';
+        for (i in interactions){
+            interact_string += '&interact['+i+']=';
+            interact_temp = '[';
+            for (j in interactions[i]) {
+                interact_temp += interactions[i][j]+',';
+            }
+            interact_temp = interact_temp.substr(0,(interact_temp.length-2)) + ']';
+            interact_string += encodeURIComponent(interact_temp);
+        }
+        //interact_string = encodeURIComponent(interact_string.substr(0,(interact_string.length-1)));
+        params += interact_string;
+        /*params = {
+            'lid': lms_lp_id,
+            'uid': lms_user_id,
+            'vid': lms_view_id,
+            'iid': lms_item_id,
+            's': score,
+            'max': max,
+            'min': min,
             'status': lesson_status,
             't': session_time,
-            'suspend': suspend_data,
-            'loc': lesson_location,
+            'suspend': suspend_data,
+            'loc': lesson_location,
             'interact': interac_string,
-            'core_exit': lms_item_core_exit
-        }
-        */
-        $.ajax({
-            type:"GET",
-            data: params,
+            'core_exit': lms_item_core_exit
+        }
+        */
+        $.ajax({
+            type:"GET",
+            data: params,
             url: "lp_ajax_save_item.php",
-            dataType: "script",
-            async: false
-            }
-        );
-}
-/**
- * Starts the timer with the server clock time.
- * Originally, we used the xajax library. Now we use jQuery
- */
-function xajax_start_timer() {
-    $.ajax({
-        type: "GET",
-        url: "lp_ajax_start_timer.php",
-        dataType: "script",
-        async: false
+            dataType: "script",
+            async: false
+            }
+        );
+}
+/**
+ * Starts the timer with the server clock time.
+ * Originally, we used the xajax library. Now we use jQuery
+ */
+function xajax_start_timer() {
+    $.ajax({
+        type: "GET",
+        url: "lp_ajax_start_timer.php",
+        dataType: "script",
+        async: false
+    });
+}
+/**
+ * Save a specific item's objectives into the LMS through
+ * an AJAX call. Originally, we used the xajax library. Now we use jQuery
+ */
+function xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,item_objectives) {
+        params='';
+        params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id;
+        params += '&iid='+lms_item_id;
+        obj_string = '';
+        for (i in item_objectives){
+            obj_string += '&objectives['+i+']=';
+            obj_temp = '[';
+            for (j in item_objectives[i]) {
+                obj_temp += item_objectives[i][j]+',';
+            }
+            obj_temp = obj_temp.substr(0,(obj_temp.length-2)) + ']';
+            obj_string += encodeURIComponent(obj_temp);
+        }
+        params += obj_string;
+        $.ajax({
+            type: "GET",
+            data: params,
+            url: "lp_ajax_save_objectives.php",
+            dataType: "script",
+            async: false
+        });
+}
+/**
+ * Switch between two items through
+ * an AJAX call. Originally, we used the xajax library. Now we use jQuery
+ */
+function xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,next_item) {
+    params = {
+        'lid': lms_lp_id,
+        'uid': lms_user_id,
+        'vid': lms_view_id,
+        'iid': lms_item_id,
+        'next': next_item
+    }
+    $.ajax({
+        type: "GET",
+        data: params,
+        url: "lp_ajax_switch_item.php",
+        dataType: "script",
+        async: false
     });
-}
-/**
- * Save a specific item's objectives into the LMS through
- * an AJAX call. Originally, we used the xajax library. Now we use jQuery
- */
-function xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,item_objectives) {
-        params='';
-        params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id;
-        params += '&iid='+lms_item_id;
-        obj_string = '';
-        for (i in item_objectives){
-            obj_string += '&objectives['+i+']=';
-            obj_temp = '[';
-            for (j in item_objectives[i]) {
-                obj_temp += item_objectives[i][j]+',';
-            }
-            obj_temp = obj_temp.substr(0,(obj_temp.length-2)) + ']';
-            obj_string += encodeURIComponent(obj_temp);
-        }
-        params += obj_string;
-        $.ajax({
-            type: "GET",
-            data: params,
-            url: "lp_ajax_save_objectives.php",
-            dataType: "script",
-            async: false
-        });
-}
-/**
- * Switch between two items through
- * an AJAX call. Originally, we used the xajax library. Now we use jQuery
- */
-function xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,next_item) {
-    params = {
-        'lid': lms_lp_id,
-        'uid': lms_user_id,
-        'vid': lms_view_id,
-        'iid': lms_item_id,
-        'next': next_item
-    }
-    $.ajax({
-        type: "GET",
-        data: params,
-        url: "lp_ajax_switch_item.php",
-        dataType: "script",
-        async: false
-    });
-}
+}
 addEvent(window,'load',addListeners,false);

+ 230 - 230
main/newscorm/aicc_hacp.php

@@ -1,245 +1,245 @@
 <?php // $Id: $
-/**
+/**
 ==============================================================================
-*	API event handler functions for AICC / CMIv4 in HACP communication mode
-*
-*	@author   Denes Nagy <darkden@freemail.hu>
-*   @author   Yannick Warnier <ywarnier@beeznest.org>
-*	@version  v 1.0
-*	@access   public
-*	@package  dokeos.learnpath
-* 	@license	GNU/GPL - See Dokeos license directory for details
+*	API event handler functions for AICC / CMIv4 in HACP communication mode
+*
+*	@author   Denes Nagy <darkden@freemail.hu>
+*   @author   Yannick Warnier <ywarnier@beeznest.org>
+*	@version  v 1.0
+*	@access   public
+*	@package  dokeos.learnpath
+* 	@license	GNU/GPL - See Dokeos license directory for details
 ==============================================================================
-*/
-/**
+*/
+/**
  * This script is divided into three sections.
- * The first section (below) is the initialisation part.
- * The second section is the AICC object part
- * The third section defines the event handlers for Dokeos' internal messaging
- * and frames refresh
+ * The first section (below) is the initialisation part.
+ * The second section is the AICC object part
+ * The third section defines the event handlers for Dokeos' internal messaging
+ * and frames refresh
  *
- * This script implements the HACP messaging for AICC. The API messaging is
- * made by another set of scripts.
+ * This script implements the HACP messaging for AICC. The API messaging is
+ * made by another set of scripts.
  *
- * Rules for HACP processing of one AU
- * Rule #1 The first HACP message issued must be a GetParam
- * Rule #2 The last HACP message issued must be an ExitAU
- * Rule #3 At least one PutParam message must be issued prior to an ExitAU message
- * Rule #4 No HACP messages can be issued after a successfully issued ExitAU message
+ * Rules for HACP processing of one AU
+ * Rule #1 The first HACP message issued must be a GetParam
+ * Rule #2 The last HACP message issued must be an ExitAU
+ * Rule #3 At least one PutParam message must be issued prior to an ExitAU message
+ * Rule #4 No HACP messages can be issued after a successfully issued ExitAU message
  *
- * Only suspend_data and core.lesson_location should be sent updated to a late GetParam
- * request. All other params should be as when the AU was launched.
- */
-/*
+ * Only suspend_data and core.lesson_location should be sent updated to a late GetParam
+ * request. All other params should be as when the AU was launched.
+ */
+/*
 ==============================================================================
-	   INIT SECTION
+	   INIT SECTION
 ==============================================================================
 */
-$debug = 0;
-
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-//Use session ID as provided by the request
-if(!empty($_REQUEST['aicc_sid']))
-{
-	session_id($_REQUEST['aicc_sid']);
-	if($debug>1){error_log('New LP - '.__FILE__.','.__LINE__.' - reusing session ID '.$_REQUEST['aicc_sid'],0);}
-}
-//Load common libraries using a compatibility script to bridge between 1.6 and 1.8
+$debug = 0;
+
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+//Use session ID as provided by the request
+if(!empty($_REQUEST['aicc_sid']))
+{
+	session_id($_REQUEST['aicc_sid']);
+	if($debug>1){error_log('New LP - '.__FILE__.','.__LINE__.' - reusing session ID '.$_REQUEST['aicc_sid'],0);}
+}
+//Load common libraries using a compatibility script to bridge between 1.6 and 1.8
 require_once('back_compat.inc.php');
-if($debug>2){error_log('New LP - '.__FILE__.','.__LINE__.' - Current session ID: '.session_id(),0);}
-//Load learning path libraries so we can use the objects to define the initial values
-//of the API
-require_once('learnpath.class.php');
-require_once('learnpathItem.class.php');
-require_once('aicc.class.php');
-
-// Is this needed? This is probabaly done in the header file
-//$_user							= $_SESSION['_user'];
-$file							= $_SESSION['file'];
-$oLP							= unserialize($_SESSION['lpobject']);
-$oItem 							=& $oLP->items[$oLP->current];
-if(!is_object($oItem)){
-	error_log('New LP - aicc_hacp - Could not load oItem item',0);
-	exit;
-}
-$autocomplete_when_80pct = 0;
-
-$result = array(
-	'core'=>array(),
-	'core_lesson'=>array(),
-	'core_vendor'=>array(),
-	'evaluation'=>array(),
-	'student_data'=>array(),
-);
-$convert_enc = array('%25','%0D','%0A','%09','%20','%2D','%2F','%3B','%3F','%7B','%7D','%7C','%5C','%5E','%7E','%5B','%5D','%60','%23','%3E','%3C','%22');
-$convert_dec = array('%',"\r","\n","\t",' ','-','/',';','?','{','}','|','\\','^','~','[',']','`','#','>','<','"');
-$crlf = "\r\n";
-$tab = "\t";
-$s_ec = 'error='; //string for error code
-$s_et = 'error_text='; //string for error text
-$s_ad = 'aicc_data='; //string for aicc_data
-
-$errors = array(0=>'Successful',1=>'Invalid Command',2=>'Invalid AU password',3=>'Invalid Session ID');
-
-$error_code = 0;
-$error_text = '';
-$aicc_data = '';
-$result = '';
-//GET REQUEST
-if(!empty($_REQUEST['command']))
-{
-	//error_log('In '.__FILE__.', '.__LINE__.' - request is '.$_REQUEST['command'],0);
-	switch(strtolower($_REQUEST['command']))
-	{
-		case 'getparam':
-			//request for all available data to be printed out in the answer
-			if(!empty($_REQUEST['version'])){
-				$hacp_version = learnpath::escape_string($_REQUEST['version']);
-			}
-			if(!empty($_REQUEST['session_id'])){
-				$hacp_session_id = learnpath::escape_string($_REQUEST['session_id']);
-			}
-			$error_code = 0;
-			$error_text = $errors[$error_code];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
-			$result .= '[Core]'.$crlf;
-			$result .= $tab.'Student_ID='.$_user['user_id'].$crlf;
-			$result .= $tab.'Student_Name='.api_get_person_name($_user['firstName'], $_user['lastName']).$crlf;
-			$result .= $tab.'Lesson_Location='.$oItem->get_lesson_location().$crlf;
-			$result .= $tab.'Credit='.$oItem->get_credit().$crlf;
-			$result .= $tab.'Lesson_Status='.$oItem->get_status().$crlf;
-			$result .= $tab.'Score='.$oItem->get_score().$crlf;
-			$result .= $tab.'Time='.$oItem->get_scorm_time('js').$crlf;
-			$result .= $tab.'Lesson_Mode='.$oItem->get_lesson_mode().$crlf;
-			$result .= '[Core_Lesson]'.$crlf;
-			$result .= $oItem->get_suspend_data().$crlf;
-			$result .= '[Core_Vendor]'.$crlf;
-			$result .= $oItem->get_launch_data.$crlf;
-			$result .= '[Comments]'.$crlf;
-			$result .= $crlf;
-			$result .= '[Evaluation]'.$crlf;
-			$result .= $tab.'Course_ID={'.api_get_course_id().'}'.$crlf;
-			//$result .= '[Objectives_Status]'.$crlf;
-			$result .= '[Student_Data]'.$crlf;
-			$result .= $tab.'Mastery_Score='.$oItem->masteryscore.$crlf;
-			//$result .= '[Student_Demographics]'.$crlf;
-			//$result .= '[Student_Preferences]'.$crlf;
+if($debug>2){error_log('New LP - '.__FILE__.','.__LINE__.' - Current session ID: '.session_id(),0);}
+//Load learning path libraries so we can use the objects to define the initial values
+//of the API
+require_once('learnpath.class.php');
+require_once('learnpathItem.class.php');
+require_once('aicc.class.php');
+
+// Is this needed? This is probabaly done in the header file
+//$_user							= $_SESSION['_user'];
+$file							= $_SESSION['file'];
+$oLP							= unserialize($_SESSION['lpobject']);
+$oItem 							=& $oLP->items[$oLP->current];
+if(!is_object($oItem)){
+	error_log('New LP - aicc_hacp - Could not load oItem item',0);
+	exit;
+}
+$autocomplete_when_80pct = 0;
+
+$result = array(
+	'core'=>array(),
+	'core_lesson'=>array(),
+	'core_vendor'=>array(),
+	'evaluation'=>array(),
+	'student_data'=>array(),
+);
+$convert_enc = array('%25','%0D','%0A','%09','%20','%2D','%2F','%3B','%3F','%7B','%7D','%7C','%5C','%5E','%7E','%5B','%5D','%60','%23','%3E','%3C','%22');
+$convert_dec = array('%',"\r","\n","\t",' ','-','/',';','?','{','}','|','\\','^','~','[',']','`','#','>','<','"');
+$crlf = "\r\n";
+$tab = "\t";
+$s_ec = 'error='; //string for error code
+$s_et = 'error_text='; //string for error text
+$s_ad = 'aicc_data='; //string for aicc_data
+
+$errors = array(0=>'Successful',1=>'Invalid Command',2=>'Invalid AU password',3=>'Invalid Session ID');
+
+$error_code = 0;
+$error_text = '';
+$aicc_data = '';
+$result = '';
+//GET REQUEST
+if(!empty($_REQUEST['command']))
+{
+	//error_log('In '.__FILE__.', '.__LINE__.' - request is '.$_REQUEST['command'],0);
+	switch(strtolower($_REQUEST['command']))
+	{
+		case 'getparam':
+			//request for all available data to be printed out in the answer
+			if(!empty($_REQUEST['version'])){
+				$hacp_version = learnpath::escape_string($_REQUEST['version']);
+			}
+			if(!empty($_REQUEST['session_id'])){
+				$hacp_session_id = learnpath::escape_string($_REQUEST['session_id']);
+			}
+			$error_code = 0;
+			$error_text = $errors[$error_code];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
+			$result .= '[Core]'.$crlf;
+			$result .= $tab.'Student_ID='.$_user['user_id'].$crlf;
+			$result .= $tab.'Student_Name='.api_get_person_name($_user['firstName'], $_user['lastName']).$crlf;
+			$result .= $tab.'Lesson_Location='.$oItem->get_lesson_location().$crlf;
+			$result .= $tab.'Credit='.$oItem->get_credit().$crlf;
+			$result .= $tab.'Lesson_Status='.$oItem->get_status().$crlf;
+			$result .= $tab.'Score='.$oItem->get_score().$crlf;
+			$result .= $tab.'Time='.$oItem->get_scorm_time('js').$crlf;
+			$result .= $tab.'Lesson_Mode='.$oItem->get_lesson_mode().$crlf;
+			$result .= '[Core_Lesson]'.$crlf;
+			$result .= $oItem->get_suspend_data().$crlf;
+			$result .= '[Core_Vendor]'.$crlf;
+			$result .= $oItem->get_launch_data.$crlf;
+			$result .= '[Comments]'.$crlf;
+			$result .= $crlf;
+			$result .= '[Evaluation]'.$crlf;
+			$result .= $tab.'Course_ID={'.api_get_course_id().'}'.$crlf;
+			//$result .= '[Objectives_Status]'.$crlf;
+			$result .= '[Student_Data]'.$crlf;
+			$result .= $tab.'Mastery_Score='.$oItem->masteryscore.$crlf;
+			//$result .= '[Student_Demographics]'.$crlf;
+			//$result .= '[Student_Preferences]'.$crlf;
 
-			//error_log('Returning message: '.$result,0);
-			$result = str_replace($convert_dec,$convert_enc,$result);
-			//error_log('Returning message (encoded): '.$result,0);
-			break;
-		case 'putparam':
-			$hacp_version = '';
-			$hacp_session_id = '';
-			$hacp_aicc_data = '';
-			foreach($_REQUEST as $name => $value)
-			{
-				//escape the value as described in the AICC documentation p170
-				switch(strtolower($name))
-				{
-					case 'version':
-						$hacp_version = $value;
-						break;
-					case 'session_id':
-						$hacp_session_id = $value;
-						break;
-					case 'aicc_data':
-						//error_log('In '.__FILE__.', '.__LINE__.' - aicc data before translation is '.$value,0);
-						$value = str_replace('+',' ',$value);
-						$value = str_replace($convert_enc,$convert_dec,$value);
+			//error_log('Returning message: '.$result,0);
+			$result = str_replace($convert_dec,$convert_enc,$result);
+			//error_log('Returning message (encoded): '.$result,0);
+			break;
+		case 'putparam':
+			$hacp_version = '';
+			$hacp_session_id = '';
+			$hacp_aicc_data = '';
+			foreach($_REQUEST as $name => $value)
+			{
+				//escape the value as described in the AICC documentation p170
+				switch(strtolower($name))
+				{
+					case 'version':
+						$hacp_version = $value;
+						break;
+					case 'session_id':
+						$hacp_session_id = $value;
+						break;
+					case 'aicc_data':
+						//error_log('In '.__FILE__.', '.__LINE__.' - aicc data before translation is '.$value,0);
+						$value = str_replace('+',' ',$value);
+						$value = str_replace($convert_enc,$convert_dec,$value);
 						$hacp_aicc_data = $value;
-						break;
-				}
-			}
-			//error_log('In '.__FILE__.', '.__LINE__.' - aicc data is '.$hacp_aicc_data,0);
-			//treat the incoming request:
-			$msg_array = aicc::parse_ini_string_quotes_safe($hacp_aicc_data,array('core_lesson','core_vendor'));
-			//error_log('Message is now in this form: '.print_r($msg_array,true),0);
-			foreach($msg_array as $key=>$dummy){
-				switch (strtolower($key)){
-					case 'core':
-						foreach($msg_array[$key] as $subkey => $value){
-							switch(strtolower($subkey)){
-								case 'lesson_location':
-									//error_log('Setting lesson_location to '.$value,0);
-									$oItem->set_lesson_location($value);
-									break;
-								case 'lesson_status':
-									//error_log('Setting lesson_status to '.$value,0);
-									$oItem->set_status($value);
-									break;
-								case 'score':
-									//error_log('Setting lesson_score to '.$value,0);
-									$oItem->set_score($value);
-									break;
-								case 'time':
-									//error_log('Setting lesson_time to '.$value,0);
-									$oItem->set_time($value);
-									break;
-							}
-						}
-						break;
-					case 'core_lesson':
-						//error_log('Setting suspend_data to '.print_r($msg_array[$key],true),0);
-						$oItem->current_data = $msg_array[$key];
-						break;
-					case 'comments':
-						break;
-					case 'objectives_status':
-						break;
-					case 'student_data':
-						break;
-					case 'student_preferences':
-						break;
-				}
-			}
+						break;
+				}
+			}
+			//error_log('In '.__FILE__.', '.__LINE__.' - aicc data is '.$hacp_aicc_data,0);
+			//treat the incoming request:
+			$msg_array = aicc::parse_ini_string_quotes_safe($hacp_aicc_data,array('core_lesson','core_vendor'));
+			//error_log('Message is now in this form: '.print_r($msg_array,true),0);
+			foreach($msg_array as $key=>$dummy){
+				switch (strtolower($key)){
+					case 'core':
+						foreach($msg_array[$key] as $subkey => $value){
+							switch(strtolower($subkey)){
+								case 'lesson_location':
+									//error_log('Setting lesson_location to '.$value,0);
+									$oItem->set_lesson_location($value);
+									break;
+								case 'lesson_status':
+									//error_log('Setting lesson_status to '.$value,0);
+									$oItem->set_status($value);
+									break;
+								case 'score':
+									//error_log('Setting lesson_score to '.$value,0);
+									$oItem->set_score($value);
+									break;
+								case 'time':
+									//error_log('Setting lesson_time to '.$value,0);
+									$oItem->set_time($value);
+									break;
+							}
+						}
+						break;
+					case 'core_lesson':
+						//error_log('Setting suspend_data to '.print_r($msg_array[$key],true),0);
+						$oItem->current_data = $msg_array[$key];
+						break;
+					case 'comments':
+						break;
+					case 'objectives_status':
+						break;
+					case 'student_data':
+						break;
+					case 'student_preferences':
+						break;
+				}
+			}
 
-			$error_code = 0;
-			$error_text = $errors[$error_code];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
-			$oItem->save(false);
-			break;
-		case 'putcomments':
-			$error_code = 0;
-			$error_text = $errors[$error_code];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
-			break;
-		case 'putobjectives':
-			$error_code = 0;
-			$error_text = $errors[$error_code];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
-			break;
-		case 'putpath':
-			$error_code = 0;
-			$error_text = $errors[$error_code];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
-			break;
-		case 'putinteractions':
-			$error_code = 0;
-			$error_text = $errors[$error_code];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
-			break;
-		case 'putperformance':
-			$error_code = 0;
-			$error_text = $errors[$error_code];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
-			break;
-		case 'exitau':
-			$error_code = 0;
-			$error_text = $errors[$error_code];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
-			break;
-		default:
-			$error_code = 1;
-			$error_text = $errors[1];
-			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf;
-	}
-}
-$_SESSION['lpobject'] = serialize($oLP);
-//content type must be text/plain
-header('Content-type: text/plain');
-echo $result;
+			$error_code = 0;
+			$error_text = $errors[$error_code];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
+			$oItem->save(false);
+			break;
+		case 'putcomments':
+			$error_code = 0;
+			$error_text = $errors[$error_code];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
+			break;
+		case 'putobjectives':
+			$error_code = 0;
+			$error_text = $errors[$error_code];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
+			break;
+		case 'putpath':
+			$error_code = 0;
+			$error_text = $errors[$error_code];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
+			break;
+		case 'putinteractions':
+			$error_code = 0;
+			$error_text = $errors[$error_code];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
+			break;
+		case 'putperformance':
+			$error_code = 0;
+			$error_text = $errors[$error_code];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
+			break;
+		case 'exitau':
+			$error_code = 0;
+			$error_text = $errors[$error_code];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf.$s_ad.$crlf;
+			break;
+		default:
+			$error_code = 1;
+			$error_text = $errors[1];
+			$result = $s_ec.$error_code.$crlf.$s_et.$error_text.$crlf;
+	}
+}
+$_SESSION['lpobject'] = serialize($oLP);
+//content type must be text/plain
+header('Content-type: text/plain');
+echo $result;
 ?>

+ 14 - 14
main/newscorm/back_compat.inc.php

@@ -1,16 +1,16 @@
-<?php //$id: $
-/**
+<?php //$id: $
+/**
  * This script used to allow compatibility between the New SCORM tool and both
- * version 1.6.3 and 1.8 of Dokeos by loading libraries in a different way.
- * The switch is now deprecated and this file will be renamed later on to
- * something like lp_includes.inc.php
- * @package dokeos.learnpath
- */
-require_once('../inc/global.inc.php');
-require_once(api_get_path(LIBRARY_PATH) . 'database.lib.php');
-require_once(api_get_path(LIBRARY_PATH) . 'document.lib.php');
-require_once(api_get_path(LIBRARY_PATH) . 'fileDisplay.lib.php');
-require_once(api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php'); //replace_dangerous_char()
-require_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php'); //check_name_exists()
-require_once(api_get_path(LIBRARY_PATH) . 'pclzip/pclzip.lib.php');
+ * version 1.6.3 and 1.8 of Dokeos by loading libraries in a different way.
+ * The switch is now deprecated and this file will be renamed later on to
+ * something like lp_includes.inc.php
+ * @package dokeos.learnpath
+ */
+require_once('../inc/global.inc.php');
+require_once(api_get_path(LIBRARY_PATH) . 'database.lib.php');
+require_once(api_get_path(LIBRARY_PATH) . 'document.lib.php');
+require_once(api_get_path(LIBRARY_PATH) . 'fileDisplay.lib.php');
+require_once(api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php'); //replace_dangerous_char()
+require_once(api_get_path(LIBRARY_PATH) . 'fileManage.lib.php'); //check_name_exists()
+require_once(api_get_path(LIBRARY_PATH) . 'pclzip/pclzip.lib.php');
 ?>

+ 43 - 43
main/newscorm/blank.php

@@ -1,46 +1,46 @@
-<?php //$id: $
-/**
- * Script that displays a blank page (with later a message saying why)
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-
-
-$language_file[] = "learnpath";
-
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-require('../inc/global.inc.php');
-include_once('../inc/reduced_header.inc.php');
-
-?>
-
-<body>
-
-<?php
-
-if (isset($_GET['error'])) {
-	switch($_GET['error']){
-		case 'document_deleted':
-			echo '<br /><br />';
-			Display::display_error_message(get_lang('DocumentHasBeenDeleted'));
-			break;
+<?php //$id: $
+/**
+ * Script that displays a blank page (with later a message saying why)
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+
+
+$language_file[] = "learnpath";
+
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+require('../inc/global.inc.php');
+include_once('../inc/reduced_header.inc.php');
+
+?>
+
+<body>
+
+<?php
+
+if (isset($_GET['error'])) {
+	switch($_GET['error']){
+		case 'document_deleted':
+			echo '<br /><br />';
+			Display::display_error_message(get_lang('DocumentHasBeenDeleted'));
+			break;
 		case 'prerequisites':
 			echo '<br /><br />';
-			Display::display_normal_message(get_lang('_prereq_not_complete'));
-			break;
-		default:
-			break;
-	}
-} else if(isset($_GET['msg']) && $_GET['msg']=='exerciseFinished') {
-	echo '<br /><br />';
-	Display::display_normal_message(get_lang('ExerciseFinished'));
-}
-?>
-
-</body>
+			Display::display_normal_message(get_lang('_prereq_not_complete'));
+			break;
+		default:
+			break;
+	}
+} else if(isset($_GET['msg']) && $_GET['msg']=='exerciseFinished') {
+	echo '<br /><br />';
+	Display::display_normal_message(get_lang('ExerciseFinished'));
+}
+?>
+
+</body>
 </html>

+ 51 - 51
main/newscorm/content_makers.inc.php

@@ -1,51 +1,51 @@
-<?php //$id: $
-/**
- * The only usage of this script is to have a portable way of keeping the list of content makers
- * @package dokeos.learnpath
- * @author Yannick Warnier <yannick.warnier@dokeos.com>
- */
-/**
- * Script
- */
-  $content_origins = array(
-	"--".get_lang('GenericScorm')."--",
-	"--".get_lang('Other')."--",
-	'Accent',
-	'Accenture',
-	'ADLNet',
-  	'Articulate',
-  	'ATutor',
-  	'Blackboard',
-  	'Calfat',
-  	'Captivate',
-  	'Claroline',
-	'Commest',
-	'Coursebuilder',
-	'Docent',
-	'Dokeos',
-	'Dreamweaver',
-	'Easyquiz',
-	'e-doceo',
-	'ENI Editions',
-	'Explio',
-	'Flash',
-	'HTML',
-	'HotPotatoes',
-	'Hyperoffice',
-	'Ingenatic',
-	'Instruxion',
-	'iProgress',
-	'Lectora',
-	'Microsoft',
-	'Onlineformapro',
-	'Opikanoba',
-	'Plantyn',
-	'Saba',
-	'Skillsoft',
-	'Speechi',
-	'Thomson-NETg',
-	'U&I Learning',
-    'Udutu',
-	'WebCT'
-  );
-?>
+<?php //$id: $
+/**
+ * The only usage of this script is to have a portable way of keeping the list of content makers
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <yannick.warnier@dokeos.com>
+ */
+/**
+ * Script
+ */
+  $content_origins = array(
+	"--".get_lang('GenericScorm')."--",
+	"--".get_lang('Other')."--",
+	'Accent',
+	'Accenture',
+	'ADLNet',
+  	'Articulate',
+  	'ATutor',
+  	'Blackboard',
+  	'Calfat',
+  	'Captivate',
+  	'Claroline',
+	'Commest',
+	'Coursebuilder',
+	'Docent',
+	'Dokeos',
+	'Dreamweaver',
+	'Easyquiz',
+	'e-doceo',
+	'ENI Editions',
+	'Explio',
+	'Flash',
+	'HTML',
+	'HotPotatoes',
+	'Hyperoffice',
+	'Ingenatic',
+	'Instruxion',
+	'iProgress',
+	'Lectora',
+	'Microsoft',
+	'Onlineformapro',
+	'Opikanoba',
+	'Plantyn',
+	'Saba',
+	'Skillsoft',
+	'Speechi',
+	'Thomson-NETg',
+	'U&I Learning',
+    'Udutu',
+	'WebCT'
+  );
+?>

+ 39 - 39
main/newscorm/display_audiorecorder.php

@@ -1,43 +1,43 @@
-<?php //$id: $
-// This file is part of the Dokeos software - See license and credits in the documentation/ directory
-/**
- * Script opened in an iframe and containing the learning path's table of contents
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
+<?php //$id: $
+// This file is part of the Dokeos software - See license and credits in the documentation/ directory
+/**
+ * Script opened in an iframe and containing the learning path's table of contents
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
 $use_anonymous = true;
-require_once('back_compat.inc.php');
-require_once('learnpath.class.php');
-require_once('scorm.class.php');
-require_once('aicc.class.php');
-
-if(isset($_SESSION['lpobject']))
-{
-	$oLP = unserialize($_SESSION['lpobject']);
-	if(is_object($oLP)){
-		$_SESSION['oLP'] = $oLP;
-	}else{
-		die('Could not instanciate lp object');
-	}
-}
-$charset = $_SESSION['oLP']->encoding;
-
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-$scorm_css_header=true;
-include_once('../inc/reduced_header.inc.php');
-echo '<html>
+require_once('back_compat.inc.php');
+require_once('learnpath.class.php');
+require_once('scorm.class.php');
+require_once('aicc.class.php');
+
+if(isset($_SESSION['lpobject']))
+{
+	$oLP = unserialize($_SESSION['lpobject']);
+	if(is_object($oLP)){
+		$_SESSION['oLP'] = $oLP;
+	}else{
+		die('Could not instanciate lp object');
+	}
+}
+$charset = $_SESSION['oLP']->encoding;
+
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+$scorm_css_header=true;
+include_once('../inc/reduced_header.inc.php');
+echo '<html>
 		<body>';
 
-		echo '<div id="audiorecorder">	';
-		$audio_recorder_studentview = 'true';
-		$audio_recorder_item_id = $_SESSION['oLP']->current;
-		if(api_get_setting('service_visio','active')=='true'){
-			include('audiorecorder.inc.php');
-		}
-		echo '</div>';
-		// end of audiorecorder include
-
-echo '</body></html>';
+		echo '<div id="audiorecorder">	';
+		$audio_recorder_studentview = 'true';
+		$audio_recorder_item_id = $_SESSION['oLP']->current;
+		if(api_get_setting('service_visio','active')=='true'){
+			include('audiorecorder.inc.php');
+		}
+		echo '</div>';
+		// end of audiorecorder include
+
+echo '</body></html>';
 ?>

+ 470 - 470
main/newscorm/document.php

@@ -1,471 +1,471 @@
-<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
-==============================================================================
-*/
-
-/**
-==============================================================================
-* This file was origially the copy of document.php, but many modifications happened since then ;
-* the direct file view is not any more needed, if the user uploads a scorm zip file, a directory
-* will be automatically created for it, and the files will be uncompressed there for example ;
-*
-* @package dokeos.learnpath
-* @author Yannick Warnier <ywarnier@beeznest.org>
-==============================================================================
-*/
-/**
- * Script
- */
-// name of the language file that needs to be included
-$language_file = "scormdocument";
-
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-require('back_compat.inc.php');
-include('learnpath_functions.inc.php');
-include_once('scorm.lib.php');
-$courseDir   = api_get_course_path().'/scorm';
-$baseWordDir = $courseDir;
-
-require_once('learnpathList.class.php');
-require_once('learnpath.class.php');
-require_once('learnpathItem.class.php');
-
-// storing the tables names in variables.
-$tbl_document           = Database::get_course_table(TABLE_SCORMDOC);
-$tbl_learnpath_main     = Database::get_course_table(TABLE_LEARNPATH_MAIN);
-$tbl_tool               = Database::get_course_table(TABLE_TOOL_LIST);
-
-$default_visibility="v";
-$show_description_field=0;
-
-/**
- * Display initialisation and security checks
- */
-//extra javascript functions for in html head:
-$htmlHeadXtra[] =
-"<script language='javascript' type='text/javascript'>
-function confirmation(name)
-{
-	if (confirm(\" ".trim(get_lang('AreYouSureToDelete'))." ?\"))
-		{return true;}
-	else
+<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
+==============================================================================
+*/
+
+/**
+==============================================================================
+* This file was origially the copy of document.php, but many modifications happened since then ;
+* the direct file view is not any more needed, if the user uploads a scorm zip file, a directory
+* will be automatically created for it, and the files will be uncompressed there for example ;
+*
+* @package dokeos.learnpath
+* @author Yannick Warnier <ywarnier@beeznest.org>
+==============================================================================
+*/
+/**
+ * Script
+ */
+// name of the language file that needs to be included
+$language_file = "scormdocument";
+
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+require('back_compat.inc.php');
+include('learnpath_functions.inc.php');
+include_once('scorm.lib.php');
+$courseDir   = api_get_course_path().'/scorm';
+$baseWordDir = $courseDir;
+
+require_once('learnpathList.class.php');
+require_once('learnpath.class.php');
+require_once('learnpathItem.class.php');
+
+// storing the tables names in variables.
+$tbl_document           = Database::get_course_table(TABLE_SCORMDOC);
+$tbl_learnpath_main     = Database::get_course_table(TABLE_LEARNPATH_MAIN);
+$tbl_tool               = Database::get_course_table(TABLE_TOOL_LIST);
+
+$default_visibility="v";
+$show_description_field=0;
+
+/**
+ * Display initialisation and security checks
+ */
+//extra javascript functions for in html head:
+$htmlHeadXtra[] =
+"<script language='javascript' type='text/javascript'>
+function confirmation(name)
+{
+	if (confirm(\" ".trim(get_lang('AreYouSureToDelete'))." ?\"))
+		{return true;}
+	else
 		{return false;}
-}
-</script>";
-
-// Define the 'doc.inc.php' as language file
-//$nameTools = get_lang("Doc");
-
-// When GET['learnpath_id'] is defined, it means that
-// a learnpath has been chosen, so we redirect to
-// learnpath_handler - we possibly lose the $dialogBox warning here
-if(!empty($_GET['learnpath_id']))
-{
-	header('location:../learnpath/learnpath_handler.php?'
-		.'learnpath_id='.$_GET['learnpath_id']);
-	exit();
-}
-
-event_access_tool(TOOL_LEARNPATH);
-
-if (! $is_allowed_in_course) api_not_allowed();
-
-/**
- * Now checks have been done, prepare the data to be displayed
- */
-if(!empty($openDir))
-{
-  //prevent going higher than allowed in the hierarchy
-  //if the requested dir is found inside the base course dir, use course dir
-  //error_log($courseDir." against ".$openDir,0);
-  if((strstr($courseDir,$openDir)===false) and (strstr($openDir,'.')===false) ){
-  	$curDirPath = $openDir;
-  }else{
-  	$curDirPath = $courseDir;
-  }
-}
-else
-{
-  $curDirPath= $courseDir;
-}
-if ($curDirPath == "/" || $curDirPath == "\\" || strstr($curDirPath, ".."))
-{
-  $curDirPath =""; // manage the root directory problem
-  /*
-   * The strstr($curDirPath, "..") prevent malicious users to go to the root directory
-   */
-}
-
-$curDirName = basename($curDirPath);
-$parentDir  = dirname($curDirPath);
-
-if ($parentDir == "/" || $parentDir == "\\")
-{
-  $parentDir =""; // manage the root directory problem
-}
-
-
-/* Search infos in the DB about the current directory the user is in */
-
-$result = mysql_query ("SELECT * FROM $tbl_document
-				WHERE path LIKE    '".$curDirPath."/%'
-				AND   path NOT LIKE '".$curDirPath."/%/%'");
-
-if ($result) while($row = mysql_fetch_array($result, MYSQL_ASSOC))
-{
-  $attribute['path'      ][] = $row['path'      ];
-  $attribute['visibility'][] = $row['visibility'];
-  $attribute['comment'   ][] = $row['comment'   ];
-}
-
-$fileList = get_scorm_paths_from_dir($baseWorkDir.$curDirPath,$attribute);
-if(!isset($fileList)){
-	die("<center>
-	   <b>Wrong directory !</b>
-	   <br> Please contact your platform administrator.
-	   </center>");
-}
-/*
- * Sort alphabetically the File list
- */
-
-if (is_array($fileList) && count($fileList)>0)
-{
-  array_multisort($fileList['type'], $fileList['name'],
-		 $fileList['size'], $fileList['date'],
-		 $fileList['comment'],$fileList['visibility']);
-}
-/*----------------------------------------
-	CHECK BASE INTEGRITY
---------------------------------------*/
-/* commented until we know what it's for
-if ( is_array($attribute) && ( count($attribute['path']) > 0 ) )
-{
-  $queryClause = ' WHERE path IN ( "'.implode('" , "' , $attribute['path']).'" )';
-
-  Database::query("DELETE FROM $tbl_document ".$queryClause,__FILE__,__LINE__);
-
-  Database::query("DELETE FROM $tbl_document WHERE comment LIKE '' AND visibility LIKE 'v'",__FILE__,__LINE__);
-  // The second query clean the DB 'in case of' empty records (no comment an visibility=v)
-  // These kind of records should'nt be there, but we never know...
-
-}	// end if sizeof($attribute['path']) > 0
-*/
-
-unset($attribute);
-
-
-/**
- * Display
- */
-Display::display_header($nameTools,"Path");
-$dspCurDirName = htmlentities($curDirName);
-$cmdCurDirPath = rawurlencode($curDirPath);
-$cmdParentDir  = rawurlencode($parentDir);
-
-$ob_string = '';
-
-api_display_tool_title($nameTools);
-
-/*
------------------------------------------------------------
-	Introduction section
-	(editable by course admins)
------------------------------------------------------------
-*/
-
-if($my_version=='1.8'){
-	Display::display_introduction_section(TOOL_LEARNPATH);
-}else{
-	api_introductionsection(TOOL_LEARNPATH);
-}
-
-
-if(api_is_allowed_to_edit())
-{
-   /*--------------------------------------
-      UPLOAD SECTION - displays file upload box
-     --------------------------------------*/
-
-  echo	"<!-- upload  -->",
-	"<p align=\"right\">",
-	"<form action=\"".api_get_self()."?openDir=", rawurlencode($openDir),
-		"&subdirs=$subdirs\" method=\"post\" enctype=\"multipart/form-data\">",
-		"<input type=\"hidden\" name=\"uploadPath\" value=\"$curDirPath\" />",
-		get_lang('DownloadFile'),"&nbsp;:&nbsp;",
-		"<input type=\"file\" name=\"userFile\" />",
-		"<input type=\"submit\" value=\"".get_lang('Download')."\" />&nbsp;",
-		"</p></form>";
-
-  /*--------------------------------------
-    DIALOG BOX SECTION
-    --------------------------------------*/
-
-  if ($dialogBox)
-  {
-    Display::display_normal_message($dialogBox);
-  }
-
-  echo	"<table border='0' cellspacing='2' cellpadding='4'>
-    <tr>
-      <td valign='bottom'>
-        <a href='".api_get_self()."?action=add'>",
-	"<img src='../img/scormbuilder.gif' border=\"0\" align=\"absmiddle\" alt='scormbuilder' />".get_lang('_add_learnpath')."</a>
-      </td>",
-      "<td valign='bottom'>&nbsp;&nbsp;&nbsp;<a href='".api_get_self()."?createDir=$cmdCurDirPath'>",
-      "<img src=\"../img/dossier.gif\" border=\"0\" align=\"absmiddle\" />",
-	"",get_lang("CreateDir"),"</a>
-      </td>
-    </tr>
-  </table>";
-
-
-}
-
-echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" class='data_table'>";
-api_is_allowed_to_edit() ? $colspan = 9 : $colspan = 3;
-
-if ($curDirName) /* if the $curDirName is empty, we're in the root point
-   				 and we can't go to a parent dir */
-{
-  ?>
-  <!-- parent dir -->
-  <a href="<?php echo api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdParentDir.'&subdirs=yes'; ?>">
-  <img src="../img/folder_up.gif" border="0" align="absbottom" hspace="5" alt="parent" />
-  <?php echo get_lang("Up"); ?></a>&nbsp;
-  <?php
-}
-
-if ($curDirPath)
-{
-  if(substr($curDirPath,1,1)=='/'){
-  	$tmpcurDirPath=substr($curDirPath,1,strlen($curDirPath));
-  }else{
-  	$tmpcurDirPath = $curDirPath;
-  }
-  ?>
-  <!-- current dir name -->
-  <tr>
-    <td colspan="<?php echo $colspan ?>" align="left" bgcolor="#4171B5">
-      <img src="../img/opendir.gif" align="absbottom" vspace="2" hspace="3" alt="open_dir" />
-      <?php echo $tmpcurDirPath ?>
-    </td>
-  </tr>
-  <?php
-}
-
-/* CURRENT DIRECTORY */
-
-echo	"<tr bgcolor=\"$color2\" align=\"center\" valign=\"top\">";
-echo	"<td width='290'><b>",get_lang("Name"),"</b></td>\n",
-	 "<td><b>",get_lang("Description"),"</b></td>\n";
-if (api_is_allowed_to_edit())
-{
-  echo "<td><b>",get_lang("ExportShort"),"</b></td>\n",
-	"<td width='200'><b>",get_lang("Modify"),"</b></td>\n";
-}
-
-echo		"</tr>\n";
-
-/*--------------------------------------
-	  DISPLAY SCORM LIST
-  --------------------------------------*/
-if ($fileList)
-{
-  $counter=0;
-  while (list($fileKey, $fileName) = each ($fileList['name']))
-  {
-    $counter++;
-    if (($counter % 2)==0) { $oddclass="row_odd"; } else { $oddclass="row_even"; }
-
-    if ($fileList['type'][$fileKey] == A_FILE) continue;  // RH: added
-    $dspFileName = htmlentities($fileName);
-    $cmdFileName = rawurlencode($curDirPath."/".$fileName);
-    if ($fileList['visibility'][$fileKey] == "i")
-    {
-      if (api_is_allowed_to_edit())
-      {
-        $style=" class='invisible'";
-      }
-      else
-      {
-	continue; // skip the display of this file
-      }
-    }
-    else
-    {
-      $style="";
-    }
-    $manifestRoute = $baseWorkDir.$curDirPath."/".$fileName.'/imsmanifest.xml';
-    $plantyndir1 = $baseWorkDir.$curDirPath."/".$fileName.'/LMS';
-    $plantyndir2 = $baseWorkDir.$curDirPath."/".$fileName.'/REF';
-    $plantyndir3 = $baseWorkDir.$curDirPath."/".$fileName.'/SCO';
-    $aiccdir = $baseWorkDir.$curDirPath."/".$fileName.'/aicc';
-    $indexRoute1 = $indexRoute2 = $indexRouteA = '';
-    if ((file_exists($plantyndir1)) and (file_exists($plantyndir2)) and (file_exists($plantyndir3))) {
-      $indexRoute1 = $baseWorkDir.$curDirPath."/".$fileName.'/index.htm';
-      $indexRoute2 = $baseWorkDir.$curDirPath."/".$fileName.'/index.html';
-    }
-    if (file_exists($aiccdir)) {
-      $indexRouteA = $baseWorkDir.$curDirPath."/".$fileName.'/start.htm';
-    }
-
-    if (file_exists($indexRoute1)) {
-      $urlFileName = api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdFileName.'&indexRoute=index.htm';
-      $image="<img src=\"./../img/scorm_logo.gif\" border=\"0\" align=\"absmiddle\" alt='scorm' />";
-    } elseif (file_exists($indexRoute2)) {
-      $urlFileName = api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdFileName.'&indexRoute=index.html';
-      $image="<img src=\"./../img/scorm_logo.gif\" border=\"0\" align=\"absmiddle\" alt='scorm'>";
-    } elseif (file_exists($indexRouteA)) {
-      $urlFileName = api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdFileName.'&indexRoute=start.htm';
-      $image="<img src=\"./../img/scorm_logo.gif\" border=\"0\" align=\"absmiddle\" alt='scorm'>";
-    } elseif (file_exists($manifestRoute)) {
-      $urlFileName = api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdFileName;
-      $image="<img src=\"./../img/scorm_logo.gif\" border=\"0\" align=\"absmiddle\" alt='scorm'>";
-    } else {
-      $urlFileName = api_get_self().'?'.api_get_cidreq().'&subdirs=yes&openDir='.$cmdFileName;
-      $image="<img src=\"../img/dossier.gif\" border=\"0\"  hspace=\"3\" align=\"absmiddle\" alt='scorm'>";
-    }
-
-    if ($curDirPath) {
-      $sqlpath=$curDirPath."/".$fileList['name'][$fileKey]."";
-    } else {
-      $sqlpath="/".$fileList['name'][$fileKey]."";
-    }
-    $sql="SELECT name FROM $tbl_document WHERE ((path='$sqlpath') and (filetype='folder'))";
-    $result=Database::query($sql,__FILE__,__LINE__);
-    $row=mysql_fetch_array($result);
-    if ($row['name']) { $name=$row['name']; } else { $name=$dspFileName; }
-    echo	"<tr align=\"center\"", " class=".$oddclass.">\n",
-        	"<td align=\"left\" valign='middle'>&nbsp;",
-		"<a href=\"".$urlFileName."\" ".$style.">",
-		"",$image,"</a>&nbsp;<a href=\"".$urlFileName."\" ".$style.">",$name,"</a>",
-		"</td>\n";
-
-    /* NB : Before tracking implementation the url above was simply
-     * "<a href=\"",$urlFileName,"\"",$style,">"
-     */
-    $desc=$fileList['comment'][$fileKey];
-    /* DESCRIPTION */
-    echo 	"<td>$desc",
-        "</td>\n";
-    if(api_is_allowed_to_edit())
-    {
-      $fileExtension=explode('.',$dspFileName);
-      $fileExtension=strtolower($fileExtension[sizeof($fileExtension)-1]);
-
-     /* export */
-
-     echo "<td align='center'><a href='".api_get_self()."?action=exportscorm&".api_get_cidreq()."&path=".$cmdFileName."'><img src=\"../img/save_zip.gif\" border=\"0\" title=\"".get_lang('Export')."\"></a>";
-
-     /* edit title and description */
-
-      echo "<td align='center'>",
-	"<a href='".api_get_self()."?action=editscorm&path=".$cmdFileName."'><img src=\"../img/edit.gif\" border=\"0\" title=\"".get_lang('_edit_learnpath')."\"></a>";
-
-      /* DELETE COMMAND */
-      echo
-	"<a href=\"".api_get_self()."?delete=",$cmdFileName,"\" ",
-	"onClick=\"return confirmation('",addslashes($dspFileName),"');\">",
-	"<img src=\"../img/delete.gif\" border=\"0\" title=\"".get_lang('_delete_learnpath')."\" />",
-	"</a>";
-
-      /* VISIBILITY COMMAND */
-
-      if ($fileList['visibility'][$fileKey] == "i")
-      {
-        echo	"<a href=\"".api_get_self()."?make_directory_visible=",$cmdFileName,"\">",
-	  "<img src=\"../img/invisible.gif\" border=\"0\" title=\"".get_lang('_publish')."\" />",
-	  "</a>";
-      }
-      else
-      {
-        echo	"<a href=\"".api_get_self()."?make_directory_invisible=",$cmdFileName,"\">",
-	  "<img src=\"../img/visible.gif\" border=\"0\" title=\"".get_lang('_no_publish')."\" />",
-	  "</a>";
-      }
-
-    }	// end if($is_allowedToEdit)
-    echo	"</tr>\n";
-
-  }	// end each ($fileList)
-}// end if ( $fileList)
-
-//display learning paths
-
-if (!$curDirPath) {
-
-  echo "<tr><td colspan='4'>&nbsp;</td></tr>";
-  $sql="select * from $tbl_learnpath_main";
-  $result=Database::query($sql,__FILE__,__LINE__);
-  $counter=0;
-  while ($row=mysql_fetch_array($result)) {
-    $counter++;
-    if (($counter % 2)==0) { $oddclass="row_odd"; } else { $oddclass="row_even"; }
-
-    $id=$row["learnpath_id"];
-    $sql2="SELECT * FROM $tbl_learnpath_main where learnpath_id=$id";
-    $result2=Database::query($sql2,__FILE__,__LINE__);
-    $row2=mysql_fetch_array($result2);
-    $name=$row2['learnpath_name'];
-    $sql3="SELECT * FROM $tbl_tool where (name=\"$name\" and image='scormbuilder.gif')";
-    $result3=Database::query($sql3,__FILE__,__LINE__);
-    $row3=mysql_fetch_array($result3);
-    if ((api_is_allowed_to_edit()) or ((!api_is_allowed_to_edit()) and ($row3["visibility"] == '1'))) {
-      $row['learnpath_name']=str_replace(' ','&nbsp;',$row['learnpath_name']);
-      if ($row3["visibility"] != '1') { $style=' class="invisible"'; } else { $style=''; }
-      echo "<tr align=\"center\" class=".$oddclass.">\n",
-	  "<td align='left'>&nbsp;",
-	  "<a href=\"../learnpath/learnpath_handler.php?".api_get_cidreq()."&learnpath_id={$row['learnpath_id']}\" $style>",
-	  "<img src='../img/scormbuilder.gif' border=\"0\"  alt='scormbuilder'></a>&nbsp;",
-	  "<a href=\"../learnpath/learnpath_handler.php?".api_get_cidreq()."&learnpath_id={$row['learnpath_id']}\" $style>{$row['learnpath_name']}</a></td>",
-	  "<td>&nbsp;{$row['learnpath_description']}</td>";
-    }
-    if(api_is_allowed_to_edit()) {
-      //no init of $circle1 here
-      echo "<td align='center'><a href='".api_get_self()."?action=exportpath&id=".$row["learnpath_id"]."'><img src=\"../img/save_zip.gif\" border=\"0\" title=\"".get_lang('Export')."\"></a>";
-
-      echo "<td align='center'><a href='".api_get_self()."?action=editpath&id=".$row["learnpath_id"]."'><img src=\"../img/edit.gif\" border=\"0\" title=\"".get_lang('_edit_learnpath')."\"></a>";
-
-      echo "<a href='".api_get_self()."?action=deletepath&id=".$row["learnpath_id"]."'><img src=\"../img/delete.gif\" border=\"0\" title=\"".get_lang('_delete_learnpath')."\" onClick=\"return confirmation('".$row2['learnpath_name']."');\"></a>";
-
-      if (($row3["visibility"])=='1') {
-        echo "<a href='".api_get_self()."?action=publishpath&set_visibility=i&id=".$row["learnpath_id"]."'><img src=\"../img/visible.gif\" border=\"0\" alt=\"".get_lang('_no_publish')."\" title=\"".get_lang('_no_publish')."\"></a>";
-      } else {
-        echo "<a href='".api_get_self()."?action=publishpath&set_visibility=v&id=".$row["learnpath_id"]."'><img 	src=\"../img/invisible.gif\" border=\"0\" alt=\"".get_lang('_publish')."\" title=\"".get_lang('_publish')."\"></a>";
-      }
-      echo "</td>";
-    }
-    echo		"</tr>";
-  }
-}
-echo "</table>";
-// echo "</div>"; /* *** end of the div opened earlier, if needed then uncomment*/
-
-echo "<br/><br/>";
-/*
-==============================================================================
-  FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+}
+</script>";
+
+// Define the 'doc.inc.php' as language file
+//$nameTools = get_lang("Doc");
+
+// When GET['learnpath_id'] is defined, it means that
+// a learnpath has been chosen, so we redirect to
+// learnpath_handler - we possibly lose the $dialogBox warning here
+if(!empty($_GET['learnpath_id']))
+{
+	header('location:../learnpath/learnpath_handler.php?'
+		.'learnpath_id='.$_GET['learnpath_id']);
+	exit();
+}
+
+event_access_tool(TOOL_LEARNPATH);
+
+if (! $is_allowed_in_course) api_not_allowed();
+
+/**
+ * Now checks have been done, prepare the data to be displayed
+ */
+if(!empty($openDir))
+{
+  //prevent going higher than allowed in the hierarchy
+  //if the requested dir is found inside the base course dir, use course dir
+  //error_log($courseDir." against ".$openDir,0);
+  if((strstr($courseDir,$openDir)===false) and (strstr($openDir,'.')===false) ){
+  	$curDirPath = $openDir;
+  }else{
+  	$curDirPath = $courseDir;
+  }
+}
+else
+{
+  $curDirPath= $courseDir;
+}
+if ($curDirPath == "/" || $curDirPath == "\\" || strstr($curDirPath, ".."))
+{
+  $curDirPath =""; // manage the root directory problem
+  /*
+   * The strstr($curDirPath, "..") prevent malicious users to go to the root directory
+   */
+}
+
+$curDirName = basename($curDirPath);
+$parentDir  = dirname($curDirPath);
+
+if ($parentDir == "/" || $parentDir == "\\")
+{
+  $parentDir =""; // manage the root directory problem
+}
+
+
+/* Search infos in the DB about the current directory the user is in */
+
+$result = mysql_query ("SELECT * FROM $tbl_document
+				WHERE path LIKE    '".$curDirPath."/%'
+				AND   path NOT LIKE '".$curDirPath."/%/%'");
+
+if ($result) while($row = mysql_fetch_array($result, MYSQL_ASSOC))
+{
+  $attribute['path'      ][] = $row['path'      ];
+  $attribute['visibility'][] = $row['visibility'];
+  $attribute['comment'   ][] = $row['comment'   ];
+}
+
+$fileList = get_scorm_paths_from_dir($baseWorkDir.$curDirPath,$attribute);
+if(!isset($fileList)){
+	die("<center>
+	   <b>Wrong directory !</b>
+	   <br> Please contact your platform administrator.
+	   </center>");
+}
+/*
+ * Sort alphabetically the File list
+ */
+
+if (is_array($fileList) && count($fileList)>0)
+{
+  array_multisort($fileList['type'], $fileList['name'],
+		 $fileList['size'], $fileList['date'],
+		 $fileList['comment'],$fileList['visibility']);
+}
+/*----------------------------------------
+	CHECK BASE INTEGRITY
+--------------------------------------*/
+/* commented until we know what it's for
+if ( is_array($attribute) && ( count($attribute['path']) > 0 ) )
+{
+  $queryClause = ' WHERE path IN ( "'.implode('" , "' , $attribute['path']).'" )';
+
+  Database::query("DELETE FROM $tbl_document ".$queryClause,__FILE__,__LINE__);
+
+  Database::query("DELETE FROM $tbl_document WHERE comment LIKE '' AND visibility LIKE 'v'",__FILE__,__LINE__);
+  // The second query clean the DB 'in case of' empty records (no comment an visibility=v)
+  // These kind of records should'nt be there, but we never know...
+
+}	// end if sizeof($attribute['path']) > 0
+*/
+
+unset($attribute);
+
+
+/**
+ * Display
+ */
+Display::display_header($nameTools,"Path");
+$dspCurDirName = htmlentities($curDirName);
+$cmdCurDirPath = rawurlencode($curDirPath);
+$cmdParentDir  = rawurlencode($parentDir);
+
+$ob_string = '';
+
+api_display_tool_title($nameTools);
+
+/*
+-----------------------------------------------------------
+	Introduction section
+	(editable by course admins)
+-----------------------------------------------------------
+*/
+
+if($my_version=='1.8'){
+	Display::display_introduction_section(TOOL_LEARNPATH);
+}else{
+	api_introductionsection(TOOL_LEARNPATH);
+}
+
+
+if(api_is_allowed_to_edit())
+{
+   /*--------------------------------------
+      UPLOAD SECTION - displays file upload box
+     --------------------------------------*/
+
+  echo	"<!-- upload  -->",
+	"<p align=\"right\">",
+	"<form action=\"".api_get_self()."?openDir=", rawurlencode($openDir),
+		"&subdirs=$subdirs\" method=\"post\" enctype=\"multipart/form-data\">",
+		"<input type=\"hidden\" name=\"uploadPath\" value=\"$curDirPath\" />",
+		get_lang('DownloadFile'),"&nbsp;:&nbsp;",
+		"<input type=\"file\" name=\"userFile\" />",
+		"<input type=\"submit\" value=\"".get_lang('Download')."\" />&nbsp;",
+		"</p></form>";
+
+  /*--------------------------------------
+    DIALOG BOX SECTION
+    --------------------------------------*/
+
+  if ($dialogBox)
+  {
+    Display::display_normal_message($dialogBox);
+  }
+
+  echo	"<table border='0' cellspacing='2' cellpadding='4'>
+    <tr>
+      <td valign='bottom'>
+        <a href='".api_get_self()."?action=add'>",
+	"<img src='../img/scormbuilder.gif' border=\"0\" align=\"absmiddle\" alt='scormbuilder' />".get_lang('_add_learnpath')."</a>
+      </td>",
+      "<td valign='bottom'>&nbsp;&nbsp;&nbsp;<a href='".api_get_self()."?createDir=$cmdCurDirPath'>",
+      "<img src=\"../img/dossier.gif\" border=\"0\" align=\"absmiddle\" />",
+	"",get_lang("CreateDir"),"</a>
+      </td>
+    </tr>
+  </table>";
+
+
+}
+
+echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" class='data_table'>";
+api_is_allowed_to_edit() ? $colspan = 9 : $colspan = 3;
+
+if ($curDirName) /* if the $curDirName is empty, we're in the root point
+   				 and we can't go to a parent dir */
+{
+  ?>
+  <!-- parent dir -->
+  <a href="<?php echo api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdParentDir.'&subdirs=yes'; ?>">
+  <img src="../img/folder_up.gif" border="0" align="absbottom" hspace="5" alt="parent" />
+  <?php echo get_lang("Up"); ?></a>&nbsp;
+  <?php
+}
+
+if ($curDirPath)
+{
+  if(substr($curDirPath,1,1)=='/'){
+  	$tmpcurDirPath=substr($curDirPath,1,strlen($curDirPath));
+  }else{
+  	$tmpcurDirPath = $curDirPath;
+  }
+  ?>
+  <!-- current dir name -->
+  <tr>
+    <td colspan="<?php echo $colspan ?>" align="left" bgcolor="#4171B5">
+      <img src="../img/opendir.gif" align="absbottom" vspace="2" hspace="3" alt="open_dir" />
+      <?php echo $tmpcurDirPath ?>
+    </td>
+  </tr>
+  <?php
+}
+
+/* CURRENT DIRECTORY */
+
+echo	"<tr bgcolor=\"$color2\" align=\"center\" valign=\"top\">";
+echo	"<td width='290'><b>",get_lang("Name"),"</b></td>\n",
+	 "<td><b>",get_lang("Description"),"</b></td>\n";
+if (api_is_allowed_to_edit())
+{
+  echo "<td><b>",get_lang("ExportShort"),"</b></td>\n",
+	"<td width='200'><b>",get_lang("Modify"),"</b></td>\n";
+}
+
+echo		"</tr>\n";
+
+/*--------------------------------------
+	  DISPLAY SCORM LIST
+  --------------------------------------*/
+if ($fileList)
+{
+  $counter=0;
+  while (list($fileKey, $fileName) = each ($fileList['name']))
+  {
+    $counter++;
+    if (($counter % 2)==0) { $oddclass="row_odd"; } else { $oddclass="row_even"; }
+
+    if ($fileList['type'][$fileKey] == A_FILE) continue;  // RH: added
+    $dspFileName = htmlentities($fileName);
+    $cmdFileName = rawurlencode($curDirPath."/".$fileName);
+    if ($fileList['visibility'][$fileKey] == "i")
+    {
+      if (api_is_allowed_to_edit())
+      {
+        $style=" class='invisible'";
+      }
+      else
+      {
+	continue; // skip the display of this file
+      }
+    }
+    else
+    {
+      $style="";
+    }
+    $manifestRoute = $baseWorkDir.$curDirPath."/".$fileName.'/imsmanifest.xml';
+    $plantyndir1 = $baseWorkDir.$curDirPath."/".$fileName.'/LMS';
+    $plantyndir2 = $baseWorkDir.$curDirPath."/".$fileName.'/REF';
+    $plantyndir3 = $baseWorkDir.$curDirPath."/".$fileName.'/SCO';
+    $aiccdir = $baseWorkDir.$curDirPath."/".$fileName.'/aicc';
+    $indexRoute1 = $indexRoute2 = $indexRouteA = '';
+    if ((file_exists($plantyndir1)) and (file_exists($plantyndir2)) and (file_exists($plantyndir3))) {
+      $indexRoute1 = $baseWorkDir.$curDirPath."/".$fileName.'/index.htm';
+      $indexRoute2 = $baseWorkDir.$curDirPath."/".$fileName.'/index.html';
+    }
+    if (file_exists($aiccdir)) {
+      $indexRouteA = $baseWorkDir.$curDirPath."/".$fileName.'/start.htm';
+    }
+
+    if (file_exists($indexRoute1)) {
+      $urlFileName = api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdFileName.'&indexRoute=index.htm';
+      $image="<img src=\"./../img/scorm_logo.gif\" border=\"0\" align=\"absmiddle\" alt='scorm' />";
+    } elseif (file_exists($indexRoute2)) {
+      $urlFileName = api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdFileName.'&indexRoute=index.html';
+      $image="<img src=\"./../img/scorm_logo.gif\" border=\"0\" align=\"absmiddle\" alt='scorm'>";
+    } elseif (file_exists($indexRouteA)) {
+      $urlFileName = api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdFileName.'&indexRoute=start.htm';
+      $image="<img src=\"./../img/scorm_logo.gif\" border=\"0\" align=\"absmiddle\" alt='scorm'>";
+    } elseif (file_exists($manifestRoute)) {
+      $urlFileName = api_get_self().'?'.api_get_cidreq().'&openDir='.$cmdFileName;
+      $image="<img src=\"./../img/scorm_logo.gif\" border=\"0\" align=\"absmiddle\" alt='scorm'>";
+    } else {
+      $urlFileName = api_get_self().'?'.api_get_cidreq().'&subdirs=yes&openDir='.$cmdFileName;
+      $image="<img src=\"../img/dossier.gif\" border=\"0\"  hspace=\"3\" align=\"absmiddle\" alt='scorm'>";
+    }
+
+    if ($curDirPath) {
+      $sqlpath=$curDirPath."/".$fileList['name'][$fileKey]."";
+    } else {
+      $sqlpath="/".$fileList['name'][$fileKey]."";
+    }
+    $sql="SELECT name FROM $tbl_document WHERE ((path='$sqlpath') and (filetype='folder'))";
+    $result=Database::query($sql,__FILE__,__LINE__);
+    $row=mysql_fetch_array($result);
+    if ($row['name']) { $name=$row['name']; } else { $name=$dspFileName; }
+    echo	"<tr align=\"center\"", " class=".$oddclass.">\n",
+        	"<td align=\"left\" valign='middle'>&nbsp;",
+		"<a href=\"".$urlFileName."\" ".$style.">",
+		"",$image,"</a>&nbsp;<a href=\"".$urlFileName."\" ".$style.">",$name,"</a>",
+		"</td>\n";
+
+    /* NB : Before tracking implementation the url above was simply
+     * "<a href=\"",$urlFileName,"\"",$style,">"
+     */
+    $desc=$fileList['comment'][$fileKey];
+    /* DESCRIPTION */
+    echo 	"<td>$desc",
+        "</td>\n";
+    if(api_is_allowed_to_edit())
+    {
+      $fileExtension=explode('.',$dspFileName);
+      $fileExtension=strtolower($fileExtension[sizeof($fileExtension)-1]);
+
+     /* export */
+
+     echo "<td align='center'><a href='".api_get_self()."?action=exportscorm&".api_get_cidreq()."&path=".$cmdFileName."'><img src=\"../img/save_zip.gif\" border=\"0\" title=\"".get_lang('Export')."\"></a>";
+
+     /* edit title and description */
+
+      echo "<td align='center'>",
+	"<a href='".api_get_self()."?action=editscorm&path=".$cmdFileName."'><img src=\"../img/edit.gif\" border=\"0\" title=\"".get_lang('_edit_learnpath')."\"></a>";
+
+      /* DELETE COMMAND */
+      echo
+	"<a href=\"".api_get_self()."?delete=",$cmdFileName,"\" ",
+	"onClick=\"return confirmation('",addslashes($dspFileName),"');\">",
+	"<img src=\"../img/delete.gif\" border=\"0\" title=\"".get_lang('_delete_learnpath')."\" />",
+	"</a>";
+
+      /* VISIBILITY COMMAND */
+
+      if ($fileList['visibility'][$fileKey] == "i")
+      {
+        echo	"<a href=\"".api_get_self()."?make_directory_visible=",$cmdFileName,"\">",
+	  "<img src=\"../img/invisible.gif\" border=\"0\" title=\"".get_lang('_publish')."\" />",
+	  "</a>";
+      }
+      else
+      {
+        echo	"<a href=\"".api_get_self()."?make_directory_invisible=",$cmdFileName,"\">",
+	  "<img src=\"../img/visible.gif\" border=\"0\" title=\"".get_lang('_no_publish')."\" />",
+	  "</a>";
+      }
+
+    }	// end if($is_allowedToEdit)
+    echo	"</tr>\n";
+
+  }	// end each ($fileList)
+}// end if ( $fileList)
+
+//display learning paths
+
+if (!$curDirPath) {
+
+  echo "<tr><td colspan='4'>&nbsp;</td></tr>";
+  $sql="select * from $tbl_learnpath_main";
+  $result=Database::query($sql,__FILE__,__LINE__);
+  $counter=0;
+  while ($row=mysql_fetch_array($result)) {
+    $counter++;
+    if (($counter % 2)==0) { $oddclass="row_odd"; } else { $oddclass="row_even"; }
+
+    $id=$row["learnpath_id"];
+    $sql2="SELECT * FROM $tbl_learnpath_main where learnpath_id=$id";
+    $result2=Database::query($sql2,__FILE__,__LINE__);
+    $row2=mysql_fetch_array($result2);
+    $name=$row2['learnpath_name'];
+    $sql3="SELECT * FROM $tbl_tool where (name=\"$name\" and image='scormbuilder.gif')";
+    $result3=Database::query($sql3,__FILE__,__LINE__);
+    $row3=mysql_fetch_array($result3);
+    if ((api_is_allowed_to_edit()) or ((!api_is_allowed_to_edit()) and ($row3["visibility"] == '1'))) {
+      $row['learnpath_name']=str_replace(' ','&nbsp;',$row['learnpath_name']);
+      if ($row3["visibility"] != '1') { $style=' class="invisible"'; } else { $style=''; }
+      echo "<tr align=\"center\" class=".$oddclass.">\n",
+	  "<td align='left'>&nbsp;",
+	  "<a href=\"../learnpath/learnpath_handler.php?".api_get_cidreq()."&learnpath_id={$row['learnpath_id']}\" $style>",
+	  "<img src='../img/scormbuilder.gif' border=\"0\"  alt='scormbuilder'></a>&nbsp;",
+	  "<a href=\"../learnpath/learnpath_handler.php?".api_get_cidreq()."&learnpath_id={$row['learnpath_id']}\" $style>{$row['learnpath_name']}</a></td>",
+	  "<td>&nbsp;{$row['learnpath_description']}</td>";
+    }
+    if(api_is_allowed_to_edit()) {
+      //no init of $circle1 here
+      echo "<td align='center'><a href='".api_get_self()."?action=exportpath&id=".$row["learnpath_id"]."'><img src=\"../img/save_zip.gif\" border=\"0\" title=\"".get_lang('Export')."\"></a>";
+
+      echo "<td align='center'><a href='".api_get_self()."?action=editpath&id=".$row["learnpath_id"]."'><img src=\"../img/edit.gif\" border=\"0\" title=\"".get_lang('_edit_learnpath')."\"></a>";
+
+      echo "<a href='".api_get_self()."?action=deletepath&id=".$row["learnpath_id"]."'><img src=\"../img/delete.gif\" border=\"0\" title=\"".get_lang('_delete_learnpath')."\" onClick=\"return confirmation('".$row2['learnpath_name']."');\"></a>";
+
+      if (($row3["visibility"])=='1') {
+        echo "<a href='".api_get_self()."?action=publishpath&set_visibility=i&id=".$row["learnpath_id"]."'><img src=\"../img/visible.gif\" border=\"0\" alt=\"".get_lang('_no_publish')."\" title=\"".get_lang('_no_publish')."\"></a>";
+      } else {
+        echo "<a href='".api_get_self()."?action=publishpath&set_visibility=v&id=".$row["learnpath_id"]."'><img 	src=\"../img/invisible.gif\" border=\"0\" alt=\"".get_lang('_publish')."\" title=\"".get_lang('_publish')."\"></a>";
+      }
+      echo "</td>";
+    }
+    echo		"</tr>";
+  }
+}
+echo "</table>";
+// echo "</div>"; /* *** end of the div opened earlier, if needed then uncomment*/
+
+echo "<br/><br/>";
+/*
+==============================================================================
+  FOOTER
+==============================================================================
+*/
+Display::display_footer();
+?>

+ 16 - 16
main/newscorm/index.php

@@ -1,16 +1,16 @@
-<?php //$id: $
-/**
- * Redirection script
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-require('back_compat.inc.php');
-header('location: lp_controller.php?'.api_get_cidReq().'&action=list');
-?>
+<?php //$id: $
+/**
+ * Redirection script
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+require('back_compat.inc.php');
+header('location: lp_controller.php?'.api_get_cidReq().'&action=list');
+?>

+ 2338 - 2338
main/newscorm/learnpathItem.class.php

@@ -1,2471 +1,2471 @@
-<?php //$id:$
-/**
- * This file contains the lp_item class, that inherits from the learnpath class
- * @package	dokeos.learnpath
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
- * lp_item defines items belonging to a learnpath. Each item has a name, a score, a use time and additional
- * information that enables tracking a user's progress in a learning path
- * @package	dokeos.learnpath
- */
-class learnpathItem{
-	var $attempt_id; //also called "objectives" SCORM-wise
-    var $audio; //the path to an audio file (stored in document/audio/)
-	var $children = array(); //contains the ids of children items
-	var $condition; //if this item has a special condition embedded
-	var $current_score;
-	var $current_start_time;
-	var $current_stop_time;
-	var $current_data = '';
-	var $db_id;
-	var $db_item_view_id = '';
-	var $description = '';
-	var $file;
-	//at the moment, interactions are just an array of arrays with a structure of 8 text fields
-	//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
-	var $interactions = array();
-	var $interactions_count = 0;
-	var $objectives = array();
-	var $objectives_count = 0;
-	var $launch_data = '';
-	var $lesson_location = '';
-	var $level = 0;
-	//var $location; //only set this for SCORM?
-	var $lp_id;
-	var $max_score;
-	var $mastery_score;
-	var $min_score;
-	var $max_time_allowed = '';
-	var $name;
-	var $next;
-	var $parent;
-	var $path;
-	var $possible_status = array('not attempted','incomplete','completed','passed','failed','browsed');
-	var $prereq_string = '';
-	var $prereq_alert = '';
-	var $prereqs = array();
-	var $previous;
-	var $prevent_reinit = 1;
-	var $ref;
-	var $save_on_close = true;
-    var $search_did = NULL;
-	var $status;
-	var $title;
-	var $type; // this attribute can contain chapter|link|student_publication|module|quiz|document|forum|thread
-	var $view_id;
+<?php //$id:$
+/**
+ * This file contains the lp_item class, that inherits from the learnpath class
+ * @package	dokeos.learnpath
+ * @author	Yannick Warnier <ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * lp_item defines items belonging to a learnpath. Each item has a name, a score, a use time and additional
+ * information that enables tracking a user's progress in a learning path
+ * @package	dokeos.learnpath
+ */
+class learnpathItem{
+	var $attempt_id; //also called "objectives" SCORM-wise
+    var $audio; //the path to an audio file (stored in document/audio/)
+	var $children = array(); //contains the ids of children items
+	var $condition; //if this item has a special condition embedded
+	var $current_score;
+	var $current_start_time;
+	var $current_stop_time;
+	var $current_data = '';
+	var $db_id;
+	var $db_item_view_id = '';
+	var $description = '';
+	var $file;
+	//at the moment, interactions are just an array of arrays with a structure of 8 text fields
+	//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
+	var $interactions = array();
+	var $interactions_count = 0;
+	var $objectives = array();
+	var $objectives_count = 0;
+	var $launch_data = '';
+	var $lesson_location = '';
+	var $level = 0;
+	//var $location; //only set this for SCORM?
+	var $lp_id;
+	var $max_score;
+	var $mastery_score;
+	var $min_score;
+	var $max_time_allowed = '';
+	var $name;
+	var $next;
+	var $parent;
+	var $path;
+	var $possible_status = array('not attempted','incomplete','completed','passed','failed','browsed');
+	var $prereq_string = '';
+	var $prereq_alert = '';
+	var $prereqs = array();
+	var $previous;
+	var $prevent_reinit = 1;
+	var $ref;
+	var $save_on_close = true;
+    var $search_did = NULL;
+	var $status;
+	var $title;
+	var $type; // this attribute can contain chapter|link|student_publication|module|quiz|document|forum|thread
+	var $view_id;
 
-	var $debug = 0; //logging param
-    /**
-     * Class constructor. Prepares the learnpath_item for later launch
+	var $debug = 0; //logging param
+    /**
+     * Class constructor. Prepares the learnpath_item for later launch
      *
-     * Don't forget to use set_lp_view() if applicable after creating the item.
-     * Setting an lp_view will finalise the item_view data collection
-     * @param	integer	Learnpath item ID
-     * @param	integer	User ID
-     * @return	boolean	True on success, false on failure
-     */
-    function learnpathItem($db_id, $user_id) {
-    	//get items table
-    	if($this->debug>0){error_log('New LP - In learnpathItem constructor: '.$db_id.','.$user_id,0);}
-    	$items_table = Database::get_course_table(TABLE_LP_ITEM);
-    	$id = (int) $db_id;
-    	$sql = "SELECT * FROM $items_table WHERE id = $id";
-    	//error_log('New LP - Creating item object from DB: '.$sql,0);
-    	$res = @Database::query($sql);
-    	if(Database::num_rows($res)<1)
-    	{
-    		$this->error = "Could not find given learnpath item in learnpath_item table";
-    		//error_log('New LP - '.$this->error,0);
-    		return false;
-    	}
-    	$row = Database::fetch_array($res);
-    	$this->lp_id	 = $row['lp_id'];
-    	$this->max_score = $row['max_score'];
-    	$this->min_score = $row['min_score'];
-    	$this->name 	 = $row['title'];
-    	$this->type 	 = $row['item_type'];
-    	$this->ref		 = $row['ref'];
-    	$this->title	 = $row['title'];
-    	$this->description = $row['description'];
-    	$this->path		 = $row['path'];
-    	$this->mastery_score = $row['mastery_score'];
-    	$this->parent	 = $row['parent_item_id'];
-    	$this->next		 = $row['next_item_id'];
-    	$this->previous	 = $row['previous_item_id'];
-    	$this->display_order = $row['display_order'];
-    	$this->prereq_string = $row['prerequisite'];
-    	$this->max_time_allowed = $row['max_time_allowed'];
-    	if(isset($row['launch_data'])){
-    		$this->launch_data = $row['launch_data'];
-    	}
-		$this->save_on_close = true;
-		$this->db_id = $id;
-
-        // get search_did
-        if (api_get_setting('search_enabled')=='true') {
-            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
-            $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d LIMIT 1';
-            // TODO: verify if it's possible to assume the actual course instead of getting it from db
-            $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $this->lp_id, $id);
-            $res = Database::query($sql, __FILE__, __LINE__);
-            if (Database::num_rows($res) >  0) {
-    	        $se_ref = Database::fetch_array($res);
-    	        $this->search_did = (int)$se_ref['search_did'];
-            }
-        }
-        $this->audio = $row['audio'];
+     * Don't forget to use set_lp_view() if applicable after creating the item.
+     * Setting an lp_view will finalise the item_view data collection
+     * @param	integer	Learnpath item ID
+     * @param	integer	User ID
+     * @return	boolean	True on success, false on failure
+     */
+    function learnpathItem($db_id, $user_id) {
+    	//get items table
+    	if($this->debug>0){error_log('New LP - In learnpathItem constructor: '.$db_id.','.$user_id,0);}
+    	$items_table = Database::get_course_table(TABLE_LP_ITEM);
+    	$id = (int) $db_id;
+    	$sql = "SELECT * FROM $items_table WHERE id = $id";
+    	//error_log('New LP - Creating item object from DB: '.$sql,0);
+    	$res = @Database::query($sql);
+    	if(Database::num_rows($res)<1)
+    	{
+    		$this->error = "Could not find given learnpath item in learnpath_item table";
+    		//error_log('New LP - '.$this->error,0);
+    		return false;
+    	}
+    	$row = Database::fetch_array($res);
+    	$this->lp_id	 = $row['lp_id'];
+    	$this->max_score = $row['max_score'];
+    	$this->min_score = $row['min_score'];
+    	$this->name 	 = $row['title'];
+    	$this->type 	 = $row['item_type'];
+    	$this->ref		 = $row['ref'];
+    	$this->title	 = $row['title'];
+    	$this->description = $row['description'];
+    	$this->path		 = $row['path'];
+    	$this->mastery_score = $row['mastery_score'];
+    	$this->parent	 = $row['parent_item_id'];
+    	$this->next		 = $row['next_item_id'];
+    	$this->previous	 = $row['previous_item_id'];
+    	$this->display_order = $row['display_order'];
+    	$this->prereq_string = $row['prerequisite'];
+    	$this->max_time_allowed = $row['max_time_allowed'];
+    	if(isset($row['launch_data'])){
+    		$this->launch_data = $row['launch_data'];
+    	}
+		$this->save_on_close = true;
+		$this->db_id = $id;
 
-		//error_log('New LP - End of learnpathItem constructor for item '.$id,0);
-    	return true;
-    }
-    /**
-     * Adds a child to the current item
-     */
-    function add_child($item)
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::add_child()',0);}
-    	if(!empty($item))
-    	{
-    		//do not check in DB as we expect the call to come from the learnpath class which should
-    		//be aware of any fake
-    		$this->children[] = $item;
-    	}
-    }
-    /**
-	 * Adds an interaction to the current item
-	 * @param	int		Index (order ID) of the interaction inside this item
-	 * @param	array	Array of parameters: id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
-	 * @result	void
-     */
-    function add_interaction($index,$params)
-    {
-		$this->interactions[$index] = $params;
-		//take the current maximum index to generate the interactions_count
-		if(($index+1)>$this->interactions_count){
-			$this->interactions_count = $index+1;
-		}
-    	/*
-		if(is_array($this->interactions[$index]) && count($this->interactions[$index])>0){
-    		$this->interactions[$index] = $params;
-    		return false;
-    	}else{
-    		if(count($params)==8){//we rely on the calling script to provide parameters in the right order
-    			$this->interactions[$index] = $params;
-    			return true;
-    		}else{
-    			return false;
-    		}
-    	}
-    	*/
-    }
-    /**
-	 * Adds an objective to the current item
-	 * @param	array	Array of parameters: id(0), status(1), score_raw(2), score_max(3), score_min(4)
-	 * @result	void
-     */
-    function add_objective($index,$params)
-    {
-    	if(empty($params[0])){return null;}
-		$this->objectives[$index] = $params;
-		//take the current maximum index to generate the objectives_count
-		if((count($this->objectives)+1)>$this->objectives_count){
-			$this->objectives_count = (count($this->objectives)+1);
-		}
-    }
+        // get search_did
+        if (api_get_setting('search_enabled')=='true') {
+            $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
+            $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d LIMIT 1';
+            // TODO: verify if it's possible to assume the actual course instead of getting it from db
+            $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $this->lp_id, $id);
+            $res = Database::query($sql, __FILE__, __LINE__);
+            if (Database::num_rows($res) >  0) {
+    	        $se_ref = Database::fetch_array($res);
+    	        $this->search_did = (int)$se_ref['search_did'];
+            }
+        }
+        $this->audio = $row['audio'];
 
-    /**
-     * Closes/stops the item viewing. Finalises runtime values. If required, save to DB.
-     * @return	boolean	True on success, false otherwise
-     */
-    function close()
-    {
-		if($this->debug>0){error_log('New LP - In learnpathItem::close()',0);}
-	   	$this->current_stop_time = time();
-	   	$type = $this->get_type();
-    	if($type != 'sco'){
-    		if($type == TOOL_QUIZ or $type == TOOL_HOTPOTATOES)
-    		{
+		//error_log('New LP - End of learnpathItem constructor for item '.$id,0);
+    	return true;
+    }
+    /**
+     * Adds a child to the current item
+     */
+    function add_child($item)
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::add_child()',0);}
+    	if(!empty($item))
+    	{
+    		//do not check in DB as we expect the call to come from the learnpath class which should
+    		//be aware of any fake
+    		$this->children[] = $item;
+    	}
+    }
+    /**
+	 * Adds an interaction to the current item
+	 * @param	int		Index (order ID) of the interaction inside this item
+	 * @param	array	Array of parameters: id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
+	 * @result	void
+     */
+    function add_interaction($index,$params)
+    {
+		$this->interactions[$index] = $params;
+		//take the current maximum index to generate the interactions_count
+		if(($index+1)>$this->interactions_count){
+			$this->interactions_count = $index+1;
+		}
+    	/*
+		if(is_array($this->interactions[$index]) && count($this->interactions[$index])>0){
+    		$this->interactions[$index] = $params;
+    		return false;
+    	}else{
+    		if(count($params)==8){//we rely on the calling script to provide parameters in the right order
+    			$this->interactions[$index] = $params;
+    			return true;
+    		}else{
+    			return false;
+    		}
+    	}
+    	*/
+    }
+    /**
+	 * Adds an objective to the current item
+	 * @param	array	Array of parameters: id(0), status(1), score_raw(2), score_max(3), score_min(4)
+	 * @result	void
+     */
+    function add_objective($index,$params)
+    {
+    	if(empty($params[0])){return null;}
+		$this->objectives[$index] = $params;
+		//take the current maximum index to generate the objectives_count
+		if((count($this->objectives)+1)>$this->objectives_count){
+			$this->objectives_count = (count($this->objectives)+1);
+		}
+    }
+
+    /**
+     * Closes/stops the item viewing. Finalises runtime values. If required, save to DB.
+     * @return	boolean	True on success, false otherwise
+     */
+    function close()
+    {
+		if($this->debug>0){error_log('New LP - In learnpathItem::close()',0);}
+	   	$this->current_stop_time = time();
+	   	$type = $this->get_type();
+    	if($type != 'sco'){
+    		if($type == TOOL_QUIZ or $type == TOOL_HOTPOTATOES)
+    		{
     			$this->get_status(true,true);//update status (second option forces the update)
-    		}
-    		else
-    		{
-    			$this->status = $this->possible_status[2];
-    		}
-    	}
-    	if($this->save_on_close)
-    	{
-    		$this->save();
+    		}
+    		else
+    		{
+    			$this->status = $this->possible_status[2];
+    		}
+    	}
+    	if($this->save_on_close)
+    	{
+    		$this->save();
+    	}
+    	return true;
+    }
+    /**
+     * Deletes all traces of this item in the database
+     * @return	boolean	true. Doesn't check for errors yet.
+     */
+    function delete()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpath_item::delete() for item '.$this->db_id,0);}
+    	$lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+    	$lp_item = Database::get_course_table(TABLE_LP_ITEM);
+    	$sql_del_view = "DELETE FROM $lp_item_view WHERE item_id = ".$this->db_id;
+		//error_log('New LP - Deleting from lp_item_view: '.$sql_del_view,0);
+		$res_del_view = Database::query($sql_del_view);
+
+        $sql_sel = "SELECT * FROM $lp_item WHERE id = ".$this->db_id;
+        $res_sel = Database::query($sql_sel,__FILE__,__LINE__);
+        if(Database::num_rows($res_sel)<1){return false;}
+        $row = Database::fetch_array($res_sel);
+
+    	$sql_del_item = "DELETE FROM $lp_item WHERE id = ".$this->db_id;
+		//error_log('New LP - Deleting from lp_item: '.$sql_del_view,0);
+        $res_del_item = Database::query($sql_del_item);
+
+        if (api_get_setting('search_enabled') == 'true') {
+        	if (!is_null($this->search_did)) {
+        		require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
+        		$di = new DokeosIndexer();
+        		$di->remove_document($this->search_did);
+        	}
+        }
+
+    	return true;
+    }
+    /**
+     * Drops a child from the children array
+     * @param	string index of child item to drop
+     * @return 	void
+     */
+    function drop_child($item)
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::drop_child()',0);}
+    	if(!empty($item))
+    	{
+    		foreach($this->children as $index => $child)
+    		{
+    			if($child == $item){
+    				$this->children[$index] = null;
+    			}
+    		}
+    	}
+    }
+    /**
+     * Gets the current attempt_id for this user on this item
+     * @return	integer	The attempt_id for this item view by this user, or 1 if none defined
+     */
+    function get_attempt_id()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_attempt_id() on item '.$this->db_id,0);}
+    	$res = 1;
+    	if(!empty($this->attempt_id))
+    	{
+    		$res = $this->attempt_id;
+    	}
+    	if($this->debug>0){error_log('New LP - End of learnpathItem::get_attempt_id() on item '.$this->db_id.' - Returning '.$res,0);}
+    	return $res;
+    }
+    /**
+     * Gets a list of the item's children
+     * @return	array	Array of children items IDs
+     */
+    function get_children()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_children()',0);}
+    	$list = array();
+    	foreach($this->children as $child){
+    		if(!empty($child))
+    		{
+    			//error_log('New LP - Found '.$child,0);
+    			$list[] = $child;
+    		}
     	}
-    	return true;
-    }
-    /**
-     * Deletes all traces of this item in the database
-     * @return	boolean	true. Doesn't check for errors yet.
-     */
-    function delete()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpath_item::delete() for item '.$this->db_id,0);}
-    	$lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-    	$lp_item = Database::get_course_table(TABLE_LP_ITEM);
-    	$sql_del_view = "DELETE FROM $lp_item_view WHERE item_id = ".$this->db_id;
-		//error_log('New LP - Deleting from lp_item_view: '.$sql_del_view,0);
-		$res_del_view = Database::query($sql_del_view);
-
-        $sql_sel = "SELECT * FROM $lp_item WHERE id = ".$this->db_id;
-        $res_sel = Database::query($sql_sel,__FILE__,__LINE__);
-        if(Database::num_rows($res_sel)<1){return false;}
-        $row = Database::fetch_array($res_sel);
-
-    	$sql_del_item = "DELETE FROM $lp_item WHERE id = ".$this->db_id;
-		//error_log('New LP - Deleting from lp_item: '.$sql_del_view,0);
-        $res_del_item = Database::query($sql_del_item);
-
-        if (api_get_setting('search_enabled') == 'true') {
-        	if (!is_null($this->search_did)) {
-        		require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
-        		$di = new DokeosIndexer();
-        		$di->remove_document($this->search_did);
-        	}
-        }
-
-    	return true;
-    }
-    /**
-     * Drops a child from the children array
-     * @param	string index of child item to drop
-     * @return 	void
-     */
-    function drop_child($item)
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::drop_child()',0);}
-    	if(!empty($item))
-    	{
-    		foreach($this->children as $index => $child)
-    		{
-    			if($child == $item){
-    				$this->children[$index] = null;
-    			}
-    		}
-    	}
-    }
-    /**
-     * Gets the current attempt_id for this user on this item
-     * @return	integer	The attempt_id for this item view by this user, or 1 if none defined
-     */
-    function get_attempt_id()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_attempt_id() on item '.$this->db_id,0);}
-    	$res = 1;
-    	if(!empty($this->attempt_id))
-    	{
-    		$res = $this->attempt_id;
-    	}
-    	if($this->debug>0){error_log('New LP - End of learnpathItem::get_attempt_id() on item '.$this->db_id.' - Returning '.$res,0);}
-    	return $res;
-    }
-    /**
-     * Gets a list of the item's children
-     * @return	array	Array of children items IDs
-     */
-    function get_children()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_children()',0);}
-    	$list = array();
-    	foreach($this->children as $child){
-    		if(!empty($child))
-    		{
-    			//error_log('New LP - Found '.$child,0);
-    			$list[] = $child;
-    		}
-    	}
-    	return $list;
-    }
-    /**
-     * Gets the core_exit value from the database
-     */
-    function get_core_exit()
-    {
-    	return $this->core_exit;
-    }
-    /**
-     * Gets the credit information (rather scorm-stuff) based on current status and reinit
-     * autorization. Credit tells the sco(content) if Dokeos will record the data it is sent (credit) or not (no-credit)
-     * @return	string	'credit' or 'no-credit'. Defaults to 'credit' because if we don't know enough about this item, it's probably because it was never used before.
-     */
-    function get_credit(){
-    	if(!empty($this->debug) && $this->debug>1){error_log('New LP - In learnpathItem::get_credit()',0);}
-		$credit = 'credit';
-    	//now check the value of prevent_reinit (if it's 0, return credit as the default was)
-		if($this->get_prevent_reinit() != 0){ //if prevent_reinit == 1 (or more)
-			//if status is not attempted or incomplete, credit anyway. Otherwise:
-    		//check the status in the database rather than in the object, as checking in the object
-			//would always return "no-credit" when we want to set it to completed
-			$status = $this->get_status(true);
+    	return $list;
+    }
+    /**
+     * Gets the core_exit value from the database
+     */
+    function get_core_exit()
+    {
+    	return $this->core_exit;
+    }
+    /**
+     * Gets the credit information (rather scorm-stuff) based on current status and reinit
+     * autorization. Credit tells the sco(content) if Dokeos will record the data it is sent (credit) or not (no-credit)
+     * @return	string	'credit' or 'no-credit'. Defaults to 'credit' because if we don't know enough about this item, it's probably because it was never used before.
+     */
+    function get_credit(){
+    	if(!empty($this->debug) && $this->debug>1){error_log('New LP - In learnpathItem::get_credit()',0);}
+		$credit = 'credit';
+    	//now check the value of prevent_reinit (if it's 0, return credit as the default was)
+		if($this->get_prevent_reinit() != 0){ //if prevent_reinit == 1 (or more)
+			//if status is not attempted or incomplete, credit anyway. Otherwise:
+    		//check the status in the database rather than in the object, as checking in the object
+			//would always return "no-credit" when we want to set it to completed
+			$status = $this->get_status(true);
 			if(!empty($this->debug) && $this->debug>2){error_log('New LP - In learnpathItem::get_credit() - get_prevent_reinit!=0 and status is '.$status,0);}
-			if($status != $this->possible_status[0] AND $status != $this->possible_status[1]){
-				$credit = 'no-credit';
-			}
-		}
-		return $credit;
-    }
-    /**
-     * Gets the current start time property
-     * @return	integer	Current start time, or current time if none
-     */
-    function get_current_start_time()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_current_start_time()',0);}
-    	if(empty($this->current_start_time))
-    	{
-    		return time();
-    	}else{
-    		return $this->current_start_time;
-    	}
-    }
-    /**
-     * Gets the item's description
-     * @return	string	Description
-     */
-    function get_description(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_description()',0);}
-    	if(empty($this->description)){return '';}
-    	return $this->description;
-    }
-    /**
-     * Gets the file path from the course's root directory, no matter what tool it is from.
-     * @return	string	The file path, or an empty string if there is no file attached, or '-1' if the file must be replaced by an error page
-     */
-    function get_file_path($path_to_scorm_dir=''){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_file_path()',0);}
-    	$path = $this->get_path();
-   		$type = $this->get_type();
-    	if(empty($path))
-    	{
-    		if($type == 'dokeos_chapter' OR $type=='chapter' OR $type == 'dir')
-    		{
-    			return '';
-    		}
-    		else
-    		{
-    			return '-1';
-    		}
-    	}elseif($path == strval(intval($path))){
-    		//the path is numeric, so it is a reference to a Dokeos object
-    		switch($type)
-    		{
-    			case 'dokeos_chapter':
-    			case 'dir':
-    			case 'chapter':
-    				return '';
-    			case TOOL_DOCUMENT:
-    				$table_doc = Database::get_course_table(TABLE_DOCUMENT);
-    				$sql = 'SELECT path FROM '.$table_doc.' WHERE id = '.$path;
-    				$res = Database::query($sql,__FILE__,__LINE__);
-    				$row = Database::fetch_array($res);
-    				$real_path = 'document'.$row['path'];
-    				return $real_path;
-    			case TOOL_STUDENTPUBLICATION:
-    			case TOOL_QUIZ:
-    			case TOOL_FORUM:
-    			case TOOL_THREAD:
-    			case TOOL_LINK:
-    			default:
-    				return '-1';
-    		}
-    	}else{
-    		if(!empty($path_to_scorm_dir))
-    		{
-    			$path = $path_to_scorm_dir.$path;
-    		}
-    		return $path;
-    	}
-    }
-    /**
-     * Gets the DB ID
-     * @return	integer	Database ID for the current item
-     */
-    function get_id(){
-    	if($this->debug>1){error_log('New LP - In learnpathItem::get_id()',0);}
-    	if(!empty($this->db_id))
-    	{
-    		return $this->db_id;
-    	}
-    	//TODO check this return value is valid for children classes (SCORM?)
-    	return 0;
-    }
-    /**
-     * Loads the interactions into the item object, from the database.
-     * If object interactions exist, they will be overwritten by this function,
-     * using the database elements only.
-     * @return void Directly sets the interactions attribute in memory
-     */
-    function load_interactions() {
-            $this->interactions = array();
-            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-            $sql = "SELECT id FROM $tbl " .
-                    "WHERE lp_item_id = ".$this->db_id." " .
-                    "AND   lp_view_id = ".$this->view_id." " .
-                    "AND   view_count = ".$this->attempt_id;
-            $res = Database::query($sql,__FILE__,__LINE__);
-            if (Database::num_rows($res)>0) {
-                $row = Database::fetch_array($res);
-                $lp_iv_id = $row[0];
-                $iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
-                $iva_sql = "SELECT * FROM $iva_table " .
-                            "WHERE lp_iv_id = $lp_iv_id ";
-                $res_sql = Database::query($iva_sql);
-                while ($row = Database::fetch_array($res_sql)) {
-                    $this->interactions[$row['interaction_id']] = array($row['interaction_id'],$row['interaction_type'],$row['weighting'],$row['completion_time'],$row['correct_responses'],$row['student_responses'],$row['result'],$row['latency']);
-                }
-            }
-    }
-    /**
-     * Gets the current count of interactions recorded in the database
-     * @param   bool    Whether to count from database or not (defaults to no)
-     * @return	int	The current number of interactions recorder
-     */
-    function get_interactions_count($checkdb=false)
-    {
-    	if($this->debug>1){error_log('New LP - In learnpathItem::get_interactions_count()',0);}
-    	$return = 0;
-        if ($checkdb) {
-            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-            $sql = "SELECT id FROM $tbl " .
-                    "WHERE lp_item_id = ".$this->db_id." " .
-                    "AND   lp_view_id = ".$this->view_id." " .
-                    "AND   view_count = ".$this->attempt_id;
-            $res = Database::query($sql,__FILE__,__LINE__);
-            if (Database::num_rows($res)>0) {
-                $row = Database::fetch_array($res);
-                $lp_iv_id = $row[0];
-                $iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
-                $iva_sql = "SELECT count(id) as mycount FROM $iva_table " .
-                            "WHERE lp_iv_id = $lp_iv_id ";
-                $res_sql = Database::query($iva_sql);
-                if (Database::num_rows($res_sql)>0) {
-                	$row = Database::fetch_array($res_sql);
-                    $return = $row['mycount'];
-                }
-            }
-        } else {
-        	if(!empty($this->interactions_count)){
-        		$return = $this->interactions_count;
-        	}
-        }
-    	return $return;
-    }
-    /**
-     * Gets the JavaScript array content to fill the interactions array.
-     * @params  bool    Whether to check directly into the database (default no)
-     * @return  string  An empty string if no interaction, a JS array definition otherwise
-     */
-    function get_interactions_js_array($checkdb=false) {
-        $return = '';
-        if ($checkdb) {
-            $this->load_interactions(true);
-        }
-        foreach ($this->interactions as $id=>$in) {
-    		$return .= "['$id','".$in[1]."','".$in[2]."','".$in[3]."','".$in[4]."','".$in[5]."','".$in[6]."','".$in[7]."'],";
-    	}
-        if (!empty($return)) {
-        	$return = substr($return,0,-1);
-        }
-        return $return;
-    }
-    /**
-     * Gets the current count of objectives recorded in the database
-     * @return	int	The current number of objectives recorder
-     */
-    function get_objectives_count()
-    {
-    	if($this->debug>1){error_log('New LP - In learnpathItem::get_objectives_count()',0);}
-    	$res = 0;
-    	if(!empty($this->objectives_count)){
-    		$res = $this->objectives_count;
-    	}
-    	return $res;
-    }
-    /**
-     * Gets the launch_data field found in imsmanifests (this is SCORM- or AICC-related, really)
-     * @return	string	Launch data as found in imsmanifest and stored in Dokeos (read only). Defaults to ''.
-     */
-    function get_launch_data(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_launch_data()',0);}
-    	if(!empty($this->launch_data)){
-    		return $this->launch_data;
-    	}
-    	return '';
-    }
-    /**
-     * Gets the lesson location
-     * @return string	lesson location as recorded by the SCORM and AICC elements. Defaults to ''
-     */
-	function get_lesson_location(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_lesson_location()',0);}
-    	if(!empty($this->lesson_location)){return $this->lesson_location;}else{return '';}
-	}
-	/**
-	 * Gets the lesson_mode (scorm feature, but might be used by aicc as well as dokeos paths)
+			if($status != $this->possible_status[0] AND $status != $this->possible_status[1]){
+				$credit = 'no-credit';
+			}
+		}
+		return $credit;
+    }
+    /**
+     * Gets the current start time property
+     * @return	integer	Current start time, or current time if none
+     */
+    function get_current_start_time()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_current_start_time()',0);}
+    	if(empty($this->current_start_time))
+    	{
+    		return time();
+    	}else{
+    		return $this->current_start_time;
+    	}
+    }
+    /**
+     * Gets the item's description
+     * @return	string	Description
+     */
+    function get_description(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_description()',0);}
+    	if(empty($this->description)){return '';}
+    	return $this->description;
+    }
+    /**
+     * Gets the file path from the course's root directory, no matter what tool it is from.
+     * @return	string	The file path, or an empty string if there is no file attached, or '-1' if the file must be replaced by an error page
+     */
+    function get_file_path($path_to_scorm_dir=''){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_file_path()',0);}
+    	$path = $this->get_path();
+   		$type = $this->get_type();
+    	if(empty($path))
+    	{
+    		if($type == 'dokeos_chapter' OR $type=='chapter' OR $type == 'dir')
+    		{
+    			return '';
+    		}
+    		else
+    		{
+    			return '-1';
+    		}
+    	}elseif($path == strval(intval($path))){
+    		//the path is numeric, so it is a reference to a Dokeos object
+    		switch($type)
+    		{
+    			case 'dokeos_chapter':
+    			case 'dir':
+    			case 'chapter':
+    				return '';
+    			case TOOL_DOCUMENT:
+    				$table_doc = Database::get_course_table(TABLE_DOCUMENT);
+    				$sql = 'SELECT path FROM '.$table_doc.' WHERE id = '.$path;
+    				$res = Database::query($sql,__FILE__,__LINE__);
+    				$row = Database::fetch_array($res);
+    				$real_path = 'document'.$row['path'];
+    				return $real_path;
+    			case TOOL_STUDENTPUBLICATION:
+    			case TOOL_QUIZ:
+    			case TOOL_FORUM:
+    			case TOOL_THREAD:
+    			case TOOL_LINK:
+    			default:
+    				return '-1';
+    		}
+    	}else{
+    		if(!empty($path_to_scorm_dir))
+    		{
+    			$path = $path_to_scorm_dir.$path;
+    		}
+    		return $path;
+    	}
+    }
+    /**
+     * Gets the DB ID
+     * @return	integer	Database ID for the current item
+     */
+    function get_id(){
+    	if($this->debug>1){error_log('New LP - In learnpathItem::get_id()',0);}
+    	if(!empty($this->db_id))
+    	{
+    		return $this->db_id;
+    	}
+    	//TODO check this return value is valid for children classes (SCORM?)
+    	return 0;
+    }
+    /**
+     * Loads the interactions into the item object, from the database.
+     * If object interactions exist, they will be overwritten by this function,
+     * using the database elements only.
+     * @return void Directly sets the interactions attribute in memory
+     */
+    function load_interactions() {
+            $this->interactions = array();
+            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+            $sql = "SELECT id FROM $tbl " .
+                    "WHERE lp_item_id = ".$this->db_id." " .
+                    "AND   lp_view_id = ".$this->view_id." " .
+                    "AND   view_count = ".$this->attempt_id;
+            $res = Database::query($sql,__FILE__,__LINE__);
+            if (Database::num_rows($res)>0) {
+                $row = Database::fetch_array($res);
+                $lp_iv_id = $row[0];
+                $iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
+                $iva_sql = "SELECT * FROM $iva_table " .
+                            "WHERE lp_iv_id = $lp_iv_id ";
+                $res_sql = Database::query($iva_sql);
+                while ($row = Database::fetch_array($res_sql)) {
+                    $this->interactions[$row['interaction_id']] = array($row['interaction_id'],$row['interaction_type'],$row['weighting'],$row['completion_time'],$row['correct_responses'],$row['student_responses'],$row['result'],$row['latency']);
+                }
+            }
+    }
+    /**
+     * Gets the current count of interactions recorded in the database
+     * @param   bool    Whether to count from database or not (defaults to no)
+     * @return	int	The current number of interactions recorder
+     */
+    function get_interactions_count($checkdb=false)
+    {
+    	if($this->debug>1){error_log('New LP - In learnpathItem::get_interactions_count()',0);}
+    	$return = 0;
+        if ($checkdb) {
+            $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+            $sql = "SELECT id FROM $tbl " .
+                    "WHERE lp_item_id = ".$this->db_id." " .
+                    "AND   lp_view_id = ".$this->view_id." " .
+                    "AND   view_count = ".$this->attempt_id;
+            $res = Database::query($sql,__FILE__,__LINE__);
+            if (Database::num_rows($res)>0) {
+                $row = Database::fetch_array($res);
+                $lp_iv_id = $row[0];
+                $iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
+                $iva_sql = "SELECT count(id) as mycount FROM $iva_table " .
+                            "WHERE lp_iv_id = $lp_iv_id ";
+                $res_sql = Database::query($iva_sql);
+                if (Database::num_rows($res_sql)>0) {
+                	$row = Database::fetch_array($res_sql);
+                    $return = $row['mycount'];
+                }
+            }
+        } else {
+        	if(!empty($this->interactions_count)){
+        		$return = $this->interactions_count;
+        	}
+        }
+    	return $return;
+    }
+    /**
+     * Gets the JavaScript array content to fill the interactions array.
+     * @params  bool    Whether to check directly into the database (default no)
+     * @return  string  An empty string if no interaction, a JS array definition otherwise
+     */
+    function get_interactions_js_array($checkdb=false) {
+        $return = '';
+        if ($checkdb) {
+            $this->load_interactions(true);
+        }
+        foreach ($this->interactions as $id=>$in) {
+    		$return .= "['$id','".$in[1]."','".$in[2]."','".$in[3]."','".$in[4]."','".$in[5]."','".$in[6]."','".$in[7]."'],";
+    	}
+        if (!empty($return)) {
+        	$return = substr($return,0,-1);
+        }
+        return $return;
+    }
+    /**
+     * Gets the current count of objectives recorded in the database
+     * @return	int	The current number of objectives recorder
+     */
+    function get_objectives_count()
+    {
+    	if($this->debug>1){error_log('New LP - In learnpathItem::get_objectives_count()',0);}
+    	$res = 0;
+    	if(!empty($this->objectives_count)){
+    		$res = $this->objectives_count;
+    	}
+    	return $res;
+    }
+    /**
+     * Gets the launch_data field found in imsmanifests (this is SCORM- or AICC-related, really)
+     * @return	string	Launch data as found in imsmanifest and stored in Dokeos (read only). Defaults to ''.
+     */
+    function get_launch_data(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_launch_data()',0);}
+    	if(!empty($this->launch_data)){
+    		return $this->launch_data;
+    	}
+    	return '';
+    }
+    /**
+     * Gets the lesson location
+     * @return string	lesson location as recorded by the SCORM and AICC elements. Defaults to ''
+     */
+	function get_lesson_location(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_lesson_location()',0);}
+    	if(!empty($this->lesson_location)){return $this->lesson_location;}else{return '';}
+	}
+	/**
+	 * Gets the lesson_mode (scorm feature, but might be used by aicc as well as dokeos paths)
 	 *
-	 * The "browse" mode is not supported yet (because there is no such way of seeing a sco in Dokeos)
-	 * @return	string	'browse','normal' or 'review'. Defaults to 'normal'
-	 */
-	function get_lesson_mode(){
-		$mode = 'normal';
-		if($this->get_prevent_reinit() != 0){ //if prevent_reinit == 0
-			$my_status = $this->get_status();
+	 * The "browse" mode is not supported yet (because there is no such way of seeing a sco in Dokeos)
+	 * @return	string	'browse','normal' or 'review'. Defaults to 'normal'
+	 */
+	function get_lesson_mode(){
+		$mode = 'normal';
+		if($this->get_prevent_reinit() != 0){ //if prevent_reinit == 0
+			$my_status = $this->get_status();
 			if($my_status != $this->possible_status[0] AND $my_status != $this->possible_status[1]){
-				$mode = 'review';
-			}
-		}
-		return $mode;
-	}
-    /**
-     * Gets the depth level
-     * @return int	Level. Defaults to 0
-     */
-    function get_level(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_level()',0);}
-    	if(empty($this->level)){return 0;}
-    	return $this->level;
-    }
-    /**
-     * Gets the mastery score
-     */
-    function get_mastery_score()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_mastery_score()',0);}
+				$mode = 'review';
+			}
+		}
+		return $mode;
+	}
+    /**
+     * Gets the depth level
+     * @return int	Level. Defaults to 0
+     */
+    function get_level(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_level()',0);}
+    	if(empty($this->level)){return 0;}
+    	return $this->level;
+    }
+    /**
+     * Gets the mastery score
+     */
+    function get_mastery_score()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_mastery_score()',0);}
     	if(isset($this->mastery_score)){return $this->mastery_score;}else{return -1;}
-    }
-    /**
-     * Gets the maximum (score)
-     * @return	int	Maximum score. Defaults to 100 if nothing else is defined
-     */
-    function get_max(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_max()',0);}
-    	if($this->type == 'sco')
-    	{
-    		if(!empty($this->view_max_score) and $this->view_max_score>0)
-    		{
-    			return $this->view_max_score;
-    		}
-    		elseif($this->view_max_score === '')
-    		{
-    			return $this->view_max_score;
-    		}
-    		else
-    		{
-		    	if(!empty($this->max_score)){return $this->max_score;}else{return 100;}
-    		}
-    	}
-    	else
-    	{
-    		if(!empty($this->max_score)){return $this->max_score;}else{return 100;}
-    	}
-    }
-    /**
-     * Gets the maximum time allowed for this user in this attempt on this item
-     * @return	string	Time string in SCORM format (HH:MM:SS or HH:MM:SS.SS or HHHH:MM:SS.SS)
-     */
-    function get_max_time_allowed()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_max_time_allowed()',0);}
+    }
+    /**
+     * Gets the maximum (score)
+     * @return	int	Maximum score. Defaults to 100 if nothing else is defined
+     */
+    function get_max(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_max()',0);}
+    	if($this->type == 'sco')
+    	{
+    		if(!empty($this->view_max_score) and $this->view_max_score>0)
+    		{
+    			return $this->view_max_score;
+    		}
+    		elseif($this->view_max_score === '')
+    		{
+    			return $this->view_max_score;
+    		}
+    		else
+    		{
+		    	if(!empty($this->max_score)){return $this->max_score;}else{return 100;}
+    		}
+    	}
+    	else
+    	{
+    		if(!empty($this->max_score)){return $this->max_score;}else{return 100;}
+    	}
+    }
+    /**
+     * Gets the maximum time allowed for this user in this attempt on this item
+     * @return	string	Time string in SCORM format (HH:MM:SS or HH:MM:SS.SS or HHHH:MM:SS.SS)
+     */
+    function get_max_time_allowed()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_max_time_allowed()',0);}
     	if(!empty($this->max_time_allowed)){return $this->max_time_allowed;}else{return '';}
-    }
-    /**
-     * Gets the minimum (score)
-     * @return int	Minimum score. Defaults to 0
-     */
-    function get_min(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_min()',0);}
-    	if(!empty($this->min_score)){return $this->min_score;}else{return 0;}
-    }
-    /**
-     * Gets the parent ID
-     * @return	int	Parent ID. Defaults to null
-     */
-    function get_parent(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_parent()',0);}
-    	if(!empty($this->parent))
-    	{
-    		return $this->parent;
-    	}
-    	//TODO check this return value is valid for children classes (SCORM?)
-    	return null;
-    }
-    /**
-     * Gets the path attribute.
-     * @return	string	Path. Defaults to ''
-     */
-    function get_path(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_path()',0);}
-    	if(empty($this->path)){return '';}
-    	return $this->path;
-    }
-    /**
-     * Gets the prerequisites string
+    }
+    /**
+     * Gets the minimum (score)
+     * @return int	Minimum score. Defaults to 0
+     */
+    function get_min(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_min()',0);}
+    	if(!empty($this->min_score)){return $this->min_score;}else{return 0;}
+    }
+    /**
+     * Gets the parent ID
+     * @return	int	Parent ID. Defaults to null
+     */
+    function get_parent(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_parent()',0);}
+    	if(!empty($this->parent))
+    	{
+    		return $this->parent;
+    	}
+    	//TODO check this return value is valid for children classes (SCORM?)
+    	return null;
+    }
+    /**
+     * Gets the path attribute.
+     * @return	string	Path. Defaults to ''
+     */
+    function get_path(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_path()',0);}
+    	if(empty($this->path)){return '';}
+    	return $this->path;
+    }
+    /**
+     * Gets the prerequisites string
      * @return	string	Empty string or prerequisites string if defined. Defaults to
-     */
-    function get_prereq_string()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_prereq_string()',0);}
-    	if(!empty($this->prereq_string))
-    	{
-    		return $this->prereq_string;
-    	}else{
-    		return '';
-    	}
-    }
-    /**
-     * Gets the prevent_reinit attribute value (and sets it if not set already)
-     * @return	int	1 or 0 (defaults to 1)
-     */
-    function get_prevent_reinit(){
-		if($this->debug>2){error_log('New LP - In learnpathItem::get_prevent_reinit()',0);}
-    	if(!isset($this->prevent_reinit)){
-	    	if(!empty($this->lp_id)){
-	    		$db = Database::get_course_table(TABLE_LP_MAIN);
-			   	$sql = "SELECT * FROM $db WHERE id = ".$this->lp_id;
-		    	$res = @Database::query($sql);
-		    	if(Database::num_rows($res)<1)
-		    	{
-		    		$this->error = "Could not find parent learnpath in learnpath table";
-					if($this->debug>2){error_log('New LP - End of learnpathItem::get_prevent_reinit() - Returning false',0);}
-		    		return false;
-		    	}else{
-		    		$row = Database::fetch_array($res);
+     */
+    function get_prereq_string()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_prereq_string()',0);}
+    	if(!empty($this->prereq_string))
+    	{
+    		return $this->prereq_string;
+    	}else{
+    		return '';
+    	}
+    }
+    /**
+     * Gets the prevent_reinit attribute value (and sets it if not set already)
+     * @return	int	1 or 0 (defaults to 1)
+     */
+    function get_prevent_reinit(){
+		if($this->debug>2){error_log('New LP - In learnpathItem::get_prevent_reinit()',0);}
+    	if(!isset($this->prevent_reinit)){
+	    	if(!empty($this->lp_id)){
+	    		$db = Database::get_course_table(TABLE_LP_MAIN);
+			   	$sql = "SELECT * FROM $db WHERE id = ".$this->lp_id;
+		    	$res = @Database::query($sql);
+		    	if(Database::num_rows($res)<1)
+		    	{
+		    		$this->error = "Could not find parent learnpath in learnpath table";
+					if($this->debug>2){error_log('New LP - End of learnpathItem::get_prevent_reinit() - Returning false',0);}
+		    		return false;
+		    	}else{
+		    		$row = Database::fetch_array($res);
 		    		$this->prevent_reinit = $row['prevent_reinit'];
-		    	}
-	    	}else{
-	    		$this->prevent_reinit = 1;//prevent reinit is always 1 by default - see learnpath.class.php
-	    	}
-    	}
-		if($this->debug>2){error_log('New LP - End of learnpathItem::get_prevent_reinit() - Returned '.$this->prevent_reinit,0);}
-    	return $this->prevent_reinit;
-    }
-    /**
-     * Gets the item's reference column
-     * @return string	The item's reference field (generally used for SCORM identifiers)
-     */
-    function get_ref()
-    {
-    	return $this->ref;
-    }
-    /**
-     * Gets the list of included resources as a list of absolute or relative paths of
-     * resources included in the current item. This allows for a better SCORM export.
-     * The list will generally include pictures, flash objects, java applets, or any other
-     * stuff included in the source of the current item. The current item is expected
-     * to be an HTML file. If it is not, then the function will return and empty list.
-     * @param	string	type (one of the Dokeos tools) - optional (otherwise takes the current item's type)
-     * @param	string	path (absolute file path) - optional (otherwise takes the current item's path)
-     * @param	int		level of recursivity we're in
-     * @return	array	List of file paths. An additional field containing 'local' or 'remote' helps determine if the file should be copied into the zip or just linked
-     */
-    function get_resources_from_source($type=null,$abs_path=null, $recursivity=1)
-    {
-    	$max = 5;
-    	if($recursivity > $max)
-    	{
-    		return array();
-    	}
-    	if(!isset($type))
-    	{
-    		$type = $this->get_type();
-    	}
-    	if(!isset($abs_path))
-    	{
-    		$path = $this->get_file_path();
-   			$abs_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$path;
-   			//echo "Abs path coming from item : ".$abs_path."<br/>\n";
-    	}
-    	/*
-    	else
-    	{
-    		echo "Abs path coming from param: ".$abs_path."<br/>\n";
-    	}
-    	*/
-    	//error_log(str_repeat(' ',$recursivity).'Analyse file '.$abs_path,0);
-    	$files_list = array();
-    	$type = $this->get_type();
-    	switch($type)
-    	{
+		    	}
+	    	}else{
+	    		$this->prevent_reinit = 1;//prevent reinit is always 1 by default - see learnpath.class.php
+	    	}
+    	}
+		if($this->debug>2){error_log('New LP - End of learnpathItem::get_prevent_reinit() - Returned '.$this->prevent_reinit,0);}
+    	return $this->prevent_reinit;
+    }
+    /**
+     * Gets the item's reference column
+     * @return string	The item's reference field (generally used for SCORM identifiers)
+     */
+    function get_ref()
+    {
+    	return $this->ref;
+    }
+    /**
+     * Gets the list of included resources as a list of absolute or relative paths of
+     * resources included in the current item. This allows for a better SCORM export.
+     * The list will generally include pictures, flash objects, java applets, or any other
+     * stuff included in the source of the current item. The current item is expected
+     * to be an HTML file. If it is not, then the function will return and empty list.
+     * @param	string	type (one of the Dokeos tools) - optional (otherwise takes the current item's type)
+     * @param	string	path (absolute file path) - optional (otherwise takes the current item's path)
+     * @param	int		level of recursivity we're in
+     * @return	array	List of file paths. An additional field containing 'local' or 'remote' helps determine if the file should be copied into the zip or just linked
+     */
+    function get_resources_from_source($type=null,$abs_path=null, $recursivity=1)
+    {
+    	$max = 5;
+    	if($recursivity > $max)
+    	{
+    		return array();
+    	}
+    	if(!isset($type))
+    	{
+    		$type = $this->get_type();
+    	}
+    	if(!isset($abs_path))
+    	{
+    		$path = $this->get_file_path();
+   			$abs_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$path;
+   			//echo "Abs path coming from item : ".$abs_path."<br/>\n";
+    	}
+    	/*
+    	else
+    	{
+    		echo "Abs path coming from param: ".$abs_path."<br/>\n";
+    	}
+    	*/
+    	//error_log(str_repeat(' ',$recursivity).'Analyse file '.$abs_path,0);
+    	$files_list = array();
+    	$type = $this->get_type();
+    	switch($type)
+    	{
     		case TOOL_DOCUMENT :
-    		case TOOL_QUIZ:
-    		case 'sco':
-    			//get the document and, if HTML, open it
+    		case TOOL_QUIZ:
+    		case 'sco':
+    			//get the document and, if HTML, open it
+
+    			if(is_file($abs_path))
+    			{
+	    			//for now, read the whole file in one go (that's gonna be a problem when the file is too big)
+					$info = pathinfo($abs_path);
+					$ext = $info['extension'];
+					switch(strtolower($ext))
+					{
+						case 'html':
+						case 'htm':
+						case 'shtml':
+						case 'css':
+					 		$wanted_attributes = array('src','url','@import','href','value');
+			    			//parse it for included resources
+							$file_content = file_get_contents($abs_path);
+							//get an array of attributes from the HTML source
+							$attributes = learnpathItem::parse_HTML_attributes($file_content,$wanted_attributes);
+							//look at 'src' attributes in this file
+							foreach($wanted_attributes as $attr)
+							{
+								if(isset($attributes[$attr]))
+								{
+									//find which kind of path these are (local or remote)
+									$sources = $attributes[$attr];
 
-    			if(is_file($abs_path))
-    			{
-	    			//for now, read the whole file in one go (that's gonna be a problem when the file is too big)
-					$info = pathinfo($abs_path);
-					$ext = $info['extension'];
-					switch(strtolower($ext))
-					{
-						case 'html':
-						case 'htm':
-						case 'shtml':
-						case 'css':
-					 		$wanted_attributes = array('src','url','@import','href','value');
-			    			//parse it for included resources
-							$file_content = file_get_contents($abs_path);
-							//get an array of attributes from the HTML source
-							$attributes = learnpathItem::parse_HTML_attributes($file_content,$wanted_attributes);
-							//look at 'src' attributes in this file
-							foreach($wanted_attributes as $attr)
-							{
-								if(isset($attributes[$attr]))
-								{
-									//find which kind of path these are (local or remote)
-									$sources = $attributes[$attr];
+									foreach($sources as $source)
+									{
+										//skip what is obviously not a resource
+										if(strpos($source,"+this.")) continue; //javascript code - will still work unaltered
+										if(strpos($source,'.')=== false) continue; //no dot, should not be an external file anyway
+										if(strpos($source,'mailto:')) continue; //mailto link
+										if(strpos($source,';') && !strpos($source,'&amp;')) continue; //avoid code - that should help
 
-									foreach($sources as $source)
-									{
-										//skip what is obviously not a resource
-										if(strpos($source,"+this.")) continue; //javascript code - will still work unaltered
-										if(strpos($source,'.')=== false) continue; //no dot, should not be an external file anyway
-										if(strpos($source,'mailto:')) continue; //mailto link
-										if(strpos($source,';') && !strpos($source,'&amp;')) continue; //avoid code - that should help
+										if($attr == 'value')
+										{
+											if(strpos($source , 'mp3file'))
+											{
+												$files_list[] = array(substr($source, 0, strpos($source , '.swf')+4),'local','abs');
+												$mp3file = substr($source , strpos($source , 'mp3file=')+8);
+												if(substr($mp3file,0,1) == '/')
+													$files_list[] = array($mp3file,'local','abs');
+												else
+													$files_list[] = array($mp3file,'local','rel');
+											}
+                                            elseif(strpos($source, 'flv=')===0)
+                                            {
+                                            	$source = substr($source, 4);
+                                                if(strpos($source, '&')>0)
+                                                {
+                                                	$source = substr($source,0,strpos($source, '&'));
+                                                }
+                                            	if(strpos($source,'://')>0)
+                                                {
+                                                    if(strpos($source,api_get_path(WEB_PATH))!==false)
+                                                    {
+                                                        //we found the current portal url
+                                                        $files_list[] = array($source,'local','url');
+                                                    }
+                                                    else
+                                                    {
+                                                        //we didn't find any trace of current portal
+                                                        $files_list[] = array($source,'remote','url');
+                                                    }
+                                                }
+                                                else
+                                                {
+                                                    $files_list[] = array($source,'local','abs');
+                                                }
+                                                continue; //skipping anything else to avoid two entries (while the others can have sub-files in their url, flv's can't)
+                                            }
+										}
+										if(strpos($source,'://') > 0)
+										{
 
-										if($attr == 'value')
-										{
-											if(strpos($source , 'mp3file'))
-											{
-												$files_list[] = array(substr($source, 0, strpos($source , '.swf')+4),'local','abs');
-												$mp3file = substr($source , strpos($source , 'mp3file=')+8);
-												if(substr($mp3file,0,1) == '/')
-													$files_list[] = array($mp3file,'local','abs');
-												else
-													$files_list[] = array($mp3file,'local','rel');
-											}
-                                            elseif(strpos($source, 'flv=')===0)
-                                            {
-                                            	$source = substr($source, 4);
-                                                if(strpos($source, '&')>0)
-                                                {
-                                                	$source = substr($source,0,strpos($source, '&'));
-                                                }
-                                            	if(strpos($source,'://')>0)
-                                                {
-                                                    if(strpos($source,api_get_path(WEB_PATH))!==false)
-                                                    {
-                                                        //we found the current portal url
-                                                        $files_list[] = array($source,'local','url');
-                                                    }
-                                                    else
-                                                    {
-                                                        //we didn't find any trace of current portal
-                                                        $files_list[] = array($source,'remote','url');
-                                                    }
-                                                }
-                                                else
-                                                {
-                                                    $files_list[] = array($source,'local','abs');
-                                                }
-                                                continue; //skipping anything else to avoid two entries (while the others can have sub-files in their url, flv's can't)
-                                            }
-										}
-										if(strpos($source,'://') > 0)
-										{
+											//cut at '?' in a URL with params
+											if(strpos($source,'?')>0)
+											{
+												$second_part = substr($source,strpos($source,'?'));
+												if(strpos($second_part,'://')>0)
+												{//if the second part of the url contains a url too, treat the second one before cutting
 
-											//cut at '?' in a URL with params
-											if(strpos($source,'?')>0)
-											{
-												$second_part = substr($source,strpos($source,'?'));
-												if(strpos($second_part,'://')>0)
-												{//if the second part of the url contains a url too, treat the second one before cutting
-
-													$pos1 = strpos($second_part,'=');
-													$pos2 = strpos($second_part,'&');
-													$second_part = substr($second_part,$pos1+1,$pos2-($pos1+1));
-													if(strpos($second_part,api_get_path(WEB_PATH))!==false)
-													{
-														//we found the current portal url
-														$files_list[] = array($second_part,'local','url');
-														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$second_part,$recursivity+1);
-														if(count($in_files_list)>0)
-														{
-															$files_list = array_merge($files_list,$in_files_list);
-														}
-													}
-													else
-													{
-														//we didn't find any trace of current portal
-														$files_list[] = array($second_part,'remote','url');
-													}
-												}
-												elseif(strpos($second_part,'=')>0)
-												{
-													if(substr($second_part,0,1) === '/')
-													{	//link starts with a /, making it absolute (relative to DocumentRoot)
-														$files_list[] = array($second_part,'local','abs');
+													$pos1 = strpos($second_part,'=');
+													$pos2 = strpos($second_part,'&');
+													$second_part = substr($second_part,$pos1+1,$pos2-($pos1+1));
+													if(strpos($second_part,api_get_path(WEB_PATH))!==false)
+													{
+														//we found the current portal url
+														$files_list[] = array($second_part,'local','url');
+														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$second_part,$recursivity+1);
+														if(count($in_files_list)>0)
+														{
+															$files_list = array_merge($files_list,$in_files_list);
+														}
+													}
+													else
+													{
+														//we didn't find any trace of current portal
+														$files_list[] = array($second_part,'remote','url');
+													}
+												}
+												elseif(strpos($second_part,'=')>0)
+												{
+													if(substr($second_part,0,1) === '/')
+													{	//link starts with a /, making it absolute (relative to DocumentRoot)
+														$files_list[] = array($second_part,'local','abs');
 														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$second_part,$recursivity+1);
-														if(count($in_files_list)>0)
-														{
-															$files_list = array_merge($files_list,$in_files_list);
+														if(count($in_files_list)>0)
+														{
+															$files_list = array_merge($files_list,$in_files_list);
 														}
-													}
-													elseif(strstr($second_part,'..') === 0)
-													{	//link is relative but going back in the hierarchy
-														$files_list[] = array($second_part,'local','rel');
-														$dir = dirname($abs_path);
-														$new_abs_path = realpath($dir.'/'.$second_part);
+													}
+													elseif(strstr($second_part,'..') === 0)
+													{	//link is relative but going back in the hierarchy
+														$files_list[] = array($second_part,'local','rel');
+														$dir = dirname($abs_path);
+														$new_abs_path = realpath($dir.'/'.$second_part);
 														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$new_abs_path,$recursivity+1);
-														if(count($in_files_list)>0)
-														{
-															$files_list = array_merge($files_list,$in_files_list);
+														if(count($in_files_list)>0)
+														{
+															$files_list = array_merge($files_list,$in_files_list);
 														}
-													}
-													else
-													{	//no starting '/', making it relative to current document's path
-														if(substr($second_part,0,2) == './')
-														{
-															$second_part = substr($second_part,2);
-														}
-														$files_list[] = array($second_part,'local','rel');
-														$dir = dirname($abs_path);
-														$new_abs_path = realpath($dir.'/'.$second_part);
+													}
+													else
+													{	//no starting '/', making it relative to current document's path
+														if(substr($second_part,0,2) == './')
+														{
+															$second_part = substr($second_part,2);
+														}
+														$files_list[] = array($second_part,'local','rel');
+														$dir = dirname($abs_path);
+														$new_abs_path = realpath($dir.'/'.$second_part);
 														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$new_abs_path,$recursivity+1);
-														if(count($in_files_list)>0)
-														{
-															$files_list = array_merge($files_list,$in_files_list);
+														if(count($in_files_list)>0)
+														{
+															$files_list = array_merge($files_list,$in_files_list);
 														}
-													}
+													}
 
-												}
-												//leave that second part behind now
-												$source = substr($source,0,strpos($source,'?'));
-												if(strpos($source,'://') > 0)
-												{
-													if(strpos($source,api_get_path(WEB_PATH))!==false)
-													{
-														//we found the current portal url
-														$files_list[] = array($source,'local','url');
-														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$source,$recursivity+1);
-														if(count($in_files_list)>0)
-														{
-															$files_list = array_merge($files_list,$in_files_list);
+												}
+												//leave that second part behind now
+												$source = substr($source,0,strpos($source,'?'));
+												if(strpos($source,'://') > 0)
+												{
+													if(strpos($source,api_get_path(WEB_PATH))!==false)
+													{
+														//we found the current portal url
+														$files_list[] = array($source,'local','url');
+														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$source,$recursivity+1);
+														if(count($in_files_list)>0)
+														{
+															$files_list = array_merge($files_list,$in_files_list);
 														}
-													}
-													else
-													{
-														//we didn't find any trace of current portal
-														$files_list[] = array($source,'remote','url');
-													}
-												}
-												else
-												{
-													//no protocol found, make link local
-													if(substr($source,0,1) === '/')
-													{	//link starts with a /, making it absolute (relative to DocumentRoot)
-														$files_list[] = array($source,'local','abs');
+													}
+													else
+													{
+														//we didn't find any trace of current portal
+														$files_list[] = array($source,'remote','url');
+													}
+												}
+												else
+												{
+													//no protocol found, make link local
+													if(substr($source,0,1) === '/')
+													{	//link starts with a /, making it absolute (relative to DocumentRoot)
+														$files_list[] = array($source,'local','abs');
 														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$source,$recursivity+1);
-														if(count($in_files_list)>0)
-														{
-															$files_list = array_merge($files_list,$in_files_list);
+														if(count($in_files_list)>0)
+														{
+															$files_list = array_merge($files_list,$in_files_list);
 														}
-													}
-													elseif(strstr($source,'..') === 0)
-													{	//link is relative but going back in the hierarchy
-														$files_list[] = array($source,'local','rel');
-														$dir = dirname($abs_path);
-														$new_abs_path = realpath($dir.'/'.$source);
+													}
+													elseif(strstr($source,'..') === 0)
+													{	//link is relative but going back in the hierarchy
+														$files_list[] = array($source,'local','rel');
+														$dir = dirname($abs_path);
+														$new_abs_path = realpath($dir.'/'.$source);
 														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$new_abs_path,$recursivity+1);
-														if(count($in_files_list)>0)
-														{
-															$files_list = array_merge($files_list,$in_files_list);
+														if(count($in_files_list)>0)
+														{
+															$files_list = array_merge($files_list,$in_files_list);
+														}
+													}
+													else
+													{	//no starting '/', making it relative to current document's path
+														if(substr($source,0,2) == './')
+														{
+															$source = substr($source,2);
 														}
-													}
-													else
-													{	//no starting '/', making it relative to current document's path
-														if(substr($source,0,2) == './')
-														{
-															$source = substr($source,2);
-														}
-														$files_list[] = array($source,'local','rel');
-														$dir = dirname($abs_path);
-														$new_abs_path = realpath($dir.'/'.$source);
+														$files_list[] = array($source,'local','rel');
+														$dir = dirname($abs_path);
+														$new_abs_path = realpath($dir.'/'.$source);
 														$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$new_abs_path,$recursivity+1);
-														if(count($in_files_list)>0)
-														{
-															$files_list = array_merge($files_list,$in_files_list);
+														if(count($in_files_list)>0)
+														{
+															$files_list = array_merge($files_list,$in_files_list);
 														}
-													}
-												}
-											}
-											//found some protocol there
-											if(strpos($source,api_get_path(WEB_PATH))!==false)
-											{
-												//we found the current portal url
-												$files_list[] = array($source,'local','url');
-												$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$source,$recursivity+1);
-												if(count($in_files_list)>0)
-												{
-													$files_list = array_merge($files_list,$in_files_list);
+													}
 												}
-											}
-											else
-											{
-												//we didn't find any trace of current portal
-												$files_list[] = array($source,'remote','url');
-											}
-										}
-										else
-										{
-											//no protocol found, make link local
-											if(substr($source,0,1) === '/')
-											{	//link starts with a /, making it absolute (relative to DocumentRoot)
-												$files_list[] = array($source,'local','abs');
+											}
+											//found some protocol there
+											if(strpos($source,api_get_path(WEB_PATH))!==false)
+											{
+												//we found the current portal url
+												$files_list[] = array($source,'local','url');
 												$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$source,$recursivity+1);
-												if(count($in_files_list)>0)
-												{
-													$files_list = array_merge($files_list,$in_files_list);
+												if(count($in_files_list)>0)
+												{
+													$files_list = array_merge($files_list,$in_files_list);
 												}
-											}
-											elseif(strstr($source,'..') === 0)
-											{	//link is relative but going back in the hierarchy
-												$files_list[] = array($source,'local','rel');
-												$dir = dirname($abs_path);
-												$new_abs_path = realpath($dir.'/'.$source);
+											}
+											else
+											{
+												//we didn't find any trace of current portal
+												$files_list[] = array($source,'remote','url');
+											}
+										}
+										else
+										{
+											//no protocol found, make link local
+											if(substr($source,0,1) === '/')
+											{	//link starts with a /, making it absolute (relative to DocumentRoot)
+												$files_list[] = array($source,'local','abs');
+												$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$source,$recursivity+1);
+												if(count($in_files_list)>0)
+												{
+													$files_list = array_merge($files_list,$in_files_list);
+												}
+											}
+											elseif(strstr($source,'..') === 0)
+											{	//link is relative but going back in the hierarchy
+												$files_list[] = array($source,'local','rel');
+												$dir = dirname($abs_path);
+												$new_abs_path = realpath($dir.'/'.$source);
 												$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$new_abs_path,$recursivity+1);
-												if(count($in_files_list)>0)
-												{
-													$files_list = array_merge($files_list,$in_files_list);
+												if(count($in_files_list)>0)
+												{
+													$files_list = array_merge($files_list,$in_files_list);
+												}
+											}
+											else
+											{	//no starting '/', making it relative to current document's path
+												if(substr($source,0,2) == './')
+												{
+													$source = substr($source,2);
 												}
-											}
-											else
-											{	//no starting '/', making it relative to current document's path
-												if(substr($source,0,2) == './')
-												{
-													$source = substr($source,2);
-												}
-												$files_list[] = array($source,'local','rel');
-												$dir = dirname($abs_path);
-												$new_abs_path = realpath($dir.'/'.$source);
+												$files_list[] = array($source,'local','rel');
+												$dir = dirname($abs_path);
+												$new_abs_path = realpath($dir.'/'.$source);
 												$in_files_list[] = learnpathItem::get_resources_from_source(TOOL_DOCUMENT,$new_abs_path,$recursivity+1);
-												if(count($in_files_list)>0)
-												{
-													$files_list = array_merge($files_list,$in_files_list);
+												if(count($in_files_list)>0)
+												{
+													$files_list = array_merge($files_list,$in_files_list);
 												}
-											}
-										}
-									}
-								}
-							}
-							break;
-						default:
-							break;
-					}
+											}
+										}
+									}
+								}
+							}
+							break;
+						default:
+							break;
+					}
 
-    			}
-    			else
-    			{
-    				//the file could not be found
-    				return false;
-    			}
-    			break;
-    		default: //ignore
-    			break;
-    	}
-    	//error_log(str_repeat(' ',$recursivity),'found files '.print_r($files_list,true),0);
-		//return $files_list;
-		$checked_files_list = array();
-    	$checked_array_list = array();
-    	foreach($files_list as $idx => $file)
-    	{
-    		if(!empty($file[0]))
-    		{
-	    		if(!in_array($file[0],$checked_files_list))
-	    		{
-	    			$checked_files_list[] = $files_list[$idx][0];
-	    			$checked_array_list[] = $files_list[$idx];
-	    		}
-    		}
-    	}
-    	return $checked_array_list;
-    }
-    /**
-     * Gets the score
-     * @return	float	The current score or 0 if no score set yet
-     */
-    function get_score(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_score()',0);}
-    	$res = 0;
-    	if(!empty($this->current_score))
-    	{
-    		$res = $this->current_score;
-    	}
-    	if($this->debug>1){error_log('New LP - Out of learnpathItem::get_score() - returning '.$res,0);}
-    	return $res;
-    }
-    /**
-     * Gets the item status
-     * @param	boolean	Do or don't check into the database for the latest value. Optional. Default is true
-     * @param	boolean	Do or don't update the local attribute value with what's been found in DB
-     * @return	string	Current status or 'Nnot attempted' if no status set yet
-     */
-    function get_status($check_db=true,$update_local=false) {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_status() on item '.$this->db_id,0);}
-    	if($check_db) {
-    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status(): checking db',0);}
-    		$table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-    		$sql = "SELECT * FROM $table WHERE id = '".$this->db_item_view_id."' AND view_count = '".$this->get_attempt_id()."'";
-    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status() - Checking DB: '.$sql,0);}
-
-    		$res = Database::query($sql);
-    		if (Database::num_rows($res)==1) {
-    			$row = Database::fetch_array($res);
-    			if($update_local==true){
-    				$this->set_status($row['status']);
-    			}
+    			}
+    			else
+    			{
+    				//the file could not be found
+    				return false;
+    			}
+    			break;
+    		default: //ignore
+    			break;
+    	}
+    	//error_log(str_repeat(' ',$recursivity),'found files '.print_r($files_list,true),0);
+		//return $files_list;
+		$checked_files_list = array();
+    	$checked_array_list = array();
+    	foreach($files_list as $idx => $file)
+    	{
+    		if(!empty($file[0]))
+    		{
+	    		if(!in_array($file[0],$checked_files_list))
+	    		{
+	    			$checked_files_list[] = $files_list[$idx][0];
+	    			$checked_array_list[] = $files_list[$idx];
+	    		}
+    		}
+    	}
+    	return $checked_array_list;
+    }
+    /**
+     * Gets the score
+     * @return	float	The current score or 0 if no score set yet
+     */
+    function get_score(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_score()',0);}
+    	$res = 0;
+    	if(!empty($this->current_score))
+    	{
+    		$res = $this->current_score;
+    	}
+    	if($this->debug>1){error_log('New LP - Out of learnpathItem::get_score() - returning '.$res,0);}
+    	return $res;
+    }
+    /**
+     * Gets the item status
+     * @param	boolean	Do or don't check into the database for the latest value. Optional. Default is true
+     * @param	boolean	Do or don't update the local attribute value with what's been found in DB
+     * @return	string	Current status or 'Nnot attempted' if no status set yet
+     */
+    function get_status($check_db=true,$update_local=false) {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_status() on item '.$this->db_id,0);}
+    	if($check_db) {
+    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status(): checking db',0);}
+    		$table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+    		$sql = "SELECT * FROM $table WHERE id = '".$this->db_item_view_id."' AND view_count = '".$this->get_attempt_id()."'";
+    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status() - Checking DB: '.$sql,0);}
+
+    		$res = Database::query($sql);
+    		if (Database::num_rows($res)==1) {
+    			$row = Database::fetch_array($res);
+    			if($update_local==true){
+    				$this->set_status($row['status']);
+    			}
 	    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status() - Returning db value '.$row['status'],0);}
-    			return $row['status'];
-    		}
-    	} else {
-    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status() - in get_status: using attrib',0);}
-	    	if(!empty($this->status)) {
+    			return $row['status'];
+    		}
+    	} else {
+    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status() - in get_status: using attrib',0);}
+	    	if(!empty($this->status)) {
 	    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status() - Returning attrib: '.$this->status,0);}
-	    		return $this->status;
-	    	}
-    	}
+	    		return $this->status;
+	    	}
+    	}
    		if($this->debug>2){error_log('New LP - In learnpathItem::get_status() - Returning default '.$this->possible_status[0],0);}
-    	return $this->possible_status[0];
-    }
-    /**
-     * Gets the suspend data
-     */
-    function get_suspend_data()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_suspend_data()',0);}
-    	//TODO : improve cleaning of breaklines ... it works but is it really a beautiful way to do it ?
-    	if(!empty($this->current_data)){return str_replace(array("\r","\n"),array('\r','\n'),$this->current_data);}else{return '';}
-    }
-    /**
-     * Gets the total time spent on this item view so far
-     * @param	string	Origin of the request. If coming from PHP, send formatted as xxhxx'xx", otherwise use scorm format 00:00:00
-     * @param	integer	Given time is a default time to return formatted
-     */
-    function get_scorm_time($origin='php',$given_time=null){
-    	//if($this->debug>0){error_log('New LP - In learnpathItem::get_scorm_time()',0);}
-    	$h = get_lang('h');
-    	if(!isset($given_time)){
-	    	if(!empty($this->current_start_time) && is_object($this)){
-	    		if(!empty($this->current_stop_time)){
-	    			$time = $this->current_stop_time - $this->current_start_time;
-	    		}else{
-	    			$time = time() - $this->current_start_time;
-	    		}
-	    	}else{
-	    		if($origin == 'js'){
-	    			return '00:00:00';
-	    		}else{
-	    			return '00'.$h.'00\'00"';
-	    		}
-	    	}
-    	}else{
-    		$time = $given_time;
-    	}
-		$hours = $time/3600;
-		$mins  = ($time%3600)/60;
-		$secs  = ($time%60);
-  		if($origin == 'js'){
-			$scorm_time = trim(sprintf("%4d:%02d:%02d",$hours,$mins,$secs));
-  		}else{
-			$scorm_time = trim(sprintf("%4d$h%02d'%02d\"",$hours,$mins,$secs));
-  		}
-		return $scorm_time;
-    }
+    	return $this->possible_status[0];
+    }
+    /**
+     * Gets the suspend data
+     */
+    function get_suspend_data()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_suspend_data()',0);}
+    	//TODO : improve cleaning of breaklines ... it works but is it really a beautiful way to do it ?
+    	if(!empty($this->current_data)){return str_replace(array("\r","\n"),array('\r','\n'),$this->current_data);}else{return '';}
+    }
+    /**
+     * Gets the total time spent on this item view so far
+     * @param	string	Origin of the request. If coming from PHP, send formatted as xxhxx'xx", otherwise use scorm format 00:00:00
+     * @param	integer	Given time is a default time to return formatted
+     */
+    function get_scorm_time($origin='php',$given_time=null){
+    	//if($this->debug>0){error_log('New LP - In learnpathItem::get_scorm_time()',0);}
+    	$h = get_lang('h');
+    	if(!isset($given_time)){
+	    	if(!empty($this->current_start_time) && is_object($this)){
+	    		if(!empty($this->current_stop_time)){
+	    			$time = $this->current_stop_time - $this->current_start_time;
+	    		}else{
+	    			$time = time() - $this->current_start_time;
+	    		}
+	    	}else{
+	    		if($origin == 'js'){
+	    			return '00:00:00';
+	    		}else{
+	    			return '00'.$h.'00\'00"';
+	    		}
+	    	}
+    	}else{
+    		$time = $given_time;
+    	}
+		$hours = $time/3600;
+		$mins  = ($time%3600)/60;
+		$secs  = ($time%60);
+  		if($origin == 'js'){
+			$scorm_time = trim(sprintf("%4d:%02d:%02d",$hours,$mins,$secs));
+  		}else{
+			$scorm_time = trim(sprintf("%4d$h%02d'%02d\"",$hours,$mins,$secs));
+  		}
+		return $scorm_time;
+    }
 
-function get_terms()
-          {
-                $lp_item = Database::get_course_table(TABLE_LP_ITEM);
-                $sql = "SELECT * FROM $lp_item WHERE id='".Database::escape_string($this->db_id)."'";
-                $res = Database::query($sql,__FILE__,__LINE__);
-                $row = Database::fetch_array($res);
-                return $row['terms'];
-          }
-    /**
-     * Returns the item's title
-     * @return	string	Title
-     */
-    function get_title(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_title()',0);}
-    	if(empty($this->title)){return '';}
-    	return $this->title;
-    }
-    /**
-     * Returns the total time used to see that item
-     * @return	integer	Total time
-     */
-    function get_total_time(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_total_time()',0);}
-    	if($this->current_start_time == 0){ //shouldn't be necessary thanks to the open() method
-    		$this->current_start_time = time();
-    	}
-    	//$this->current_stop_time=time();
-    	$time = $this->current_stop_time - $this->current_start_time;
-    	if($time < 0){
-    		return 0;
-    	}else{
-    	if($this->debug>2){error_log('New LP - In learnpathItem::get_total_time() - Current stop time = '.$this->current_stop_time.', current start time = '.$this->current_start_time.' Returning '.$time,0);}
-    		return $time;
-    	}
-    }
-    /**
-     * Gets the item type
-     * @return	string	The item type (can be doc, dir, sco, asset)
-     */
-    function get_type()
-    {
-    	$res = 'asset';
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_type() on item '.$this->db_id,0);}
-    	if(!empty($this->type))
-    	{
-    		//error_log('In item::get_type() - returning '.$this->type,0);
-    		$res = $this->type;
-    	}
-    	if($this->debug>2){error_log('New LP - In learnpathItem::get_type() - Returning '.$res.' for item '.$this->db_id,0);}
+function get_terms()
+          {
+                $lp_item = Database::get_course_table(TABLE_LP_ITEM);
+                $sql = "SELECT * FROM $lp_item WHERE id='".Database::escape_string($this->db_id)."'";
+                $res = Database::query($sql,__FILE__,__LINE__);
+                $row = Database::fetch_array($res);
+                return $row['terms'];
+          }
+    /**
+     * Returns the item's title
+     * @return	string	Title
+     */
+    function get_title(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_title()',0);}
+    	if(empty($this->title)){return '';}
+    	return $this->title;
+    }
+    /**
+     * Returns the total time used to see that item
+     * @return	integer	Total time
+     */
+    function get_total_time(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_total_time()',0);}
+    	if($this->current_start_time == 0){ //shouldn't be necessary thanks to the open() method
+    		$this->current_start_time = time();
+    	}
+    	//$this->current_stop_time=time();
+    	$time = $this->current_stop_time - $this->current_start_time;
+    	if($time < 0){
+    		return 0;
+    	}else{
+    	if($this->debug>2){error_log('New LP - In learnpathItem::get_total_time() - Current stop time = '.$this->current_stop_time.', current start time = '.$this->current_start_time.' Returning '.$time,0);}
+    		return $time;
+    	}
+    }
+    /**
+     * Gets the item type
+     * @return	string	The item type (can be doc, dir, sco, asset)
+     */
+    function get_type()
+    {
+    	$res = 'asset';
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_type() on item '.$this->db_id,0);}
+    	if(!empty($this->type))
+    	{
+    		//error_log('In item::get_type() - returning '.$this->type,0);
+    		$res = $this->type;
+    	}
+    	if($this->debug>2){error_log('New LP - In learnpathItem::get_type() - Returning '.$res.' for item '.$this->db_id,0);}
     	return $res;
-    }
-    /**
-     * Gets the view count for this item
-     */
-	function get_view_count(){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::get_view_count()',0);}
-		if(!empty($this->attempt_id)){
-			return $this->attempt_id;
-		}else{
-			return 0;
-		}
-	}
-	/**
-	 * Tells if an item is done ('completed','passed','succeeded') or not
-	 * @return	bool	True if the item is done ('completed','passed','succeeded'), false otherwise
-	 */
-	function is_done(){
-   		if($this->status_is(array('completed','passed','succeeded'))){
-   			if($this->debug>2){error_log('New LP - In learnpath::is_done() - Item '.$this->get_id().' is complete',0);}
-   			return true;
-   		}else{
-   			if($this->debug>2){error_log('New LP - In learnpath::is_done() - Item '.$this->get_id().' is not complete',0);}
-   			return false;
-   		}
-	}
-	/**
-	 * Tells if a restart is allowed (take it from $this->prevent_reinit and $this->status)
-	 * @return	integer	-1 if retaking the sco another time for credit is not allowed,
+    }
+    /**
+     * Gets the view count for this item
+     */
+	function get_view_count(){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::get_view_count()',0);}
+		if(!empty($this->attempt_id)){
+			return $this->attempt_id;
+		}else{
+			return 0;
+		}
+	}
+	/**
+	 * Tells if an item is done ('completed','passed','succeeded') or not
+	 * @return	bool	True if the item is done ('completed','passed','succeeded'), false otherwise
+	 */
+	function is_done(){
+   		if($this->status_is(array('completed','passed','succeeded'))){
+   			if($this->debug>2){error_log('New LP - In learnpath::is_done() - Item '.$this->get_id().' is complete',0);}
+   			return true;
+   		}else{
+   			if($this->debug>2){error_log('New LP - In learnpath::is_done() - Item '.$this->get_id().' is not complete',0);}
+   			return false;
+   		}
+	}
+	/**
+	 * Tells if a restart is allowed (take it from $this->prevent_reinit and $this->status)
+	 * @return	integer	-1 if retaking the sco another time for credit is not allowed,
 	 * 					 0 if it is not allowed but the item has to be finished
-	 * 					 1 if it is allowed. Defaults to 1
-	 */
-	function is_restart_allowed()
-	{
-		if($this->debug>2){error_log('New LP - In learnpathItem::is_restart_allowed()',0);}
-		$restart = 1;
-		$mystatus = $this->get_status(true);
-		if($this->get_prevent_reinit() > 0){ //if prevent_reinit == 1 (or more)
-			//if status is not attempted or incomplete, authorize retaking (of the same) anyway. Otherwise:
-			if($mystatus != $this->possible_status[0] AND $mystatus != $this->possible_status[1]){
-				$restart = -1;
-			}else{
-				$restart = 0;
-			}
-		}else{
-			if($mystatus == $this->possible_status[0] OR $mystatus == $this->possible_status[1]){
-				$restart = -1;
-			}
-		}
-		if($this->debug>2){error_log('New LP - End of learnpathItem::is_restart_allowed() - Returning '.$restart,0);}
-		return $restart;
-	}
-    /**
-     * Opens/launches the item. Initialises runtime values.
-     * @return	boolean	True on success, false on failure.
-     */
-    function open($allow_new_attempt=false){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::open()',0);}
-    	if($this->prevent_reinit == 0)
-    	{
-	    	$this->current_score = 0;
-	    	$this->current_start_time = time();
-	    	//In this case, as we are opening the item, what is important to us
-	    	//is the database status, in order to know if this item has already
-	    	//been used in the past (rather than just loaded and modified by
-	    	//some javascript but not written in the database).
-	    	//If the database status is different from 'not attempted', we can
-	    	//consider this item has already been used, and as such we can
-	    	//open a new attempt. Otherwise, we'll just reuse the current
-	    	//attempt, which is generally created the first time the item is
-	    	//loaded (for example as part of the table of contents)
-	    	$stat = $this->get_status(true);
-	    	if($allow_new_attempt && isset($stat) && ($stat != $this->possible_status[0]))
-	    	{
-	    		$this->attempt_id = $this->attempt_id + 1; //open a new attempt
-	    	}
-	    	$this->status = $this->possible_status[1];
-    	}
-    	else
-    	{
-    		if($this->current_start_time == 0)
-    		{ //small exception for start time, to avoid amazing values
-    			$this->current_start_time = time();
-    		}
-    		//error_log('New LP - reinit blocked by setting',0);
-    	}
-    }
-    /**
-     * Outputs the item contents
-     * @return	string	HTML file (displayable in an <iframe>) or empty string if no path defined
-     */
-    function output()
-    {
-    	if($this->debug>0){error_log('New LP - In learnpathItem::output()',0);}
-    	if(!empty($this->path) and is_file($this->path))
-    	{
-	    	$output = '';
-	    	$output .= file_get_contents($this->path);
-	    	return $output;
-    	}
-    	return '';
-    }
-    /**
-     * Parses the prerequisites string with the AICC logic language
-     * @param	string	The prerequisites string as it figures in imsmanifest.xml
-     * @param	Array	Array of items in the current learnpath object. Although we're in the learnpathItem object, it's necessary to have a list of all items to be able to check the current item's prerequisites
-	 * @param	Array	List of references (the "ref" column in the lp_item table) that are strings used in the expression of prerequisites.
-	 * @param	integer	The user ID. In some cases like Dokeos quizzes, it's necessary to have the user ID to query other tables (like the results of quizzes)
-     * @return	boolean	True if the list of prerequisites given is entirely satisfied, false otherwise
-     */
-    function parse_prereq($prereqs_string, $items, $refs_list,$user_id){
-    	if($this->debug>0){error_log('New LP - In learnpathItem::parse_prereq() for learnpath '.$this->lp_id.' with string '.$prereqs_string,0);}
-    	//deal with &, |, ~, =, <>, {}, ,, X*, () in reverse order
-		$this->prereq_alert = '';
-		// First parse all parenthesis by using a sequential loop (looking for less-inclusives first)
-		if($prereqs_string == '_true_'){return true;}
+	 * 					 1 if it is allowed. Defaults to 1
+	 */
+	function is_restart_allowed()
+	{
+		if($this->debug>2){error_log('New LP - In learnpathItem::is_restart_allowed()',0);}
+		$restart = 1;
+		$mystatus = $this->get_status(true);
+		if($this->get_prevent_reinit() > 0){ //if prevent_reinit == 1 (or more)
+			//if status is not attempted or incomplete, authorize retaking (of the same) anyway. Otherwise:
+			if($mystatus != $this->possible_status[0] AND $mystatus != $this->possible_status[1]){
+				$restart = -1;
+			}else{
+				$restart = 0;
+			}
+		}else{
+			if($mystatus == $this->possible_status[0] OR $mystatus == $this->possible_status[1]){
+				$restart = -1;
+			}
+		}
+		if($this->debug>2){error_log('New LP - End of learnpathItem::is_restart_allowed() - Returning '.$restart,0);}
+		return $restart;
+	}
+    /**
+     * Opens/launches the item. Initialises runtime values.
+     * @return	boolean	True on success, false on failure.
+     */
+    function open($allow_new_attempt=false){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::open()',0);}
+    	if($this->prevent_reinit == 0)
+    	{
+	    	$this->current_score = 0;
+	    	$this->current_start_time = time();
+	    	//In this case, as we are opening the item, what is important to us
+	    	//is the database status, in order to know if this item has already
+	    	//been used in the past (rather than just loaded and modified by
+	    	//some javascript but not written in the database).
+	    	//If the database status is different from 'not attempted', we can
+	    	//consider this item has already been used, and as such we can
+	    	//open a new attempt. Otherwise, we'll just reuse the current
+	    	//attempt, which is generally created the first time the item is
+	    	//loaded (for example as part of the table of contents)
+	    	$stat = $this->get_status(true);
+	    	if($allow_new_attempt && isset($stat) && ($stat != $this->possible_status[0]))
+	    	{
+	    		$this->attempt_id = $this->attempt_id + 1; //open a new attempt
+	    	}
+	    	$this->status = $this->possible_status[1];
+    	}
+    	else
+    	{
+    		if($this->current_start_time == 0)
+    		{ //small exception for start time, to avoid amazing values
+    			$this->current_start_time = time();
+    		}
+    		//error_log('New LP - reinit blocked by setting',0);
+    	}
+    }
+    /**
+     * Outputs the item contents
+     * @return	string	HTML file (displayable in an <iframe>) or empty string if no path defined
+     */
+    function output()
+    {
+    	if($this->debug>0){error_log('New LP - In learnpathItem::output()',0);}
+    	if(!empty($this->path) and is_file($this->path))
+    	{
+	    	$output = '';
+	    	$output .= file_get_contents($this->path);
+	    	return $output;
+    	}
+    	return '';
+    }
+    /**
+     * Parses the prerequisites string with the AICC logic language
+     * @param	string	The prerequisites string as it figures in imsmanifest.xml
+     * @param	Array	Array of items in the current learnpath object. Although we're in the learnpathItem object, it's necessary to have a list of all items to be able to check the current item's prerequisites
+	 * @param	Array	List of references (the "ref" column in the lp_item table) that are strings used in the expression of prerequisites.
+	 * @param	integer	The user ID. In some cases like Dokeos quizzes, it's necessary to have the user ID to query other tables (like the results of quizzes)
+     * @return	boolean	True if the list of prerequisites given is entirely satisfied, false otherwise
+     */
+    function parse_prereq($prereqs_string, $items, $refs_list,$user_id){
+    	if($this->debug>0){error_log('New LP - In learnpathItem::parse_prereq() for learnpath '.$this->lp_id.' with string '.$prereqs_string,0);}
+    	//deal with &, |, ~, =, <>, {}, ,, X*, () in reverse order
+		$this->prereq_alert = '';
+		// First parse all parenthesis by using a sequential loop (looking for less-inclusives first)
+		if($prereqs_string == '_true_'){return true;}
 		if($prereqs_string == '_false_'){
-			if(empty($this->prereq_alert)){
-    			$this->prereq_alert = get_lang('_prereq_not_complete');
-    		}
-			return false;
+			if(empty($this->prereq_alert)){
+    			$this->prereq_alert = get_lang('_prereq_not_complete');
+    		}
+			return false;
+		}
+		while(strpos($prereqs_string,'(')!==false){
+			//remove any () set and replace with its value
+			$matches = array();
+			$res = preg_match_all('/(\(([^\(\)]*)\))/',$prereqs_string,$matches);
+			if($res){
+				foreach($matches[2] as $id=>$match){
+					$str_res = $this->parse_prereq($match,$items,$refs_list,$user_id);
+					if($str_res){
+						$prereqs_string = str_replace($matches[1][$id],'_true_',$prereqs_string);
+					}else{
+						$prereqs_string = str_replace($matches[1][$id],'_false_',$prereqs_string);
+					}
+				}
+			}
 		}
-		while(strpos($prereqs_string,'(')!==false){
-			//remove any () set and replace with its value
-			$matches = array();
-			$res = preg_match_all('/(\(([^\(\)]*)\))/',$prereqs_string,$matches);
-			if($res){
-				foreach($matches[2] as $id=>$match){
-					$str_res = $this->parse_prereq($match,$items,$refs_list,$user_id);
-					if($str_res){
-						$prereqs_string = str_replace($matches[1][$id],'_true_',$prereqs_string);
-					}else{
-						$prereqs_string = str_replace($matches[1][$id],'_false_',$prereqs_string);
-					}
-				}
-			}
-		}
 
-		//parenthesis removed, now look for ORs as it is the lesser-priority binary operator (= always uses one text operand)
-		if(strpos($prereqs_string,"|")===false){
-    		if($this->debug>1){error_log('New LP - Didnt find any OR, looking for AND',0);}
-	    	if(strpos($prereqs_string,"&")!==false){
-	    		$list = split("&",$prereqs_string);
-	    		if(count($list)>1){
-					$andstatus = true;
-					foreach($list as $condition){
-	    				$andstatus = $andstatus && $this->parse_prereq($condition,$items,$refs_list,$user_id);
-	    				if($andstatus==false){
-							if($this->debug>1){error_log('New LP - One condition in AND was false, short-circuit',0);}
+		//parenthesis removed, now look for ORs as it is the lesser-priority binary operator (= always uses one text operand)
+		if(strpos($prereqs_string,"|")===false){
+    		if($this->debug>1){error_log('New LP - Didnt find any OR, looking for AND',0);}
+	    	if(strpos($prereqs_string,"&")!==false){
+	    		$list = split("&",$prereqs_string);
+	    		if(count($list)>1){
+					$andstatus = true;
+					foreach($list as $condition){
+	    				$andstatus = $andstatus && $this->parse_prereq($condition,$items,$refs_list,$user_id);
+	    				if($andstatus==false){
+							if($this->debug>1){error_log('New LP - One condition in AND was false, short-circuit',0);}
 							break;
-	    				}
-					}
-					if(empty($this->prereq_alert) && !$andstatus){
-    					$this->prereq_alert = get_lang('_prereq_not_complete');
-    				}
-					return $andstatus;
-	    		}else{
-	    			if(isset($items[$refs_list[$list[0]]])){
-	    				$status = $items[$refs_list[$list[0]]]->get_status(true);
-		    			$returnstatus = (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3]));
-				    	if(empty($this->prereq_alert) && !$returnstatus){
-				    		$this->prereq_alert = get_lang('_prereq_not_complete');
-				    	}
-		    			return $returnstatus;
-	    			}
-		    		$this->prereq_alert = get_lang('_prereq_not_complete');
-					return false;
-	    		}
-	    	}else{
+	    				}
+					}
+					if(empty($this->prereq_alert) && !$andstatus){
+    					$this->prereq_alert = get_lang('_prereq_not_complete');
+    				}
+					return $andstatus;
+	    		}else{
+	    			if(isset($items[$refs_list[$list[0]]])){
+	    				$status = $items[$refs_list[$list[0]]]->get_status(true);
+		    			$returnstatus = (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3]));
+				    	if(empty($this->prereq_alert) && !$returnstatus){
+				    		$this->prereq_alert = get_lang('_prereq_not_complete');
+				    	}
+		    			return $returnstatus;
+	    			}
+		    		$this->prereq_alert = get_lang('_prereq_not_complete');
+					return false;
+	    		}
+	    	}else{
 
-	    		//no ORs found, now look for ANDs
+	    		//no ORs found, now look for ANDs
 
     			if($this->debug>1){error_log('New LP - Didnt find any AND, looking for =',0);}
-	    		if(strpos($prereqs_string,"=")!==false){
-		    		if($this->debug>1){error_log('New LP - Found =, looking into it',0);}
-		    		//we assume '=' signs only appear when there's nothing else around
-		    		$params = split('=',$prereqs_string);
-		    		if(count($params) == 2){
-		    			//right number of operands
-		    			if(isset($items[$refs_list[$params[0]]])){
-		    				$status = $items[$refs_list[$params[0]]]->get_status(true);
-			    			$returnstatus = ($status == $params[1]);
-					    	if(empty($this->prereq_alert) && !$returnstatus){
-					    		$this->prereq_alert = get_lang('_prereq_not_complete');
-					    	}
-			    			return $returnstatus;
-		    			}
-			    		$this->prereq_alert = get_lang('_prereq_not_complete');
-						return false;
-		    		}
-	    		}else{
+	    		if(strpos($prereqs_string,"=")!==false){
+		    		if($this->debug>1){error_log('New LP - Found =, looking into it',0);}
+		    		//we assume '=' signs only appear when there's nothing else around
+		    		$params = split('=',$prereqs_string);
+		    		if(count($params) == 2){
+		    			//right number of operands
+		    			if(isset($items[$refs_list[$params[0]]])){
+		    				$status = $items[$refs_list[$params[0]]]->get_status(true);
+			    			$returnstatus = ($status == $params[1]);
+					    	if(empty($this->prereq_alert) && !$returnstatus){
+					    		$this->prereq_alert = get_lang('_prereq_not_complete');
+					    	}
+			    			return $returnstatus;
+		    			}
+			    		$this->prereq_alert = get_lang('_prereq_not_complete');
+						return false;
+		    		}
+	    		}else{
 
-	    			//No ANDs found, look for <>
+	    			//No ANDs found, look for <>
 
 	    			if($this->debug>1){error_log('New LP - Didnt find any =, looking for <>',0);}
-		    		if(strpos($prereqs_string,"<>")!==false){
-			    		if($this->debug>1){error_log('New LP - Found <>, looking into it',0);}
-			    		//we assume '<>' signs only appear when there's nothing else around
-			    		$params = split('<>',$prereqs_string);
-			    		if(count($params) == 2){
-			    			//right number of operands
-			    			if(isset($items[$refs_list[$params[0]]])){
-			    				$status = $items[$refs_list[$params[0]]]->get_status(true);
-				    			$returnstatus =  ($status != $params[1]);
-						    	if(empty($this->prereq_alert) && !$returnstatus){
-						    		$this->prereq_alert = get_lang('_prereq_not_complete');
-						    	}
-				    			return $returnstatus;
-			    			}
-				    		$this->prereq_alert = get_lang('_prereq_not_complete');
-			    			return false;
-			    		}
-		    		}else{
+		    		if(strpos($prereqs_string,"<>")!==false){
+			    		if($this->debug>1){error_log('New LP - Found <>, looking into it',0);}
+			    		//we assume '<>' signs only appear when there's nothing else around
+			    		$params = split('<>',$prereqs_string);
+			    		if(count($params) == 2){
+			    			//right number of operands
+			    			if(isset($items[$refs_list[$params[0]]])){
+			    				$status = $items[$refs_list[$params[0]]]->get_status(true);
+				    			$returnstatus =  ($status != $params[1]);
+						    	if(empty($this->prereq_alert) && !$returnstatus){
+						    		$this->prereq_alert = get_lang('_prereq_not_complete');
+						    	}
+				    			return $returnstatus;
+			    			}
+				    		$this->prereq_alert = get_lang('_prereq_not_complete');
+			    			return false;
+			    		}
+		    		}else{
 
-		    			//No <> found, look for ~ (unary)
+		    			//No <> found, look for ~ (unary)
 
-		    			if($this->debug>1){error_log('New LP - Didnt find any =, looking for ~',0);}
-		    			//only remains: ~ and X*{}
-		    			if(strpos($prereqs_string,"~")!==false){
-		    				//found NOT
-				    		if($this->debug>1){error_log('New LP - Found ~, looking into it',0);}
-		    				$list = array();
-		    				$myres = preg_match('/~([^(\d+\*)\{]*)/',$prereqs_string,$list);
-		    				if($myres){
-		    					$returnstatus = !$this->parse_prereq($list[1],$items,$refs_list,$user_id);
-						    	if(empty($this->prereq_alert) && !$returnstatus){
-						    		$this->prereq_alert = get_lang('_prereq_not_complete');
-						    	}
-								return $returnstatus;
-		    				}else{
-		    					//strange...
-					    		if($this->debug>1){error_log('New LP - Found ~ but strange string: '.$prereqs_string,0);}
-		    				}
-		    			}else{
+		    			if($this->debug>1){error_log('New LP - Didnt find any =, looking for ~',0);}
+		    			//only remains: ~ and X*{}
+		    			if(strpos($prereqs_string,"~")!==false){
+		    				//found NOT
+				    		if($this->debug>1){error_log('New LP - Found ~, looking into it',0);}
+		    				$list = array();
+		    				$myres = preg_match('/~([^(\d+\*)\{]*)/',$prereqs_string,$list);
+		    				if($myres){
+		    					$returnstatus = !$this->parse_prereq($list[1],$items,$refs_list,$user_id);
+						    	if(empty($this->prereq_alert) && !$returnstatus){
+						    		$this->prereq_alert = get_lang('_prereq_not_complete');
+						    	}
+								return $returnstatus;
+		    				}else{
+		    					//strange...
+					    		if($this->debug>1){error_log('New LP - Found ~ but strange string: '.$prereqs_string,0);}
+		    				}
+		    			}else{
 
-		    				//Finally, look for sets/groups
+		    				//Finally, look for sets/groups
 
 			    			if($this->debug>1){error_log('New LP - Didnt find any ~, looking for groups',0);}
-		    				//only groups here
-					    	$groups = array();
-					    	$groups_there = preg_match_all('/((\d+\*)?\{([^\}]+)\}+)/',$prereqs_string,$groups);
-					    	if($groups_there){
-						    	foreach($groups[1] as $gr) //only take the results that correspond to the big brackets-enclosed condition
-						    	{
-						    		if($this->debug>1){error_log('New LP - Dealing with group '.$gr,0);}
-						    		$multi = array();
-									$mycond = false;
-						    		if(preg_match('/(\d+)\*\{([^\}]+)\}/',$gr,$multi)){
-						    			if($this->debug>1){error_log('New LP - Found multiplier '.$multi[0],0);}
-						    			$count = $multi[1];
-						    			$list = split(',',$multi[2]);
-						    			$mytrue = 0;
-						    			foreach($list as $cond){
-							    			if(isset($items[$refs_list[$cond]])){
-							    				$status = $items[$refs_list[$cond]]->get_status(true);
-								    			if (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3])){
-						    						$mytrue ++;
-						    						if($this->debug>1){error_log('New LP - Found true item, counting.. ('.($mytrue).')',0);}
-								    			}
-						    				}else{
-							    				if($this->debug>1){error_log('New LP - item '.$cond.' does not exist in items list',0);}
-							    			}
-						    			}
-										if($mytrue >= $count){
-					    					if($this->debug>1){error_log('New LP - Got enough true results, return true',0);}
-											$mycond = true;
-										}else{
-					    					if($this->debug>1){error_log('New LP - Not enough true results',0);}
-										}
-						    		}
-						    		else{
-						    			if($this->debug>1){error_log('New LP - No multiplier',0);}
-						    			$list = split(',',$gr);
-						    			$mycond = true;
-						    			foreach($list as $cond){
-							    			if(isset($items[$refs_list[$cond]])){
-							    				$status = $items[$refs_list[$cond]]->get_status(true);
-								    			if (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3])){
-						    						$mycond = true;
+		    				//only groups here
+					    	$groups = array();
+					    	$groups_there = preg_match_all('/((\d+\*)?\{([^\}]+)\}+)/',$prereqs_string,$groups);
+					    	if($groups_there){
+						    	foreach($groups[1] as $gr) //only take the results that correspond to the big brackets-enclosed condition
+						    	{
+						    		if($this->debug>1){error_log('New LP - Dealing with group '.$gr,0);}
+						    		$multi = array();
+									$mycond = false;
+						    		if(preg_match('/(\d+)\*\{([^\}]+)\}/',$gr,$multi)){
+						    			if($this->debug>1){error_log('New LP - Found multiplier '.$multi[0],0);}
+						    			$count = $multi[1];
+						    			$list = split(',',$multi[2]);
+						    			$mytrue = 0;
+						    			foreach($list as $cond){
+							    			if(isset($items[$refs_list[$cond]])){
+							    				$status = $items[$refs_list[$cond]]->get_status(true);
+								    			if (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3])){
+						    						$mytrue ++;
+						    						if($this->debug>1){error_log('New LP - Found true item, counting.. ('.($mytrue).')',0);}
+								    			}
+						    				}else{
+							    				if($this->debug>1){error_log('New LP - item '.$cond.' does not exist in items list',0);}
+							    			}
+						    			}
+										if($mytrue >= $count){
+					    					if($this->debug>1){error_log('New LP - Got enough true results, return true',0);}
+											$mycond = true;
+										}else{
+					    					if($this->debug>1){error_log('New LP - Not enough true results',0);}
+										}
+						    		}
+						    		else{
+						    			if($this->debug>1){error_log('New LP - No multiplier',0);}
+						    			$list = split(',',$gr);
+						    			$mycond = true;
+						    			foreach($list as $cond){
+							    			if(isset($items[$refs_list[$cond]])){
+							    				$status = $items[$refs_list[$cond]]->get_status(true);
+								    			if (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3])){
+						    						$mycond = true;
 							    					if($this->debug>1){error_log('New LP - Found true item',0);}
-								    			}else{
+								    			}else{
 							    					if($this->debug>1){error_log('New LP - Found false item, the set is not true, return false',0);}
-								    				$mycond = false;
-								    				break;
-								    			}
-						    				}else{
-							    				if($this->debug>1){error_log('New LP - item '.$cond.' does not exist in items list',0);}
+								    				$mycond = false;
+								    				break;
+								    			}
+						    				}else{
+							    				if($this->debug>1){error_log('New LP - item '.$cond.' does not exist in items list',0);}
 						    					if($this->debug>1){error_log('New LP - Found false item, the set is not true, return false',0);}
-							    				$mycond = false;
-							    				break;
-							    			}
-						    			}
-						    		}
-							    	if(!$mycond && empty($this->prereq_alert)){
-							    		$this->prereq_alert = get_lang('_prereq_not_complete');
-							    	}
-						    		return $mycond;
-						    	}
-					    	}else{
+							    				$mycond = false;
+							    				break;
+							    			}
+						    			}
+						    		}
+							    	if(!$mycond && empty($this->prereq_alert)){
+							    		$this->prereq_alert = get_lang('_prereq_not_complete');
+							    	}
+						    		return $mycond;
+						    	}
+					    	}else{
 
-					    		//Nothing found there either. Now return the value of the corresponding resource completion status
+					    		//Nothing found there either. Now return the value of the corresponding resource completion status
 
-				    			if($this->debug>1){error_log('New LP - Didnt find any group, returning value for '.$prereqs_string,0);}
+				    			if($this->debug>1){error_log('New LP - Didnt find any group, returning value for '.$prereqs_string,0);}
 				    			if(isset($items[$refs_list[$prereqs_string]])){
-				    				if($items[$refs_list[$prereqs_string]]->type == 'quiz')
-				    				{
-				    					$sql = 'SELECT exe_result, exe_weighting
-												FROM '.Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES).'
+				    				if($items[$refs_list[$prereqs_string]]->type == 'quiz')
+				    				{
+				    					$sql = 'SELECT exe_result, exe_weighting
+												FROM '.Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES).'
 												WHERE exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.'
-												AND exe_user_id = '.$user_id.'
+												AND exe_user_id = '.$user_id.'
 												AND status <> "incomplete"
-												ORDER BY exe_date DESC
-												LIMIT 0, 1';
-										$rs_quiz = Database::query($sql, __FILE__, __LINE__);
-										if($quiz = Database :: fetch_array($rs_quiz))
-										{
-											if($quiz['exe_result'] >= $items[$refs_list[$prereqs_string]]->get_mastery_score())
-											{
-												$returnstatus = true;
-											}
-											else
-											{
-												$this->prereq_alert = get_lang('_prereq_not_complete');
-												$returnstatus = false;
-											}
-										}
-										else
-										{
-											$this->prereq_alert = get_lang('_prereq_not_complete');
-											$returnstatus = false;
-										}
-										return $returnstatus;
-				    				}
-				    				else
-				    				{
-					    				$status = $items[$refs_list[$prereqs_string]]->get_status(true);
-						    			$returnstatus = (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3]));
-								    	if(!$returnstatus && empty($this->prereq_alert)){
-								    		$this->prereq_alert = get_lang('_prereq_not_complete');
-								    	}
-								    	if(!$returnstatus){
-								    		if($this->debug>1){error_log('New LP - Prerequisite '.$prereqs_string.' not complete',0);}
-								    	}else{
-								    		if($this->debug>1){error_log('New LP - Prerequisite '.$prereqs_string.' complete',0);}
-								    	}
-						    			return $returnstatus;
-				    				}
-				    			}else{
-				    				if($this->debug>1){error_log('New LP - Could not find '.$prereqs_string.' in '.print_r($refs_list,true),0);}
-				    			}
-					    	}
-		    			}
-		    		}
-	    		}
-	    	}
-    	}else{
-    		$list = split("\|",$prereqs_string);
-    		if(count($list)>1){
-	    		if($this->debug>1){error_log('New LP - Found OR, looking into it',0);}
-				$orstatus = false;
-				foreach($list as $condition){
-					if($this->debug>1){error_log('New LP - Found OR, adding it ('.$condition.')',0);}
-    				$orstatus = $orstatus || $this->parse_prereq($condition,$items,$refs_list,$user_id);
-    				if($orstatus == true){
-    					//shortcircuit OR
-						if($this->debug>1){error_log('New LP - One condition in OR was true, short-circuit',0);}
-    					break;
-    				}
-				}
-		    	if(!$orstatus && empty($this->prereq_alert)){
-		    		$this->prereq_alert = get_lang('_prereq_not_complete');
-		    	}
-				return $orstatus;
-    		}else{
-	    		if($this->debug>1){error_log('New LP - OR was found but only one elem present !?',0);}
-    			if(isset($items[$refs_list[$list[0]]])){
-    				$status = $items[$refs_list[$list[0]]]->get_status(true);
-	    			$returnstatus = (($status == 'completed') OR ($status == 'passed'));
-			    	if(!$returnstatus && empty($this->prereq_alert)){
-			    		$this->prereq_alert = get_lang('_prereq_not_complete');
-			    	}
-	    			return $returnstatus;
-    			}
-    		}
-    	}
-    	if(empty($this->prereq_alert)){
-    		$this->prereq_alert = get_lang('_prereq_not_complete');
-    	}
-    	if($this->debug>1){error_log('New LP - End of parse_prereq. Error code is now '.$this->prereq_alert,0);}
-    	return false;
-    }
-    /**
-	 * Parses the HTML attributes given as string.
+												ORDER BY exe_date DESC
+												LIMIT 0, 1';
+										$rs_quiz = Database::query($sql, __FILE__, __LINE__);
+										if($quiz = Database :: fetch_array($rs_quiz))
+										{
+											if($quiz['exe_result'] >= $items[$refs_list[$prereqs_string]]->get_mastery_score())
+											{
+												$returnstatus = true;
+											}
+											else
+											{
+												$this->prereq_alert = get_lang('_prereq_not_complete');
+												$returnstatus = false;
+											}
+										}
+										else
+										{
+											$this->prereq_alert = get_lang('_prereq_not_complete');
+											$returnstatus = false;
+										}
+										return $returnstatus;
+				    				}
+				    				else
+				    				{
+					    				$status = $items[$refs_list[$prereqs_string]]->get_status(true);
+						    			$returnstatus = (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3]));
+								    	if(!$returnstatus && empty($this->prereq_alert)){
+								    		$this->prereq_alert = get_lang('_prereq_not_complete');
+								    	}
+								    	if(!$returnstatus){
+								    		if($this->debug>1){error_log('New LP - Prerequisite '.$prereqs_string.' not complete',0);}
+								    	}else{
+								    		if($this->debug>1){error_log('New LP - Prerequisite '.$prereqs_string.' complete',0);}
+								    	}
+						    			return $returnstatus;
+				    				}
+				    			}else{
+				    				if($this->debug>1){error_log('New LP - Could not find '.$prereqs_string.' in '.print_r($refs_list,true),0);}
+				    			}
+					    	}
+		    			}
+		    		}
+	    		}
+	    	}
+    	}else{
+    		$list = split("\|",$prereqs_string);
+    		if(count($list)>1){
+	    		if($this->debug>1){error_log('New LP - Found OR, looking into it',0);}
+				$orstatus = false;
+				foreach($list as $condition){
+					if($this->debug>1){error_log('New LP - Found OR, adding it ('.$condition.')',0);}
+    				$orstatus = $orstatus || $this->parse_prereq($condition,$items,$refs_list,$user_id);
+    				if($orstatus == true){
+    					//shortcircuit OR
+						if($this->debug>1){error_log('New LP - One condition in OR was true, short-circuit',0);}
+    					break;
+    				}
+				}
+		    	if(!$orstatus && empty($this->prereq_alert)){
+		    		$this->prereq_alert = get_lang('_prereq_not_complete');
+		    	}
+				return $orstatus;
+    		}else{
+	    		if($this->debug>1){error_log('New LP - OR was found but only one elem present !?',0);}
+    			if(isset($items[$refs_list[$list[0]]])){
+    				$status = $items[$refs_list[$list[0]]]->get_status(true);
+	    			$returnstatus = (($status == 'completed') OR ($status == 'passed'));
+			    	if(!$returnstatus && empty($this->prereq_alert)){
+			    		$this->prereq_alert = get_lang('_prereq_not_complete');
+			    	}
+	    			return $returnstatus;
+    			}
+    		}
+    	}
+    	if(empty($this->prereq_alert)){
+    		$this->prereq_alert = get_lang('_prereq_not_complete');
+    	}
+    	if($this->debug>1){error_log('New LP - End of parse_prereq. Error code is now '.$this->prereq_alert,0);}
+    	return false;
+    }
+    /**
+	 * Parses the HTML attributes given as string.
 	 *
-	 * @param    string  HTML attribute string
-	 * @param	 array	 List of attributes that we want to get back
-	 * @return   array   An associative array of attributes
-	 * @author Based on a function from the HTML_Common2 PEAR module
-	 */
-	function parse_HTML_attributes($attrString,$wanted=array())
-	{
-	    $attributes = array();
-	    $regs = array();
-	    $reduced = false;
-	    if(count($wanted)>0)
-	    {
-	    	$reduced = true;
-	    }
-	    try {
-	       //Find all occurences of something that looks like a URL
-           // The structure of this regexp is:
+	 * @param    string  HTML attribute string
+	 * @param	 array	 List of attributes that we want to get back
+	 * @return   array   An associative array of attributes
+	 * @author Based on a function from the HTML_Common2 PEAR module
+	 */
+	function parse_HTML_attributes($attrString,$wanted=array())
+	{
+	    $attributes = array();
+	    $regs = array();
+	    $reduced = false;
+	    if(count($wanted)>0)
+	    {
+	    	$reduced = true;
+	    }
+	    try {
+	       //Find all occurences of something that looks like a URL
+           // The structure of this regexp is:
            // (find protocol) then
-           // (optionally find some kind of space 1 or more times) then
-           // find (either an equal sign or a bracket) followed by an optional space
-           // followed by some text without quotes (between quotes itself or not)
-           // then possible closing brackets if we were in the opening bracket case
+           // (optionally find some kind of space 1 or more times) then
+           // find (either an equal sign or a bracket) followed by an optional space
+           // followed by some text without quotes (between quotes itself or not)
+           // then possible closing brackets if we were in the opening bracket case
            // OR something like @import()
-	    	$res = preg_match_all(
-                '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]*))' .
-//	            '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]|[^\x00-\x7F])*)' . -> seems to be taking too much
+	    	$res = preg_match_all(
+                '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]*))' .
+//	            '/(((([A-Za-z_:])([A-Za-z0-9_:\.-]|[^\x00-\x7F])*)' . -> seems to be taking too much
 //                '/(((([A-Za-z_:])([^\x00-\x7F])*)' . -> takes only last letter of parameter name
-	            '([ \n\t\r]+)?(' .
-//	              '(=([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+))' . -> doesn't restrict close enough to the url itself
-                  '(=([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+))' .
-	              '|' .
-//	              '(\(([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)\))' . -> doesn't restrict close enough to the url itself
-                  '(\(([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+)\))' .
-	            '))' .
-	            '|' .
+	            '([ \n\t\r]+)?(' .
+//	              '(=([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+))' . -> doesn't restrict close enough to the url itself
+                  '(=([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+))' .
+	              '|' .
+//	              '(\(([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)\))' . -> doesn't restrict close enough to the url itself
+                  '(\(([ \n\t\r]+)?("[^"\)]+"|\'[^\'\)]+\'|[^ \n\t\r\)]+)\))' .
+	            '))' .
+	            '|' .
 //	            '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))?/', -> takes a lot (like 100's of thousands of empty possibilities)
                 '(@import([ \n\t\r]+)?("[^"]+"|\'[^\']+\'|[^ \n\t\r]+)))/',
 	            $attrString,
-	            $regs
-	       );
-
-		} catch (Exception $e) {
-    		error_log('Caught exception: '. $e->getMessage(),0) ;
-		}
-	    if ($res) {
-	        for ($i = 0; $i < count($regs[1]); $i++) {
-	            $name  = trim($regs[3][$i]);
-	            $check = trim($regs[0][$i]);
-	            $value = trim($regs[10][$i]);
-	            if(empty($value) and !empty($regs[13][$i])){
-					$value = $regs[13][$i];
-	            }
-	            if(empty($name) && !empty($regs[16][$i]))
-	            {
-	            	$name = '@import';
-	            	$value = trim($regs[16][$i]);
-	            }
-	            if(!empty($name))
+	            $regs
+	       );
+
+		} catch (Exception $e) {
+    		error_log('Caught exception: '. $e->getMessage(),0) ;
+		}
+	    if ($res) {
+	        for ($i = 0; $i < count($regs[1]); $i++) {
+	            $name  = trim($regs[3][$i]);
+	            $check = trim($regs[0][$i]);
+	            $value = trim($regs[10][$i]);
+	            if(empty($value) and !empty($regs[13][$i])){
+					$value = $regs[13][$i];
+	            }
+	            if(empty($name) && !empty($regs[16][$i]))
 	            {
-					if(!$reduced OR in_array(strtolower($name),$wanted))
-		            {
+	            	$name = '@import';
+	            	$value = trim($regs[16][$i]);
+	            }
+	            if(!empty($name))
+	            {
+					if(!$reduced OR in_array(strtolower($name),$wanted))
+		            {
 			            if ($name == $check) {
 		            		$attributes[strtolower($name)][] = strtolower($name);
 			            } else {
 			                if (!empty($value) && ($value[0] == '\'' || $value[0] == '"')) {
 			                    $value = substr($value, 1, -1);
-			                }
-						    if ($value=='API.LMSGetValue(name') {
-						    	$value='API.LMSGetValue(name)';
+			                }
+						    if ($value=='API.LMSGetValue(name') {
+						    	$value='API.LMSGetValue(name)';
 						    }
-			                $attributes[strtolower($name)][] = $value;
-			            }
-		            }
-	            }
-	        }
-	    }else{
-	    	error_log('preg_match did not find anything',0);
-	    }
-	    return $attributes;
-	}
-    /**
-     * Reinits all local values as the learnpath is restarted
+			                $attributes[strtolower($name)][] = $value;
+			            }
+		            }
+	            }
+	        }
+	    }else{
+	    	error_log('preg_match did not find anything',0);
+	    }
+	    return $attributes;
+	}
+    /**
+     * Reinits all local values as the learnpath is restarted
      * @return	boolean	True on success, false otherwise
-     */
-    function restart()
-    {
-		if($this->debug>0){error_log('New LP - In learnpathItem::restart()',0);}
-		$this->save();
-		$allowed = $this->is_restart_allowed();
-		if($allowed === -1){
-			//nothing allowed, do nothing
-		}elseif($allowed === 1){
-			//restart as new attempt is allowed, record a new attempt
-	    	$this->attempt_id = $this->attempt_id + 1; //simply reuse the previous attempt_id
-			$this->current_score = 0;
-			$this->current_start_time = 0;
-			$this->current_stop_time = 0;
-			$this->current_data = '';
-			$this->status = $this->possible_status[0];
-			$this->interactions_count = 0;
-			$this->interactions = array();
-			$this->objectives_count = 0;
-			$this->objectives = array();
-			$this->lesson_location = '';
-			if ($this->type != TOOL_QUIZ) {
-				$this->write_to_db();
-			}
-		}else{
+     */
+    function restart()
+    {
+		if($this->debug>0){error_log('New LP - In learnpathItem::restart()',0);}
+		$this->save();
+		$allowed = $this->is_restart_allowed();
+		if($allowed === -1){
+			//nothing allowed, do nothing
+		}elseif($allowed === 1){
+			//restart as new attempt is allowed, record a new attempt
+	    	$this->attempt_id = $this->attempt_id + 1; //simply reuse the previous attempt_id
+			$this->current_score = 0;
+			$this->current_start_time = 0;
+			$this->current_stop_time = 0;
+			$this->current_data = '';
+			$this->status = $this->possible_status[0];
+			$this->interactions_count = 0;
+			$this->interactions = array();
+			$this->objectives_count = 0;
+			$this->objectives = array();
+			$this->lesson_location = '';
+			if ($this->type != TOOL_QUIZ) {
+				$this->write_to_db();
+			}
+		}else{
 			//restart current element is allowed (because it's not finished yet),
-			// reinit current
-			$this->current_score = 0;
-			$this->current_start_time = 0;
-			$this->current_stop_time = 0;
-			$this->current_data = '';
-			$this->status = $this->possible_status[0];
-            $this->interactions_count = $this->get_interactions_count(true);
-		}
-    	return true;
-    }
-    /**
-     * Saves data in the database
-     * @param	boolean	Save from URL params (1) or from object attributes (0)
-     * @param	boolean	The results of a check on prerequisites for this item. True if prerequisites are completed, false otherwise. Defaults to false. Only used if not sco or au
-     * @return	boolean	True on success, false on failure
-     */
-    function save($from_outside=true,$prereqs_complete=false)
-    {
-		if($this->debug>0){error_log('New LP - In learnpathItem::save()',0);}
-
-		//$item_view_table = Database::get_course_table(COURSEID,LEARNPATH_ITEM_VIEW_TABLE);
-     	$item_id = $this->get_id();
-     	//first check if parameters passed via GET can be saved here
-     	//in case it's a SCORM, we should get:
-		if($this->type == 'sco' || $this->type== 'au'){
-			$s = $this->get_status(true);
-			if($this->prevent_reinit == 1 AND
-				$s != $this->possible_status[0] AND $s != $this->possible_status[1]){
-				if($this->debug>1){error_log('New LP - In learnpathItem::save() - save reinit blocked by setting',0);}
-				//do nothing because the status has already been set. Don't allow it to change.
-				//TODO check there isn't a special circumstance where this should be saved
-			}else{
-			  if($this->debug>1){error_log('New LP - In learnpathItem::save() - SCORM save request received',0);}
-			  //get all new settings from the URL
-				if($from_outside==true){
-				  if($this->debug>1){error_log('New LP - In learnpathItem::save() - Getting item data from outside',0);}
-		     	  foreach($_GET as $param => $value)
-		     	  {
-		     		$value = Database::escape_string($value);
-		     		switch($param){
-		     			case 'score':
-		   					$this->set_score($value);
-		   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting score to '.$value,0);}
-		     				break;
-		     			case 'max':
-		     				$this->set_max_score($value);
-		   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting view_max_score to '.$value,0);}
-		     				break;
-		     			case 'min':
-		     				$this->min_score = $value;
-		   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting min_score to '.$value,0);}
-		     				break;
-		     			case 'lesson_status':
-		     				if(!empty($value)){
+			// reinit current
+			$this->current_score = 0;
+			$this->current_start_time = 0;
+			$this->current_stop_time = 0;
+			$this->current_data = '';
+			$this->status = $this->possible_status[0];
+            $this->interactions_count = $this->get_interactions_count(true);
+		}
+    	return true;
+    }
+    /**
+     * Saves data in the database
+     * @param	boolean	Save from URL params (1) or from object attributes (0)
+     * @param	boolean	The results of a check on prerequisites for this item. True if prerequisites are completed, false otherwise. Defaults to false. Only used if not sco or au
+     * @return	boolean	True on success, false on failure
+     */
+    function save($from_outside=true,$prereqs_complete=false)
+    {
+		if($this->debug>0){error_log('New LP - In learnpathItem::save()',0);}
+
+		//$item_view_table = Database::get_course_table(COURSEID,LEARNPATH_ITEM_VIEW_TABLE);
+     	$item_id = $this->get_id();
+     	//first check if parameters passed via GET can be saved here
+     	//in case it's a SCORM, we should get:
+		if($this->type == 'sco' || $this->type== 'au'){
+			$s = $this->get_status(true);
+			if($this->prevent_reinit == 1 AND
+				$s != $this->possible_status[0] AND $s != $this->possible_status[1]){
+				if($this->debug>1){error_log('New LP - In learnpathItem::save() - save reinit blocked by setting',0);}
+				//do nothing because the status has already been set. Don't allow it to change.
+				//TODO check there isn't a special circumstance where this should be saved
+			}else{
+			  if($this->debug>1){error_log('New LP - In learnpathItem::save() - SCORM save request received',0);}
+			  //get all new settings from the URL
+				if($from_outside==true){
+				  if($this->debug>1){error_log('New LP - In learnpathItem::save() - Getting item data from outside',0);}
+		     	  foreach($_GET as $param => $value)
+		     	  {
+		     		$value = Database::escape_string($value);
+		     		switch($param){
+		     			case 'score':
+		   					$this->set_score($value);
+		   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting score to '.$value,0);}
+		     				break;
+		     			case 'max':
+		     				$this->set_max_score($value);
+		   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting view_max_score to '.$value,0);}
+		     				break;
+		     			case 'min':
+		     				$this->min_score = $value;
+		   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting min_score to '.$value,0);}
+		     				break;
+		     			case 'lesson_status':
+		     				if(!empty($value)){
 			     				$this->set_status($value);
-			   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting status to '.$value,0);}
-		     				}
-		     				break;
-		     			case 'time':
-		     				$this->set_time($value);
-		   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting time to '.$value,0);}
-		     				break;
-		     			case 'suspend_data':
-		     				$this->current_data = $value;
-		     				if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting suspend_data to '.$value,0);}
-		     				break;
-		     			case 'lesson_location':
-		     				$this->set_lesson_location($value);
-		     				if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting lesson_location to '.$value,0);}
-		     				break;
-		     			case 'core_exit':
-		     				$this->set_core_exit($value);
-		     				if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting core_exit to '.$value,0);}
-		     				break;
-		     			case 'interactions':
-		     				//$interactions = unserialize($value);
-		     				//foreach($interactions as $interaction){
-		     				//	;
-		     				//}
-		     				break;
-		     			case 'objectives':
-		     				break;
-		     			//case 'maxtimeallowed':
-		     			//	$this->set_max_time_allowed($value);
-		     			//	break;
-		     			/*
-		     			case 'objectives._count':
-		     				$this->attempt_id = $value;
-		     				break;
-		     			*/
-		     			default:
-		     				//ignore
-		     				break;
-		     		}
-		     	  }
-				}else{
-					if($this->debug>1){error_log('New LP - In learnpathItem::save() - Using inside item status',0);}
-					//do nothing, just let the local attributes be used
-				}
-			}
-		}else{ //if not SCO, such messages should not be expected
-			$type = strtolower($this->type);
-			switch($type){
-				case 'asset':
-		 			if($prereqs_complete)
-		 			{
-			 			$this->set_status($this->possible_status[2]);
-		 			}
-		 			break;
-		 		case TOOL_HOTPOTATOES:
-		 		case TOOL_QUIZ: return false;break;
-				default:
-		 			//for now, everything that is not sco and not asset is set to
-		 			//completed when saved
-		 			if($prereqs_complete)
-		 			{
-		 				$this->set_status($this->possible_status[2]);
+			   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting status to '.$value,0);}
+		     				}
+		     				break;
+		     			case 'time':
+		     				$this->set_time($value);
+		   					if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting time to '.$value,0);}
+		     				break;
+		     			case 'suspend_data':
+		     				$this->current_data = $value;
+		     				if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting suspend_data to '.$value,0);}
+		     				break;
+		     			case 'lesson_location':
+		     				$this->set_lesson_location($value);
+		     				if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting lesson_location to '.$value,0);}
+		     				break;
+		     			case 'core_exit':
+		     				$this->set_core_exit($value);
+		     				if($this->debug>2){error_log('New LP - In learnpathItem::save() - setting core_exit to '.$value,0);}
+		     				break;
+		     			case 'interactions':
+		     				//$interactions = unserialize($value);
+		     				//foreach($interactions as $interaction){
+		     				//	;
+		     				//}
+		     				break;
+		     			case 'objectives':
+		     				break;
+		     			//case 'maxtimeallowed':
+		     			//	$this->set_max_time_allowed($value);
+		     			//	break;
+		     			/*
+		     			case 'objectives._count':
+		     				$this->attempt_id = $value;
+		     				break;
+		     			*/
+		     			default:
+		     				//ignore
+		     				break;
+		     		}
+		     	  }
+				}else{
+					if($this->debug>1){error_log('New LP - In learnpathItem::save() - Using inside item status',0);}
+					//do nothing, just let the local attributes be used
+				}
+			}
+		}else{ //if not SCO, such messages should not be expected
+			$type = strtolower($this->type);
+			switch($type){
+				case 'asset':
+		 			if($prereqs_complete)
+		 			{
+			 			$this->set_status($this->possible_status[2]);
 		 			}
-				break;
-	 		}
-		}
-		//$time = $this->time
-		if($this->debug>1){error_log('New LP - End of learnpathItem::save() - Calling write_to_db()',0);}
-		return $this->write_to_db();
-    }
-    /**
-     * Sets the number of attempt_id to a given value
-     * @param	integer	The given value to set attempt_id to
-     * @return	boolean	TRUE on success, FALSE otherwise
-     */
-    function set_attempt_id($num)
-    {
-		if($this->debug>0){error_log('New LP - In learnpathItem::set_attempt_id()',0);}
-     	if($num == strval(intval($num)) && $num>=0){
-     		$this->attempt_id = $num;
-     		return true;
-     	}
-     	return false;
-    }
-    /**
-     * Sets the core_exit value to the one given
-     */
-    function set_core_exit($value)
-    {
-    	switch($value){
-    		case '':
-    			$this->core_exit = '';
-    			break;
-    		case 'suspend':
-    			$this->core_exit = 'suspend';
-    			break;
-    		default:
-    			$this->core_exit = 'none';
-    			break;
-    	}
-    	return true;
-    }
-    /**
-     * Sets the item's description
-     * @param	string	Description
-     */
-    function set_description($string=''){
-		if($this->debug>0){error_log('New LP - In learnpathItem::set_description()',0);}
-    	if(!empty($string)){$this->description = $string;}
-    }
-    /**
-     * Sets the lesson_location value
-     * @param	string	lesson_location as provided by the SCO
-     * @return	boolean	True on success, false otherwise
-     */
-    function set_lesson_location($location)
-    {
-   		if($this->debug>0){error_log('New LP - In learnpathItem::set_lesson_location()',0);}
-		if(isset($location)){
-   			$this->lesson_location = Database::escape_string($location);
-  			return true;
-  		}
-     	return false;
-    }
-    /**
-     * Sets the item's depth level in the LP tree (0 is at root)
-     * @param	integer	Level
-     */
-    function set_level($int=0){
-		if($this->debug>0){error_log('New LP - In learnpathItem::set_level('.$int.')',0);}
-    	if(!empty($int) AND $int == strval(intval($int))){$this->level = $int;}
-    }
-    /**
-     * Sets the lp_view id this item view is registered to
-     * @param	integer	lp_view DB ID
-     * @todo //todo insert into lp_item_view if lp_view not exists
-     */
-    function set_lp_view($lp_view_id)
-    {
-		if($this->debug>0){error_log('New LP - In learnpathItem::set_lp_view('.$lp_view_id.')',0);}
-    	if(!empty($lp_view_id) and $lp_view_id = intval(strval($lp_view_id)))
-     	{
-     		$this->view_id = $lp_view_id;
-	     	$item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-	     	//get the lp_item_view with the highest view_count
-	     	$sql = "SELECT * FROM $item_view_table WHERE lp_item_id = ".$this->get_id()." " .
-	     			" AND lp_view_id = ".$lp_view_id." ORDER BY view_count DESC";
-	     	if($this->debug>2){error_log('New LP - In learnpathItem::set_lp_view() - Querying lp_item_view: '.$sql,0);}
-	     	$res = Database::query($sql,__FILE__,__LINE__);
-	     	if(Database::num_rows($res)>0){
-	     		$row = Database::fetch_array($res);
-	     		$this->db_item_view_id  = $row['id'];
-	     		$this->attempt_id 		= $row['view_count'];
-				$this->current_score	= $row['score'];
-				$this->current_data		= $row['suspend_data'];
-		    	$this->view_max_score 	= $row['max_score'];
-		    	//$this->view_min_score 	= $row['min_score'];
-				$this->status			= $row['status'];
-				$this->current_start_time	= $row['start_time'];
+		 			break;
+		 		case TOOL_HOTPOTATOES:
+		 		case TOOL_QUIZ: return false;break;
+				default:
+		 			//for now, everything that is not sco and not asset is set to
+		 			//completed when saved
+		 			if($prereqs_complete)
+		 			{
+		 				$this->set_status($this->possible_status[2]);
+		 			}
+				break;
+	 		}
+		}
+		//$time = $this->time
+		if($this->debug>1){error_log('New LP - End of learnpathItem::save() - Calling write_to_db()',0);}
+		return $this->write_to_db();
+    }
+    /**
+     * Sets the number of attempt_id to a given value
+     * @param	integer	The given value to set attempt_id to
+     * @return	boolean	TRUE on success, FALSE otherwise
+     */
+    function set_attempt_id($num)
+    {
+		if($this->debug>0){error_log('New LP - In learnpathItem::set_attempt_id()',0);}
+     	if($num == strval(intval($num)) && $num>=0){
+     		$this->attempt_id = $num;
+     		return true;
+     	}
+     	return false;
+    }
+    /**
+     * Sets the core_exit value to the one given
+     */
+    function set_core_exit($value)
+    {
+    	switch($value){
+    		case '':
+    			$this->core_exit = '';
+    			break;
+    		case 'suspend':
+    			$this->core_exit = 'suspend';
+    			break;
+    		default:
+    			$this->core_exit = 'none';
+    			break;
+    	}
+    	return true;
+    }
+    /**
+     * Sets the item's description
+     * @param	string	Description
+     */
+    function set_description($string=''){
+		if($this->debug>0){error_log('New LP - In learnpathItem::set_description()',0);}
+    	if(!empty($string)){$this->description = $string;}
+    }
+    /**
+     * Sets the lesson_location value
+     * @param	string	lesson_location as provided by the SCO
+     * @return	boolean	True on success, false otherwise
+     */
+    function set_lesson_location($location)
+    {
+   		if($this->debug>0){error_log('New LP - In learnpathItem::set_lesson_location()',0);}
+		if(isset($location)){
+   			$this->lesson_location = Database::escape_string($location);
+  			return true;
+  		}
+     	return false;
+    }
+    /**
+     * Sets the item's depth level in the LP tree (0 is at root)
+     * @param	integer	Level
+     */
+    function set_level($int=0){
+		if($this->debug>0){error_log('New LP - In learnpathItem::set_level('.$int.')',0);}
+    	if(!empty($int) AND $int == strval(intval($int))){$this->level = $int;}
+    }
+    /**
+     * Sets the lp_view id this item view is registered to
+     * @param	integer	lp_view DB ID
+     * @todo //todo insert into lp_item_view if lp_view not exists
+     */
+    function set_lp_view($lp_view_id)
+    {
+		if($this->debug>0){error_log('New LP - In learnpathItem::set_lp_view('.$lp_view_id.')',0);}
+    	if(!empty($lp_view_id) and $lp_view_id = intval(strval($lp_view_id)))
+     	{
+     		$this->view_id = $lp_view_id;
+	     	$item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+	     	//get the lp_item_view with the highest view_count
+	     	$sql = "SELECT * FROM $item_view_table WHERE lp_item_id = ".$this->get_id()." " .
+	     			" AND lp_view_id = ".$lp_view_id." ORDER BY view_count DESC";
+	     	if($this->debug>2){error_log('New LP - In learnpathItem::set_lp_view() - Querying lp_item_view: '.$sql,0);}
+	     	$res = Database::query($sql,__FILE__,__LINE__);
+	     	if(Database::num_rows($res)>0){
+	     		$row = Database::fetch_array($res);
+	     		$this->db_item_view_id  = $row['id'];
+	     		$this->attempt_id 		= $row['view_count'];
+				$this->current_score	= $row['score'];
+				$this->current_data		= $row['suspend_data'];
+		    	$this->view_max_score 	= $row['max_score'];
+		    	//$this->view_min_score 	= $row['min_score'];
+				$this->status			= $row['status'];
+				$this->current_start_time	= $row['start_time'];
 				$this->current_stop_time 	= $this->current_start_time + $row['total_time'];
-				$this->lesson_location  = $row['lesson_location'];
-				$this->core_exit		= $row['core_exit'];
-		     	if($this->debug>2){error_log('New LP - In learnpathItem::set_lp_view() - Updated item object with database values',0);}
-
-		     	//now get the number of interactions for this little guy
-		     	$item_view_interaction_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
+				$this->lesson_location  = $row['lesson_location'];
+				$this->core_exit		= $row['core_exit'];
+		     	if($this->debug>2){error_log('New LP - In learnpathItem::set_lp_view() - Updated item object with database values',0);}
+
+		     	//now get the number of interactions for this little guy
+		     	$item_view_interaction_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
 		     	$sql = "SELECT * FROM $item_view_interaction_table WHERE lp_iv_id = '".$this->db_item_view_id."'";
-				$res = Database::query($sql,__FILE__,__LINE__);
-				if($res !== false){
-					$this->interactions_count = Database::num_rows($res);
-				}else{
-					$this->interactions_count = 0;
-				}
-		     	//now get the number of objectives for this little guy
-		     	$item_view_objective_table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
+				$res = Database::query($sql,__FILE__,__LINE__);
+				if($res !== false){
+					$this->interactions_count = Database::num_rows($res);
+				}else{
+					$this->interactions_count = 0;
+				}
+		     	//now get the number of objectives for this little guy
+		     	$item_view_objective_table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
 		     	$sql = "SELECT * FROM $item_view_objective_table WHERE lp_iv_id = '".$this->db_item_view_id."'";
-				$res = Database::query($sql,__FILE__,__LINE__);
-				if($res !== false){
-					$this->objectives_count = Database::num_rows($res);
-				}else{
-					$this->objectives_count = 0;
-				}
-	     	}
-     	}
-		//end
-		if($this->debug>2){error_log('New LP - End of learnpathItem::set_lp_view()',0);}
-    }
-    /**
-     * Sets the path
-     * @param	string	Path
-     */
-    function set_path($string=''){
-		if($this->debug>0){error_log('New LP - In learnpathItem::set_path()',0);}
-    	if(!empty($string)){$this->path = $string;}
-    }
-    /**
-     * Sets the prevent_reinit attribute. This is based on the LP value and is set at creation time for
-     * each learnpathItem. It is a (bad?) way of avoiding a reference to the LP when saving an item.
-     * @param	integer	1 for "prevent", 0 for "don't prevent" saving freshened values (new "not attempted" status etc)
-     */
-    function set_prevent_reinit($prevent){
-		if($this->debug>0){error_log('New LP - In learnpathItem::set_prevent_reinit()',0);}
-    	if($prevent){
-    		$this->prevent_reinit = 1;
-    	}else{
-    		$this->prevent_reinit = 0;
-    	}
-    }
-    /**
-     * Sets the score value. If the mastery_score is set and the score reaches
-     * it, then set the status to 'passed'.
-     * @param	float	Score
-     * @return	boolean	True on success, false otherwise
-     */
-    function set_score($score)
-    {
-   		if($this->debug>0){error_log('New LP - In learnpathItem::set_score('.$score.')',0);}
-   		if(($this->max_score<=0 || $score <= $this->max_score) && ($score >= $this->min_score))
-   		{
-   			$this->current_score = $score;
-   			$master = $this->get_mastery_score();
-   			$current_status = $this->get_status(false);
-   			//if mastery_score is set AND the current score reaches the mastery score AND the current status is different from 'completed', then set it to 'passed'
-   			if($master != -1 && $this->current_score >= $master && $current_status != $this->possible_status[2])
-   			{
-   				$this->set_status($this->possible_status[3]);
-   			}
-   			elseif($master != -1 && $this->current_score<$master)
-   			{
-   				$this->set_status($this->possible_status[4]);
-   			}
-  			return true;
-  		}
-     	return false;
-    }
-    /**
-     * Sets the maximum score for this item
-     * @param	int		Maximum score - must be a decimal or an empty string
-     * @return	boolean	True on success, false on error
-     */
-    function set_max_score($score)
-    {
-   		if($this->debug>0){error_log('New LP - In learnpathItem::set_max_score('.$score.')',0);}
-     	if(is_int($score) or $score == '')
-     	{
-     		$this->view_max_score = Database::escape_string($score);
-     		if($this->debug>1){error_log('New LP - In learnpathItem::set_max_score() - Updated object score of item '.$this->db_id.' to '.$this->view_max_score,0);}
-     		return true;
-     	}
-     	return false;
-    }
-    /**
-     * Sets the status for this item
-     * @param	string	Status - must be one of the values defined in $this->possible_status
-     * @return	boolean	True on success, false on error
-     */
-    function set_status($status)
-    {
-   		if($this->debug>0){error_log('New LP - In learnpathItem::set_status('.$status.')',0);}
-     	$found = false;
-     	foreach($this->possible_status  as $possible){
-     		if(preg_match('/^'.$possible.'$/i',$status)){
-     			$found = true;
-     		}
-     	}
-     	//if(in_array($status,$this->possible_status))
-     	if($found)
-     	{
-     		$this->status = Database::escape_string($status);
-     		if($this->debug>1){error_log('New LP - In learnpathItem::set_status() - Updated object status of item '.$this->db_id.' to '.$this->status,0);}
-     		return true;
-     	}
-     	//error_log('New LP - '.$status.' was not in the possible status',0);
-     	$this->status = $this->possible_status[0];
-     	return false;
-    }
-    /**
-     * Set the terms for this learnpath item
-     * @param   string  Terms, as a comma-split list
-     * @return  boolean Always return true
-     */
-    function set_terms($terms) {
-		global $charset;
-        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
-        require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
-        $a_terms = split(',',$terms);
-        $i_terms = split(',',$this->get_terms());
-        foreach ( $i_terms as $term ) {
-            if ( !in_array($term,$a_terms) ) { array_push($a_terms,$term); }
-        }
-        $new_terms = $a_terms;
-        $new_terms_string = implode(',',$new_terms);
-        $terms_update_sql='';
-        //TODO: validate csv string
-        $terms_update_sql = "UPDATE $lp_item SET terms = '". Database::escape_string(api_htmlentities($new_terms_string, ENT_QUOTES, $charset)) . "' WHERE id=".$this->get_id();
-        $res = Database::query($terms_update_sql,__FILE__,__LINE__);
-        // save it to search engine
-        if (api_get_setting('search_enabled') == 'true') {
-            $di = new DokeosIndexer();
-            $di->update_terms($this->get_search_did(), $new_terms);
-        }
-        return true;
-    }
-    /**
-     * Get the document ID from inside the text index database
-     * @return  int     Search index database document ID
-     */
-    function get_search_did()
-    {
-        return $this->search_did;
-    }
+				$res = Database::query($sql,__FILE__,__LINE__);
+				if($res !== false){
+					$this->objectives_count = Database::num_rows($res);
+				}else{
+					$this->objectives_count = 0;
+				}
+	     	}
+     	}
+		//end
+		if($this->debug>2){error_log('New LP - End of learnpathItem::set_lp_view()',0);}
+    }
+    /**
+     * Sets the path
+     * @param	string	Path
+     */
+    function set_path($string=''){
+		if($this->debug>0){error_log('New LP - In learnpathItem::set_path()',0);}
+    	if(!empty($string)){$this->path = $string;}
+    }
+    /**
+     * Sets the prevent_reinit attribute. This is based on the LP value and is set at creation time for
+     * each learnpathItem. It is a (bad?) way of avoiding a reference to the LP when saving an item.
+     * @param	integer	1 for "prevent", 0 for "don't prevent" saving freshened values (new "not attempted" status etc)
+     */
+    function set_prevent_reinit($prevent){
+		if($this->debug>0){error_log('New LP - In learnpathItem::set_prevent_reinit()',0);}
+    	if($prevent){
+    		$this->prevent_reinit = 1;
+    	}else{
+    		$this->prevent_reinit = 0;
+    	}
+    }
+    /**
+     * Sets the score value. If the mastery_score is set and the score reaches
+     * it, then set the status to 'passed'.
+     * @param	float	Score
+     * @return	boolean	True on success, false otherwise
+     */
+    function set_score($score)
+    {
+   		if($this->debug>0){error_log('New LP - In learnpathItem::set_score('.$score.')',0);}
+   		if(($this->max_score<=0 || $score <= $this->max_score) && ($score >= $this->min_score))
+   		{
+   			$this->current_score = $score;
+   			$master = $this->get_mastery_score();
+   			$current_status = $this->get_status(false);
+   			//if mastery_score is set AND the current score reaches the mastery score AND the current status is different from 'completed', then set it to 'passed'
+   			if($master != -1 && $this->current_score >= $master && $current_status != $this->possible_status[2])
+   			{
+   				$this->set_status($this->possible_status[3]);
+   			}
+   			elseif($master != -1 && $this->current_score<$master)
+   			{
+   				$this->set_status($this->possible_status[4]);
+   			}
+  			return true;
+  		}
+     	return false;
+    }
+    /**
+     * Sets the maximum score for this item
+     * @param	int		Maximum score - must be a decimal or an empty string
+     * @return	boolean	True on success, false on error
+     */
+    function set_max_score($score)
+    {
+   		if($this->debug>0){error_log('New LP - In learnpathItem::set_max_score('.$score.')',0);}
+     	if(is_int($score) or $score == '')
+     	{
+     		$this->view_max_score = Database::escape_string($score);
+     		if($this->debug>1){error_log('New LP - In learnpathItem::set_max_score() - Updated object score of item '.$this->db_id.' to '.$this->view_max_score,0);}
+     		return true;
+     	}
+     	return false;
+    }
+    /**
+     * Sets the status for this item
+     * @param	string	Status - must be one of the values defined in $this->possible_status
+     * @return	boolean	True on success, false on error
+     */
+    function set_status($status)
+    {
+   		if($this->debug>0){error_log('New LP - In learnpathItem::set_status('.$status.')',0);}
+     	$found = false;
+     	foreach($this->possible_status  as $possible){
+     		if(preg_match('/^'.$possible.'$/i',$status)){
+     			$found = true;
+     		}
+     	}
+     	//if(in_array($status,$this->possible_status))
+     	if($found)
+     	{
+     		$this->status = Database::escape_string($status);
+     		if($this->debug>1){error_log('New LP - In learnpathItem::set_status() - Updated object status of item '.$this->db_id.' to '.$this->status,0);}
+     		return true;
+     	}
+     	//error_log('New LP - '.$status.' was not in the possible status',0);
+     	$this->status = $this->possible_status[0];
+     	return false;
+    }
+    /**
+     * Set the terms for this learnpath item
+     * @param   string  Terms, as a comma-split list
+     * @return  boolean Always return true
+     */
+    function set_terms($terms) {
+		global $charset;
+        $lp_item = Database::get_course_table(TABLE_LP_ITEM);
+        require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
+        $a_terms = split(',',$terms);
+        $i_terms = split(',',$this->get_terms());
+        foreach ( $i_terms as $term ) {
+            if ( !in_array($term,$a_terms) ) { array_push($a_terms,$term); }
+        }
+        $new_terms = $a_terms;
+        $new_terms_string = implode(',',$new_terms);
+        $terms_update_sql='';
+        //TODO: validate csv string
+        $terms_update_sql = "UPDATE $lp_item SET terms = '". Database::escape_string(api_htmlentities($new_terms_string, ENT_QUOTES, $charset)) . "' WHERE id=".$this->get_id();
+        $res = Database::query($terms_update_sql,__FILE__,__LINE__);
+        // save it to search engine
+        if (api_get_setting('search_enabled') == 'true') {
+            $di = new DokeosIndexer();
+            $di->update_terms($this->get_search_did(), $new_terms);
+        }
+        return true;
+    }
+    /**
+     * Get the document ID from inside the text index database
+     * @return  int     Search index database document ID
+     */
+    function get_search_did()
+    {
+        return $this->search_did;
+    }
 
-    /**
-     * Sets the item viewing time in a usable form, given that SCORM packages often give it as 00:00:00.0000
-     * @param	string	Time as given by SCORM
-     */
-    function set_time($scorm_time,$format='scorm')
-    {
-   		if($this->debug>0){error_log('New LP - In learnpathItem::set_time('.$scorm_time.')',0);}
-     	if($scorm_time == 0 and ($this->type!='sco') and $this->current_start_time!=0){
-     		$my_time = time() - $this->current_start_time;
-     		if($my_time > 0){
-     			$this->update_time($my_time);
-     			if($this->debug>0){error_log('New LP - In learnpathItem::set_time('.$scorm_time.') - found asset - set time to '.$my_time,0);}
-     		}
-     	}else{
-     		if($format == 'scorm'){
-		     	$res = array();
-		     	if(preg_match('/^(\d{1,4}):(\d{2}):(\d{2})(\.\d{1,4})?/',$scorm_time,$res)){
-		     		$time = time();
-					$hour = $res[1];
-					$min = $res[2];
-					$sec = $res[3];
-					//getting total number of seconds spent
-		     		$total_sec = $hour*3600 + $min*60 + $sec;
-		     		$this->update_time($total_sec);
-		     	}
-     		}elseif($format == 'int'){
-     			$this->update_time($scorm_time);
-     		}
-     	}
-    }
-    /**
-     * Sets the item's title
-     * @param	string	Title
-     */
-    function set_title($string=''){
-   		if($this->debug>0){error_log('New LP - In learnpathItem::set_title()',0);}
-    	if(!empty($string)){$this->title = $string;}
-    }
-    /**
-     * Sets the item's type
-     * @param	string	Type
-     */
-    function set_type($string=''){
-   		if($this->debug>0){error_log('New LP - In learnpathItem::set_type()',0);}
-    	if(!empty($string)){$this->type = $string;}
-    }
-	/**
-	 * Checks if the current status is part of the list of status given
-	 * @param	strings_array	An array of status to check for. If the current status is one of the strings, return true
+    /**
+     * Sets the item viewing time in a usable form, given that SCORM packages often give it as 00:00:00.0000
+     * @param	string	Time as given by SCORM
+     */
+    function set_time($scorm_time,$format='scorm')
+    {
+   		if($this->debug>0){error_log('New LP - In learnpathItem::set_time('.$scorm_time.')',0);}
+     	if($scorm_time == 0 and ($this->type!='sco') and $this->current_start_time!=0){
+     		$my_time = time() - $this->current_start_time;
+     		if($my_time > 0){
+     			$this->update_time($my_time);
+     			if($this->debug>0){error_log('New LP - In learnpathItem::set_time('.$scorm_time.') - found asset - set time to '.$my_time,0);}
+     		}
+     	}else{
+     		if($format == 'scorm'){
+		     	$res = array();
+		     	if(preg_match('/^(\d{1,4}):(\d{2}):(\d{2})(\.\d{1,4})?/',$scorm_time,$res)){
+		     		$time = time();
+					$hour = $res[1];
+					$min = $res[2];
+					$sec = $res[3];
+					//getting total number of seconds spent
+		     		$total_sec = $hour*3600 + $min*60 + $sec;
+		     		$this->update_time($total_sec);
+		     	}
+     		}elseif($format == 'int'){
+     			$this->update_time($scorm_time);
+     		}
+     	}
+    }
+    /**
+     * Sets the item's title
+     * @param	string	Title
+     */
+    function set_title($string=''){
+   		if($this->debug>0){error_log('New LP - In learnpathItem::set_title()',0);}
+    	if(!empty($string)){$this->title = $string;}
+    }
+    /**
+     * Sets the item's type
+     * @param	string	Type
+     */
+    function set_type($string=''){
+   		if($this->debug>0){error_log('New LP - In learnpathItem::set_type()',0);}
+    	if(!empty($string)){$this->type = $string;}
+    }
+	/**
+	 * Checks if the current status is part of the list of status given
+	 * @param	strings_array	An array of status to check for. If the current status is one of the strings, return true
 	 * @return	boolean			True if the status was one of the given strings, false otherwise
-	 */
-	function status_is($list=array())
-	{
-   		if($this->debug>1){error_log('New LP - In learnpathItem::status_is('.print_r($list,true).') on item '.$this->db_id,0);}
-		$mystatus = $this->get_status(true);
-		if(empty($mystatus)){
-			return false;
-		}
-		$found = false;
-		foreach($list as $status)
-		{
-			if(preg_match('/^'.$status.'$/i',$mystatus))
-			{
-				if($this->debug>2){error_log('New LP - learnpathItem::status_is() - Found status '.$status.' corresponding to current status',0);}
-				$found = true;
-				return $found;
-			}
-		}
-		if($this->debug>2){error_log('New LP - learnpathItem::status_is() - Status '.$mystatus.' did not match request',0);}
-		return $found;
-	}
-    /**
-     * Updates the time info according to the given session_time
-     * @param	integer	Time in seconds
-     * //TODO @TODO make this method better by allowing better/multiple time slices
-     */
-    function update_time($total_sec=0){
-   		if($this->debug>0){error_log('New LP - In learnpathItem::update_time('.$total_sec.')',0);}
-    	if($total_sec>=0){
-	 		//getting start time from finish time. The only problem in the calculation is it might be
-	 		//modified by the scripts processing time
-	 		$now = time();
-	 		$start = $now-$total_sec;
-			$this->current_start_time = $start;
-			$this->current_stop_time  = $now;
-	 		/*if(empty($this->current_start_time)){
-	 			$this->current_start_time = $start;
-	 			$this->current_stop_time  = $now;
-	 		}else{
-	 			//if($this->current_stop_time != $this->current_start_time){
-		 			//if the stop time has already been set before to something else
-		 			//than the start time, add the given time to what's already been
-		 			//recorder.
-		 			//This is the SCORM way of doing things, because the time comes from
-		 			//core.session_time, not core.total_time
-     			// UPDATE: adding time to previous time is only done on SCORM's finish()
-     			// call, not normally, so for now ignore this section
-		 		//	$this->current_stop_time = $this->current_stop_time + $stop;
-		 		//	error_log('New LP - Adding '.$stop.' seconds - now '.$this->current_stop_time,0);
-		 		//}else{
-		 			//if no previous stop time set, use the one just calculated now from
-		 			//start time
-		 			//$this->current_start_time = $start;
-		 			//$this->current_stop_time  = $now;
-		 			//error_log('New LP - Setting '.$stop.' seconds - now '.$this->current_stop_time,0);
-		 		//}
-	 		}*/
-    	}
-    }
-    /**
-     * Write objectives to DB. This method is separate from write_to_db() because otherwise
-     * objectives are lost as a side effect to AJAX and session concurrent access
-     * @return	boolean		True or false on error
-     */
-    function write_objectives_to_db()
-    {
-   		if($this->debug>0){error_log('New LP - In learnpathItem::write_objectives_to_db()',0);}
-     	if(is_array($this->objectives) && count($this->objectives)>0){
-     		//save objectives
-     		$tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-     		$sql = "SELECT id FROM $tbl " .
-     				"WHERE lp_item_id = ".$this->db_id." " .
-     				"AND   lp_view_id = ".$this->view_id." " .
-     				"AND   view_count = ".$this->attempt_id;
-     		$res = Database::query($sql,__FILE__,__LINE__);
-     		if(Database::num_rows($res)>0){
-     			$row = Database::fetch_array($res);
-     			$lp_iv_id = $row[0];
-     			if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Got item_view_id '.$lp_iv_id.', now checking objectives ',0);}
-	     		foreach($this->objectives as $index => $objective){
-	     			$iva_table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
-	     			$iva_sql = "SELECT id FROM $iva_table " .
-	     					"WHERE lp_iv_id = $lp_iv_id " .
-	     					//"AND order_id = $index";
-							//also check for the objective ID as it must be unique for this SCO view
-	     					"AND objective_id = '".Database::escape_string($objective[0])."'";
-	     			$iva_res = Database::query($iva_sql,__FILE__,__LINE__);
-					//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
-	     			if(Database::num_rows($iva_res)>0){
-	     				//update (or don't)
-	     				$iva_row = Database::fetch_array($iva_res);
-	     				$iva_id = $iva_row[0];
-	     				$ivau_sql = "UPDATE $iva_table " .
-	     					"SET objective_id = '".Database::escape_string($objective[0])."'," .
-	     					"status = '".Database::escape_string($objective[1])."'," .
-	     					"score_raw = '".Database::escape_string($objective[2])."'," .
-	     					"score_min = '".Database::escape_string($objective[4])."'," .
-	     					"score_max = '".Database::escape_string($objective[3])."' " .
-	     					"WHERE id = $iva_id";
-	     				$ivau_res = Database::query($ivau_sql,__FILE__,__LINE__);
-	     				//error_log($ivau_sql,0);
-	     			}else{
-	     				//insert new one
-	     				$ivai_sql = "INSERT INTO $iva_table " .
-	     						"(lp_iv_id, order_id, objective_id, status, score_raw, score_min, score_max )" .
-	     						"VALUES" .
-	     						"(".$lp_iv_id.", ".$index.",'".Database::escape_string($objective[0])."','".Database::escape_string($objective[1])."'," .
-	     						"'".Database::escape_string($objective[2])."','".Database::escape_string($objective[4])."','".Database::escape_string($objective[3])."')";
-	     				$ivai_res = Database::query($ivai_sql,__FILE__,__LINE__);
-	     				//error_log($ivai_sql);
-	     			}
-	     		}
-     		}
-     	}
-     	else
-     	{
-     		//error_log('no objective to save: '.print_r($this->objectives,1));
-     	}
-    }
-    /**
-     * Writes the current data to the database
-     * @return	boolean	Query result
-     */
-     function write_to_db()
-     {
+	 */
+	function status_is($list=array())
+	{
+   		if($this->debug>1){error_log('New LP - In learnpathItem::status_is('.print_r($list,true).') on item '.$this->db_id,0);}
+		$mystatus = $this->get_status(true);
+		if(empty($mystatus)){
+			return false;
+		}
+		$found = false;
+		foreach($list as $status)
+		{
+			if(preg_match('/^'.$status.'$/i',$mystatus))
+			{
+				if($this->debug>2){error_log('New LP - learnpathItem::status_is() - Found status '.$status.' corresponding to current status',0);}
+				$found = true;
+				return $found;
+			}
+		}
+		if($this->debug>2){error_log('New LP - learnpathItem::status_is() - Status '.$mystatus.' did not match request',0);}
+		return $found;
+	}
+    /**
+     * Updates the time info according to the given session_time
+     * @param	integer	Time in seconds
+     * //TODO @TODO make this method better by allowing better/multiple time slices
+     */
+    function update_time($total_sec=0){
+   		if($this->debug>0){error_log('New LP - In learnpathItem::update_time('.$total_sec.')',0);}
+    	if($total_sec>=0){
+	 		//getting start time from finish time. The only problem in the calculation is it might be
+	 		//modified by the scripts processing time
+	 		$now = time();
+	 		$start = $now-$total_sec;
+			$this->current_start_time = $start;
+			$this->current_stop_time  = $now;
+	 		/*if(empty($this->current_start_time)){
+	 			$this->current_start_time = $start;
+	 			$this->current_stop_time  = $now;
+	 		}else{
+	 			//if($this->current_stop_time != $this->current_start_time){
+		 			//if the stop time has already been set before to something else
+		 			//than the start time, add the given time to what's already been
+		 			//recorder.
+		 			//This is the SCORM way of doing things, because the time comes from
+		 			//core.session_time, not core.total_time
+     			// UPDATE: adding time to previous time is only done on SCORM's finish()
+     			// call, not normally, so for now ignore this section
+		 		//	$this->current_stop_time = $this->current_stop_time + $stop;
+		 		//	error_log('New LP - Adding '.$stop.' seconds - now '.$this->current_stop_time,0);
+		 		//}else{
+		 			//if no previous stop time set, use the one just calculated now from
+		 			//start time
+		 			//$this->current_start_time = $start;
+		 			//$this->current_stop_time  = $now;
+		 			//error_log('New LP - Setting '.$stop.' seconds - now '.$this->current_stop_time,0);
+		 		//}
+	 		}*/
+    	}
+    }
+    /**
+     * Write objectives to DB. This method is separate from write_to_db() because otherwise
+     * objectives are lost as a side effect to AJAX and session concurrent access
+     * @return	boolean		True or false on error
+     */
+    function write_objectives_to_db()
+    {
+   		if($this->debug>0){error_log('New LP - In learnpathItem::write_objectives_to_db()',0);}
+     	if(is_array($this->objectives) && count($this->objectives)>0){
+     		//save objectives
+     		$tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+     		$sql = "SELECT id FROM $tbl " .
+     				"WHERE lp_item_id = ".$this->db_id." " .
+     				"AND   lp_view_id = ".$this->view_id." " .
+     				"AND   view_count = ".$this->attempt_id;
+     		$res = Database::query($sql,__FILE__,__LINE__);
+     		if(Database::num_rows($res)>0){
+     			$row = Database::fetch_array($res);
+     			$lp_iv_id = $row[0];
+     			if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Got item_view_id '.$lp_iv_id.', now checking objectives ',0);}
+	     		foreach($this->objectives as $index => $objective){
+	     			$iva_table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
+	     			$iva_sql = "SELECT id FROM $iva_table " .
+	     					"WHERE lp_iv_id = $lp_iv_id " .
+	     					//"AND order_id = $index";
+							//also check for the objective ID as it must be unique for this SCO view
+	     					"AND objective_id = '".Database::escape_string($objective[0])."'";
+	     			$iva_res = Database::query($iva_sql,__FILE__,__LINE__);
+					//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
+	     			if(Database::num_rows($iva_res)>0){
+	     				//update (or don't)
+	     				$iva_row = Database::fetch_array($iva_res);
+	     				$iva_id = $iva_row[0];
+	     				$ivau_sql = "UPDATE $iva_table " .
+	     					"SET objective_id = '".Database::escape_string($objective[0])."'," .
+	     					"status = '".Database::escape_string($objective[1])."'," .
+	     					"score_raw = '".Database::escape_string($objective[2])."'," .
+	     					"score_min = '".Database::escape_string($objective[4])."'," .
+	     					"score_max = '".Database::escape_string($objective[3])."' " .
+	     					"WHERE id = $iva_id";
+	     				$ivau_res = Database::query($ivau_sql,__FILE__,__LINE__);
+	     				//error_log($ivau_sql,0);
+	     			}else{
+	     				//insert new one
+	     				$ivai_sql = "INSERT INTO $iva_table " .
+	     						"(lp_iv_id, order_id, objective_id, status, score_raw, score_min, score_max )" .
+	     						"VALUES" .
+	     						"(".$lp_iv_id.", ".$index.",'".Database::escape_string($objective[0])."','".Database::escape_string($objective[1])."'," .
+	     						"'".Database::escape_string($objective[2])."','".Database::escape_string($objective[4])."','".Database::escape_string($objective[3])."')";
+	     				$ivai_res = Database::query($ivai_sql,__FILE__,__LINE__);
+	     				//error_log($ivai_sql);
+	     			}
+	     		}
+     		}
+     	}
+     	else
+     	{
+     		//error_log('no objective to save: '.print_r($this->objectives,1));
+     	}
+    }
+    /**
+     * Writes the current data to the database
+     * @return	boolean	Query result
+     */
+     function write_to_db()
+     {
+
+   		if($this->debug>0){error_log('New LP - In learnpathItem::write_to_db()',0);}
+   		$mode = $this->get_lesson_mode();
+   		$credit = $this->get_credit();
+   		$my_verified_status=$this->get_status(false);
 
-   		if($this->debug>0){error_log('New LP - In learnpathItem::write_to_db()',0);}
-   		$mode = $this->get_lesson_mode();
-   		$credit = $this->get_credit();
-   		$my_verified_status=$this->get_status(false);
+   		$item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+		$sql_verified='SELECT status FROM '.$item_view_table.' WHERE lp_item_id="'.$this->db_id.'" AND lp_view_id="'.$this->view_id.'" AND view_count="'.$this->attempt_id.'" ;';
+		$rs_verified=Database::query($sql_verified,__FILE__,__LINE__);
+		$row_verified=Database::fetch_array($rs_verified);
 
-   		$item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-		$sql_verified='SELECT status FROM '.$item_view_table.' WHERE lp_item_id="'.$this->db_id.'" AND lp_view_id="'.$this->view_id.'" AND view_count="'.$this->attempt_id.'" ;';
-		$rs_verified=Database::query($sql_verified,__FILE__,__LINE__);
-		$row_verified=Database::fetch_array($rs_verified);
+   		$my_case_completed=array('completed','passed','browsed','failed');//added by isaac flores
+   		if (in_array($sql_verified['status'],$my_case_completed)) {
+   			$save=false;
+   		} else {
+   			$save=true;
+   		}
 
-   		$my_case_completed=array('completed','passed','browsed','failed');//added by isaac flores
-   		if (in_array($sql_verified['status'],$my_case_completed)) {
-   			$save=false;
-   		} else {
-   			$save=true;
-   		}
-
-   		if (($save===false && $this->type == 'sco') ||(($this->type == 'sco') && ($credit == 'no-credit' OR $mode == 'review' OR $mode == 'browse')))
-   		{
-   			//this info shouldn't be saved as the credit or lesson mode info prevent it
-   			if($this->debug>1){error_log('New LP - In learnpathItem::write_to_db() - credit('.$credit.') or lesson_mode('.$mode.') prevent recording!',0);}
-   		} else {
-      		//check the row exists
-      		$inserted = false;
+   		if (($save===false && $this->type == 'sco') ||(($this->type == 'sco') && ($credit == 'no-credit' OR $mode == 'review' OR $mode == 'browse')))
+   		{
+   			//this info shouldn't be saved as the credit or lesson mode info prevent it
+   			if($this->debug>1){error_log('New LP - In learnpathItem::write_to_db() - credit('.$credit.') or lesson_mode('.$mode.') prevent recording!',0);}
+   		} else {
+      		//check the row exists
+      		$inserted = false;
 
-      		// this a special case for multiple attempts and Dokeos exercises
+      		// this a special case for multiple attempts and Dokeos exercises
       		if ($this->type == 'quiz' && $this->get_prevent_reinit()==0 && $this->get_status()=='completed') {
       			// we force the item to be restarted
-      			$this->restart();
+      			$this->restart();
 
-      			$sql = "INSERT INTO $item_view_table " .
-		     			"(total_time, " .
-		     			"start_time, " .
-		     			"score, " .
-		     			"status, " .
-		     			"max_score, ".
-		     			"lp_item_id, " .
-		     			"lp_view_id, " .
-		     			"view_count, " .
-		     			"suspend_data, " .
-		     			//"max_time_allowed," .
-		     			"lesson_location)" .
-		     			"VALUES" .
-		     			"(".$this->get_total_time()."," .
-		     			"".$this->current_start_time."," .
-		     			"".$this->get_score()."," .
-		     			"'".$this->get_status(false)."'," .
-		     			"'".$this->get_max()."'," .
-		     			"".$this->db_id."," .
-		     			"".$this->view_id."," .
-		     			"".$this->get_attempt_id()."," .
-		     			"'".Database::escape_string($this->current_data)."'," .
-		     			//"'".$this->get_max_time_allowed()."'," .
-		     			"'".$this->lesson_location."')";
+      			$sql = "INSERT INTO $item_view_table " .
+		     			"(total_time, " .
+		     			"start_time, " .
+		     			"score, " .
+		     			"status, " .
+		     			"max_score, ".
+		     			"lp_item_id, " .
+		     			"lp_view_id, " .
+		     			"view_count, " .
+		     			"suspend_data, " .
+		     			//"max_time_allowed," .
+		     			"lesson_location)" .
+		     			"VALUES" .
+		     			"(".$this->get_total_time()."," .
+		     			"".$this->current_start_time."," .
+		     			"".$this->get_score()."," .
+		     			"'".$this->get_status(false)."'," .
+		     			"'".$this->get_max()."'," .
+		     			"".$this->db_id."," .
+		     			"".$this->view_id."," .
+		     			"".$this->get_attempt_id()."," .
+		     			"'".Database::escape_string($this->current_data)."'," .
+		     			//"'".$this->get_max_time_allowed()."'," .
+		     			"'".$this->lesson_location."')";
 
-      			if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Inserting into item_view forced: '.$sql,0);}
-		     	$res = Database::query($sql,__FILE__,__LINE__);
+      			if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Inserting into item_view forced: '.$sql,0);}
+		     	$res = Database::query($sql,__FILE__,__LINE__);
 		     	$this->db_item_view_id = Database::get_last_insert_id();
 		     	$inserted = true;
 		   }
 
-	     	$item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-	     	$check = "SELECT * FROM $item_view_table " .
-	     			"WHERE lp_item_id = ".$this->db_id. " " .
-	     			"AND   lp_view_id = ".$this->view_id. " ".
-	     			"AND   view_count = ".$this->get_attempt_id();
-	     	if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Querying item_view: '.$check,0);}
-	     	$check_res = Database::query($check);
-	     	//depending on what we want (really), we'll update or insert a new row
-	     	//now save into DB
-	     	$res = 0;
-	     	if( $inserted==false && Database::num_rows($check_res)<1){
-                /*$my_status = '';
-	     		if ($this->type!=TOOL_QUIZ) {
-	     				$my_status = $this->get_status(false);
-	     		}*/
-
-		     	$sql = "INSERT INTO $item_view_table " .
-		     			"(total_time, " .
-		     			"start_time, " .
-		     			"score, " .
-		     			"status, " .
-		     			"max_score, ".
-		     			"lp_item_id, " .
-		     			"lp_view_id, " .
-		     			"view_count, " .
-		     			"suspend_data, " .
-		     			//"max_time_allowed," .
-		     			"lesson_location)" .
-		     			"VALUES" .
-		     			"(".$this->get_total_time()."," .
-		     			"".$this->current_start_time."," .
-		     			"".$this->get_score()."," .
-		     			"'".$this->get_status(false)."'," .
-		     			"'".$this->get_max()."'," .
-		     			"".$this->db_id."," .
-		     			"".$this->view_id."," .
-		     			"".$this->get_attempt_id()."," .
-		     			"'".Database::escape_string($this->current_data)."'," .
-		     			//"'".$this->get_max_time_allowed()."'," .
-		     			"'".$this->lesson_location."')";
-		     	if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Inserting into item_view: '.$sql,0);}
-		     	$res = Database::query($sql,__FILE__,__LINE__);
-		     	$this->db_item_view_id = Database::get_last_insert_id();
-	     	} else {
-	     		$sql = '';
-	     		if($this->type=='hotpotatoes') {
-	     			//make an exception for HotPotatoes, don't update the score
-		     		//because it has been saved outside of this tool
-			     	$sql = "UPDATE $item_view_table " .
-			     			"SET total_time = ".$this->get_total_time().", " .
-			     			" start_time = ".$this->get_current_start_time().", " .
-			     			" score = ".$this->get_score().", " .
-			     			" status = '".$this->get_status(false)."'," .
-			     			" max_score = '".$this->get_max()."'," .
-			     			" suspend_data = '".Database::escape_string($this->current_data)."'," .
-			     			" lesson_location = '".$this->lesson_location."' " .
-			     			"WHERE lp_item_id = ".$this->db_id." " .
-			     			"AND lp_view_id = ".$this->view_id." " .
-			     			"AND view_count = ".$this->attempt_id;
-	     		} else {
+	     	$item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+	     	$check = "SELECT * FROM $item_view_table " .
+	     			"WHERE lp_item_id = ".$this->db_id. " " .
+	     			"AND   lp_view_id = ".$this->view_id. " ".
+	     			"AND   view_count = ".$this->get_attempt_id();
+	     	if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Querying item_view: '.$check,0);}
+	     	$check_res = Database::query($check);
+	     	//depending on what we want (really), we'll update or insert a new row
+	     	//now save into DB
+	     	$res = 0;
+	     	if( $inserted==false && Database::num_rows($check_res)<1){
+                /*$my_status = '';
+	     		if ($this->type!=TOOL_QUIZ) {
+	     				$my_status = $this->get_status(false);
+	     		}*/
+
+		     	$sql = "INSERT INTO $item_view_table " .
+		     			"(total_time, " .
+		     			"start_time, " .
+		     			"score, " .
+		     			"status, " .
+		     			"max_score, ".
+		     			"lp_item_id, " .
+		     			"lp_view_id, " .
+		     			"view_count, " .
+		     			"suspend_data, " .
+		     			//"max_time_allowed," .
+		     			"lesson_location)" .
+		     			"VALUES" .
+		     			"(".$this->get_total_time()."," .
+		     			"".$this->current_start_time."," .
+		     			"".$this->get_score()."," .
+		     			"'".$this->get_status(false)."'," .
+		     			"'".$this->get_max()."'," .
+		     			"".$this->db_id."," .
+		     			"".$this->view_id."," .
+		     			"".$this->get_attempt_id()."," .
+		     			"'".Database::escape_string($this->current_data)."'," .
+		     			//"'".$this->get_max_time_allowed()."'," .
+		     			"'".$this->lesson_location."')";
+		     	if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Inserting into item_view: '.$sql,0);}
+		     	$res = Database::query($sql,__FILE__,__LINE__);
+		     	$this->db_item_view_id = Database::get_last_insert_id();
+	     	} else {
+	     		$sql = '';
+	     		if($this->type=='hotpotatoes') {
+	     			//make an exception for HotPotatoes, don't update the score
+		     		//because it has been saved outside of this tool
+			     	$sql = "UPDATE $item_view_table " .
+			     			"SET total_time = ".$this->get_total_time().", " .
+			     			" start_time = ".$this->get_current_start_time().", " .
+			     			" score = ".$this->get_score().", " .
+			     			" status = '".$this->get_status(false)."'," .
+			     			" max_score = '".$this->get_max()."'," .
+			     			" suspend_data = '".Database::escape_string($this->current_data)."'," .
+			     			" lesson_location = '".$this->lesson_location."' " .
+			     			"WHERE lp_item_id = ".$this->db_id." " .
+			     			"AND lp_view_id = ".$this->view_id." " .
+			     			"AND view_count = ".$this->attempt_id;
+	     		} else {
 	     			//for all other content types...
-	     			if ($this->type=='quiz') {
+	     			if ($this->type=='quiz') {
 	     				$my_status = ' ';
 	     				$total_time = ' ';
-	     				if (!empty($_REQUEST['exeId'])) {
-							$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+	     				if (!empty($_REQUEST['exeId'])) {
+							$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 
-							$safe_exe_id = Database::escape_string($_REQUEST['exeId']);
-		     				$sql = 'SELECT start_date,exe_date FROM ' . $TBL_TRACK_EXERCICES . ' WHERE exe_id = '.(int)$safe_exe_id;
-							$res = Database::query($sql,__FILE__,__LINE__);
+							$safe_exe_id = Database::escape_string($_REQUEST['exeId']);
+		     				$sql = 'SELECT start_date,exe_date FROM ' . $TBL_TRACK_EXERCICES . ' WHERE exe_id = '.(int)$safe_exe_id;
+							$res = Database::query($sql,__FILE__,__LINE__);
 							$row_dates = Database::fetch_array($res);
 
-							$time_start_date = convert_mysql_date($row_dates['start_date']);
-							$time_exe_date 	 = convert_mysql_date($row_dates['exe_date']);
-							$mytime = ((int)$time_exe_date-(int)$time_start_date);
-							$total_time =" total_time = ".$mytime.", ";
+							$time_start_date = convert_mysql_date($row_dates['start_date']);
+							$time_exe_date 	 = convert_mysql_date($row_dates['exe_date']);
+							$mytime = ((int)$time_exe_date-(int)$time_start_date);
+							$total_time =" total_time = ".$mytime.", ";
 	     				}
-	     			} else {
-	     				$my_type_lp=learnpath::get_type_static($this->lp_id);
-	     				// this is a array containing values finished
-	     				$case_completed=array('completed','passed','browsed');
-
-	     				//is not multiple attempts
+	     			} else {
+	     				$my_type_lp=learnpath::get_type_static($this->lp_id);
+	     				// this is a array containing values finished
+	     				$case_completed=array('completed','passed','browsed');
+
+	     				//is not multiple attempts
 	     				if ($this->get_prevent_reinit()==1) {
-			  		     	// process of status verified into data base
+			  		     	// process of status verified into data base
 
-		     				$sql_verified='SELECT status FROM '.$item_view_table.' WHERE lp_item_id="'.$this->db_id.'" AND lp_view_id="'.$this->view_id.'" AND view_count="'.$this->attempt_id.'" ;';
-		     				$rs_verified=Database::query($sql_verified,__FILE__,__LINE__);
-		     				$row_verified=Database::fetch_array($rs_verified);
+		     				$sql_verified='SELECT status FROM '.$item_view_table.' WHERE lp_item_id="'.$this->db_id.'" AND lp_view_id="'.$this->view_id.'" AND view_count="'.$this->attempt_id.'" ;';
+		     				$rs_verified=Database::query($sql_verified,__FILE__,__LINE__);
+		     				$row_verified=Database::fetch_array($rs_verified);
 
 		     				//get type lp: 1=lp dokeos and  2=scorm
 			    			// if not is completed or passed or browsed and learning path is scorm
-		     				if(!in_array($this->get_status(false),$case_completed) && $my_type_lp==2 ) {//&& $this->type!='dir'
+		     				if(!in_array($this->get_status(false),$case_completed) && $my_type_lp==2 ) {//&& $this->type!='dir'
 		     					$total_time =" total_time = total_time +".$this->get_total_time().", ";
 		     					$my_status = " status = '".$this->get_status(false)."' ,";
-		     				} else {
-		     					//verified into data base
-		     					if (!in_array($row_verified['status'],$case_completed) && $my_type_lp==2 ) { //&& $this->type!='dir'
-		     						$total_time =" total_time = total_time +".$this->get_total_time().", ";
+		     				} else {
+		     					//verified into data base
+		     					if (!in_array($row_verified['status'],$case_completed) && $my_type_lp==2 ) { //&& $this->type!='dir'
+		     						$total_time =" total_time = total_time +".$this->get_total_time().", ";
 		     						$my_status = " status = '".$this->get_status(false)."' ,";
-		     	 				} elseif (in_array($row_verified['status'],$case_completed) && $my_type_lp==2 && $this->type!='sco' ) {//&& $this->type!='dir'
-		     	 					$total_time =" total_time = total_time +".$this->get_total_time().", ";
+		     	 				} elseif (in_array($row_verified['status'],$case_completed) && $my_type_lp==2 && $this->type!='sco' ) {//&& $this->type!='dir'
+		     	 					$total_time =" total_time = total_time +".$this->get_total_time().", ";
 		     	 					$my_status = " status = '".$this->get_status(false)."' ,";
-		     					}else {
+		     					}else {
 		     	 				//&& !in_array($row_verified['status'],$case_completed)
-		     	 				//is lp dokeos
-		     	 					if ($my_type_lp==1 && $this->type!='chapter') {
-	     								$total_time =" total_time = total_time + ".$this->get_total_time().", ";
+		     	 				//is lp dokeos
+		     	 					if ($my_type_lp==1 && $this->type!='chapter') {
+	     								$total_time =" total_time = total_time + ".$this->get_total_time().", ";
 	     								$my_status = " status = '".$this->get_status(false)."' ,";
 	     							}
 		     	 				}
-		     				}
-	     				} else {
-	     					// is multiple attempts
-	     					if (in_array($this->get_status(false),$case_completed) &&  $my_type_lp==2) {
+		     				}
+	     				} else {
+	     					// is multiple attempts
+	     					if (in_array($this->get_status(false),$case_completed) &&  $my_type_lp==2) {
 	     						//reset zero new attempt ?
-	     						$my_status = " status = '".$this->get_status(false)."' ,";
-	     					}  elseif (!in_array($this->get_status(false),$case_completed) &&  $my_type_lp==2){
-	     						$total_time =" total_time = ".$this->get_total_time().", ";
 	     						$my_status = " status = '".$this->get_status(false)."' ,";
-	     					} else {
-	     						//is dokeos LP
-	     						$total_time =" total_time = total_time +".$this->get_total_time().", ";
+	     					}  elseif (!in_array($this->get_status(false),$case_completed) &&  $my_type_lp==2){
+	     						$total_time =" total_time = ".$this->get_total_time().", ";
+	     						$my_status = " status = '".$this->get_status(false)."' ,";
+	     					} else {
+	     						//is dokeos LP
+	     						$total_time =" total_time = total_time +".$this->get_total_time().", ";
 	     						$my_status = " status = '".$this->get_status(false)."' ,";
 	     					}
 
-	     					//code added by isaac flores
-	     					//this code line fix the problem of wrong status
-	     					if ( $my_type_lp==2) {
-				     			//verify current status in multiples attempts
-				     			$sql_status='SELECT status FROM '.$item_view_table.' WHERE lp_item_id="'.$this->db_id.'" AND lp_view_id="'.$this->view_id.'" AND view_count="'.$this->attempt_id.'" ';
-						     	$rs_status=Database::query($sql_status,__FILE__,__LINE__);
-						     	$current_status=Database::result($rs_status,0,'status');
-						     	if (in_array($current_status,$case_completed)) {
-						     		$my_status='';
-						     		$total_time='';
-						     	} else {
-						     		$total_time =" total_time = total_time +".$this->get_total_time().", ";
-						     	}
+	     					//code added by isaac flores
+	     					//this code line fix the problem of wrong status
+	     					if ( $my_type_lp==2) {
+				     			//verify current status in multiples attempts
+				     			$sql_status='SELECT status FROM '.$item_view_table.' WHERE lp_item_id="'.$this->db_id.'" AND lp_view_id="'.$this->view_id.'" AND view_count="'.$this->attempt_id.'" ';
+						     	$rs_status=Database::query($sql_status,__FILE__,__LINE__);
+						     	$current_status=Database::result($rs_status,0,'status');
+						     	if (in_array($current_status,$case_completed)) {
+						     		$my_status='';
+						     		$total_time='';
+						     	} else {
+						     		$total_time =" total_time = total_time +".$this->get_total_time().", ";
+						     	}
 	     					}
 	     				}
-	     				/*if ($my_type_lp==1 && !in_array($row_verified['status'],$case_completed)) {
-	     					$total_time =" total_time = total_time + ".$this->get_total_time().", ";
-	     				}*/
+	     				/*if ($my_type_lp==1 && !in_array($row_verified['status'],$case_completed)) {
+	     					$total_time =" total_time = total_time + ".$this->get_total_time().", ";
+	     				}*/
+
+	     			}
 
-	     			}
-
-			     	$sql = "UPDATE $item_view_table " .
-			     			"SET " .$total_time.
-			     			" start_time = ".$this->get_current_start_time().", " .
-			     			" score = ".$this->get_score().", " .
-			     			$my_status.
-			     			" max_score = '".$this->get_max()."'," .
-			     			" suspend_data = '".Database::escape_string($this->current_data)."'," .
-			     			//" max_time_allowed = '".$this->get_max_time_allowed()."'," .
-			     			" lesson_location = '".$this->lesson_location."' " .
-			     			"WHERE lp_item_id = ".$this->db_id." " .
-			     			"AND lp_view_id = ".$this->view_id." " .
-			     			"AND view_count = ".$this->attempt_id;
+			     	$sql = "UPDATE $item_view_table " .
+			     			"SET " .$total_time.
+			     			" start_time = ".$this->get_current_start_time().", " .
+			     			" score = ".$this->get_score().", " .
+			     			$my_status.
+			     			" max_score = '".$this->get_max()."'," .
+			     			" suspend_data = '".Database::escape_string($this->current_data)."'," .
+			     			//" max_time_allowed = '".$this->get_max_time_allowed()."'," .
+			     			" lesson_location = '".$this->lesson_location."' " .
+			     			"WHERE lp_item_id = ".$this->db_id." " .
+			     			"AND lp_view_id = ".$this->view_id." " .
+			     			"AND view_count = ".$this->attempt_id;
 
-			     			$this->current_start_time = time();
-	     		}
-	    	 	if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Updating item_view: '.$sql,0);}
-		     	$res = Database::query($sql,__FILE__,__LINE__);
-	     	}
-	     	//if(!$res)
-	     	//{
-	     	//	$this->error = 'Could not update item_view table...'.mysql_error();
-	     	//}
-	     	if(is_array($this->interactions) && count($this->interactions)>0){
-	     		//save interactions
-	     		$tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-	     		$sql = "SELECT id FROM $tbl " .
-	     				"WHERE lp_item_id = ".$this->db_id." " .
-	     				"AND   lp_view_id = ".$this->view_id." " .
-	     				"AND   view_count = ".$this->attempt_id;
-	     		$res = Database::query($sql,__FILE__,__LINE__);
-	     		if(Database::num_rows($res)>0){
-	     			$row = Database::fetch_array($res);
-	     			$lp_iv_id = $row[0];
-	     			if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Got item_view_id '.$lp_iv_id.', now checking interactions ',0);}
-		     		foreach($this->interactions as $index => $interaction){
-		     			$correct_resp = '';
-		     			if(is_array($interaction[4]) && !empty($interaction[4][0]) ){
-		     				foreach($interaction[4] as $resp){
-		     					$correct_resp .= $resp.',';
-		     				}
-		     				$correct_resp = substr($correct_resp,0,strlen($correct_resp)-1);
-		     			}
-		     			$iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
-		     			$iva_sql = "SELECT id FROM $iva_table " .
-		     					"WHERE lp_iv_id = $lp_iv_id " .
-//		     					"AND order_id = $index";
-								//also check for the interaction ID as it must be unique for this SCO view
-		     					"AND (order_id = $index " .
-		     					"OR interaction_id = '".Database::escape_string($interaction[0])."')";
-		     			$iva_res = Database::query($iva_sql,__FILE__,__LINE__);
-						//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
-		     			if(Database::num_rows($iva_res)>0){
-		     				//update (or don't)
-		     				$iva_row = Database::fetch_array($iva_res);
-		     				$iva_id = $iva_row[0];
-		     				$ivau_sql = "UPDATE $iva_table " .
-		     					"SET interaction_id = '".Database::escape_string($interaction[0])."'," .
-		     					"interaction_type = '".Database::escape_string($interaction[1])."'," .
-		     					"weighting = '".Database::escape_string($interaction[3])."'," .
-		     					"completion_time = '".Database::escape_string($interaction[2])."'," .
-		     					"correct_responses = '".Database::escape_string($correct_resp)."'," .
-		     					"student_response = '".Database::escape_string($interaction[5])."'," .
-		     					"result = '".Database::escape_string($interaction[6])."'," .
-		     					"latency = '".Database::escape_string($interaction[7])."'" .
-		     					"WHERE id = $iva_id";
-		     				$ivau_res = Database::query($ivau_sql,__FILE__,__LINE__);
-		     			} else {
-		     				//insert new one
-		     				$ivai_sql = "INSERT INTO $iva_table " .
-		     						"(order_id, lp_iv_id, interaction_id, interaction_type, " .
-		     						"weighting, completion_time, correct_responses, " .
-		     						"student_response, result, latency)" .
-		     						"VALUES" .
-		     						"(".$index.",".$lp_iv_id.",'".Database::escape_string($interaction[0])."','".Database::escape_string($interaction[1])."'," .
-		     						"'".Database::escape_string($interaction[3])."','".Database::escape_string($interaction[2])."','".Database::escape_string($correct_resp)."'," .
-		     						"'".Database::escape_string($interaction[5])."','".Database::escape_string($interaction[6])."','".Database::escape_string($interaction[7])."'" .
-		     						")";
-		     				$ivai_res = Database::query($ivai_sql,__FILE__,__LINE__);
-		     			}
-		     		}
-	     		}
-	     	}
-   		}
-		if($this->debug>2){error_log('New LP - End of learnpathItem::write_to_db()',0);}
-     	return true;
-     }
-}
-?>
+			     			$this->current_start_time = time();
+	     		}
+	    	 	if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Updating item_view: '.$sql,0);}
+		     	$res = Database::query($sql,__FILE__,__LINE__);
+	     	}
+	     	//if(!$res)
+	     	//{
+	     	//	$this->error = 'Could not update item_view table...'.mysql_error();
+	     	//}
+	     	if(is_array($this->interactions) && count($this->interactions)>0){
+	     		//save interactions
+	     		$tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+	     		$sql = "SELECT id FROM $tbl " .
+	     				"WHERE lp_item_id = ".$this->db_id." " .
+	     				"AND   lp_view_id = ".$this->view_id." " .
+	     				"AND   view_count = ".$this->attempt_id;
+	     		$res = Database::query($sql,__FILE__,__LINE__);
+	     		if(Database::num_rows($res)>0){
+	     			$row = Database::fetch_array($res);
+	     			$lp_iv_id = $row[0];
+	     			if($this->debug>2){error_log('New LP - In learnpathItem::write_to_db() - Got item_view_id '.$lp_iv_id.', now checking interactions ',0);}
+		     		foreach($this->interactions as $index => $interaction){
+		     			$correct_resp = '';
+		     			if(is_array($interaction[4]) && !empty($interaction[4][0]) ){
+		     				foreach($interaction[4] as $resp){
+		     					$correct_resp .= $resp.',';
+		     				}
+		     				$correct_resp = substr($correct_resp,0,strlen($correct_resp)-1);
+		     			}
+		     			$iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
+		     			$iva_sql = "SELECT id FROM $iva_table " .
+		     					"WHERE lp_iv_id = $lp_iv_id " .
+//		     					"AND order_id = $index";
+								//also check for the interaction ID as it must be unique for this SCO view
+		     					"AND (order_id = $index " .
+		     					"OR interaction_id = '".Database::escape_string($interaction[0])."')";
+		     			$iva_res = Database::query($iva_sql,__FILE__,__LINE__);
+						//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
+		     			if(Database::num_rows($iva_res)>0){
+		     				//update (or don't)
+		     				$iva_row = Database::fetch_array($iva_res);
+		     				$iva_id = $iva_row[0];
+		     				$ivau_sql = "UPDATE $iva_table " .
+		     					"SET interaction_id = '".Database::escape_string($interaction[0])."'," .
+		     					"interaction_type = '".Database::escape_string($interaction[1])."'," .
+		     					"weighting = '".Database::escape_string($interaction[3])."'," .
+		     					"completion_time = '".Database::escape_string($interaction[2])."'," .
+		     					"correct_responses = '".Database::escape_string($correct_resp)."'," .
+		     					"student_response = '".Database::escape_string($interaction[5])."'," .
+		     					"result = '".Database::escape_string($interaction[6])."'," .
+		     					"latency = '".Database::escape_string($interaction[7])."'" .
+		     					"WHERE id = $iva_id";
+		     				$ivau_res = Database::query($ivau_sql,__FILE__,__LINE__);
+		     			} else {
+		     				//insert new one
+		     				$ivai_sql = "INSERT INTO $iva_table " .
+		     						"(order_id, lp_iv_id, interaction_id, interaction_type, " .
+		     						"weighting, completion_time, correct_responses, " .
+		     						"student_response, result, latency)" .
+		     						"VALUES" .
+		     						"(".$index.",".$lp_iv_id.",'".Database::escape_string($interaction[0])."','".Database::escape_string($interaction[1])."'," .
+		     						"'".Database::escape_string($interaction[3])."','".Database::escape_string($interaction[2])."','".Database::escape_string($correct_resp)."'," .
+		     						"'".Database::escape_string($interaction[5])."','".Database::escape_string($interaction[6])."','".Database::escape_string($interaction[7])."'" .
+		     						")";
+		     				$ivai_res = Database::query($ivai_sql,__FILE__,__LINE__);
+		     			}
+		     		}
+	     		}
+	     	}
+   		}
+		if($this->debug>2){error_log('New LP - End of learnpathItem::write_to_db()',0);}
+     	return true;
+     }
+}
+?>

+ 101 - 101
main/newscorm/learnpathList.class.php

@@ -1,106 +1,106 @@
-<?php //$id:$
-/**
- * File containing the declaration of the learnpathList class.
- * @package	dokeos.learnpath
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * This class is only a learning path list container with several practical methods for sorting the list and
- * provide links to specific paths
- * @uses	Database.lib.php to use the database
- * @uses	learnpath.class.php to generate learnpath objects to get in the list
- */
-class learnpathList {
-	var $list = array(); //holds a flat list of learnpaths data from the database
-	var $ref_list = array(); //holds a list of references to the learnpaths objects (only filled by get_refs())
-	var $alpha_list = array(); //holds a flat list of learnpaths sorted by alphabetical name order
-	var $course_code;
-	var $user_id;
-	var $refs_active = false;
+<?php //$id:$
+/**
+ * File containing the declaration of the learnpathList class.
+ * @package	dokeos.learnpath
+ * @author	Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * This class is only a learning path list container with several practical methods for sorting the list and
+ * provide links to specific paths
+ * @uses	Database.lib.php to use the database
+ * @uses	learnpath.class.php to generate learnpath objects to get in the list
+ */
+class learnpathList {
+	var $list = array(); //holds a flat list of learnpaths data from the database
+	var $ref_list = array(); //holds a list of references to the learnpaths objects (only filled by get_refs())
+	var $alpha_list = array(); //holds a flat list of learnpaths sorted by alphabetical name order
+	var $course_code;
+	var $user_id;
+	var $refs_active = false;
 
-	/**
-	 * This method is the constructor for the learnpathList. It gets a list of available learning paths from
+	/**
+	 * This method is the constructor for the learnpathList. It gets a list of available learning paths from
 	 * the database and creates the learnpath objects. This list depends on the user that is connected
-	 * (only displays) items if he has enough permissions to view them.
-	 * @param	integer		User ID
-	 * @param	string		Optional course code (otherwise we use api_get_course_id())
-	 * @return	void
-	 */
-    function learnpathList($user_id,$course_code='') {
-    	if(!empty($course_code)){
-    		//proceed with course code given
-    	}else{
-		$course_code = api_get_course_id();
-		$lp_table = Database::get_course_table(TABLE_LP_MAIN);
-    	}
-    	$this->course_code = $course_code;
-    	$this->user_id = $user_id;
-    	$sql = "SELECT * FROM $lp_table ORDER BY display_order ASC, name ASC";
-    	$res = Database::query($sql);
-    	$names = array();
-    	while ($row = Database::fetch_array($res))
-    	{
-    		//check if published
-    		$pub = '';
-    		$tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
-    		//use domesticate here instead of mysql_real_escape_string because
-    		//it prevents ' to be slashed and the input (done by learnpath.class.php::toggle_visibility())
-    		//is done using domesticate()
-    		$myname = domesticate($row['name']);
-			$mylink = 'newscorm/lp_controller.php?action=view&lp_id='.$row['id'];
-			$sql2="SELECT * FROM $tbl_tool where (name='$myname' and image='scormbuilder.gif' and link LIKE '$mylink%')";
-			//error_log('New LP - learnpathList::learnpathList - getting visibility - '.$sql2,0);
-			$res2 = Database::query($sql2,__FILE__,__LINE__);
-			if(Database::num_rows($res2)>0){
-				$row2 = Database::fetch_array($res2);
-				$pub = $row2['visibility'];
-			}else{
-				$pub = 'i';
-			}
-			//check if visible
-			$vis = api_get_item_visibility(api_get_course_info($course_code),'learnpath',$row['id']);
+	 * (only displays) items if he has enough permissions to view them.
+	 * @param	integer		User ID
+	 * @param	string		Optional course code (otherwise we use api_get_course_id())
+	 * @return	void
+	 */
+    function learnpathList($user_id,$course_code='') {
+    	if(!empty($course_code)){
+    		//proceed with course code given
+    	}else{
+		$course_code = api_get_course_id();
+		$lp_table = Database::get_course_table(TABLE_LP_MAIN);
+    	}
+    	$this->course_code = $course_code;
+    	$this->user_id = $user_id;
+    	$sql = "SELECT * FROM $lp_table ORDER BY display_order ASC, name ASC";
+    	$res = Database::query($sql);
+    	$names = array();
+    	while ($row = Database::fetch_array($res))
+    	{
+    		//check if published
+    		$pub = '';
+    		$tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
+    		//use domesticate here instead of mysql_real_escape_string because
+    		//it prevents ' to be slashed and the input (done by learnpath.class.php::toggle_visibility())
+    		//is done using domesticate()
+    		$myname = domesticate($row['name']);
+			$mylink = 'newscorm/lp_controller.php?action=view&lp_id='.$row['id'];
+			$sql2="SELECT * FROM $tbl_tool where (name='$myname' and image='scormbuilder.gif' and link LIKE '$mylink%')";
+			//error_log('New LP - learnpathList::learnpathList - getting visibility - '.$sql2,0);
+			$res2 = Database::query($sql2,__FILE__,__LINE__);
+			if(Database::num_rows($res2)>0){
+				$row2 = Database::fetch_array($res2);
+				$pub = $row2['visibility'];
+			}else{
+				$pub = 'i';
+			}
+			//check if visible
+			$vis = api_get_item_visibility(api_get_course_info($course_code),'learnpath',$row['id']);
 
-    		$this->list[$row['id']] = array(
-    			'lp_type' => $row['lp_type'],
-    			'lp_name' => stripslashes($row['name']),
-    			'lp_desc' => stripslashes($row['description']),
-    			'lp_path' => $row['path'],
-    			'lp_view_mode' => $row['default_view_mod'],
-    			'lp_force_commit' => $row['force_commit'],
-    			'lp_maker'	=> stripslashes($row['content_maker']),
-    			'lp_proximity' => $row['content_local'],
-    			'lp_encoding' => $row['default_encoding'],
-    			'lp_visibility' => $vis,
-    			'lp_published'	=> $pub,
-    			'lp_prevent_reinit' => $row['prevent_reinit'],
-    			'lp_scorm_debug' => $row['debug'],
-    			'lp_display_order' => $row['display_order'],
-    			'lp_preview_image' => stripslashes($row['preview_image'])
+    		$this->list[$row['id']] = array(
+    			'lp_type' => $row['lp_type'],
+    			'lp_name' => stripslashes($row['name']),
+    			'lp_desc' => stripslashes($row['description']),
+    			'lp_path' => $row['path'],
+    			'lp_view_mode' => $row['default_view_mod'],
+    			'lp_force_commit' => $row['force_commit'],
+    			'lp_maker'	=> stripslashes($row['content_maker']),
+    			'lp_proximity' => $row['content_local'],
+    			'lp_encoding' => $row['default_encoding'],
+    			'lp_visibility' => $vis,
+    			'lp_published'	=> $pub,
+    			'lp_prevent_reinit' => $row['prevent_reinit'],
+    			'lp_scorm_debug' => $row['debug'],
+    			'lp_display_order' => $row['display_order'],
+    			'lp_preview_image' => stripslashes($row['preview_image'])
     			);
-    		$names[$row['name']]=$row['id'];
-       	}
-       	$this->alpha_list = asort($names);
-    }
-    /**
-     * Gets references to learnpaths for all learnpaths IDs kept in the local list.
-     * This applies a transformation internally on list and ref_list and returns a copy of the refs list
+    		$names[$row['name']]=$row['id'];
+       	}
+       	$this->alpha_list = asort($names);
+    }
+    /**
+     * Gets references to learnpaths for all learnpaths IDs kept in the local list.
+     * This applies a transformation internally on list and ref_list and returns a copy of the refs list
      * @return	array	List of references to learnpath objects
-     */
-    function get_refs(){
-    	foreach($this->list as $id => $dummy)
-    	{
-    		$this->ref_list[$id] = new learnpath($this->course_code,$id,$this->user_id);
-    	}
-    	$this->refs_active = true;
-    	return $this->ref_list;
-    }
-    /**
-     * Gets a table of the different learnpaths we have at the moment
-     * @return	array	Learnpath info as [lp_id] => ([lp_type]=> ..., [lp_name]=>...,[lp_desc]=>...,[lp_path]=>...)
-     */
-    function get_flat_list()
-    {
-		return $this->list;
-    }
-}
-?>
+     */
+    function get_refs(){
+    	foreach($this->list as $id => $dummy)
+    	{
+    		$this->ref_list[$id] = new learnpath($this->course_code,$id,$this->user_id);
+    	}
+    	$this->refs_active = true;
+    	return $this->ref_list;
+    }
+    /**
+     * Gets a table of the different learnpaths we have at the moment
+     * @return	array	Learnpath info as [lp_id] => ([lp_type]=> ..., [lp_name]=>...,[lp_desc]=>...,[lp_path]=>...)
+     */
+    function get_flat_list()
+    {
+		return $this->list;
+    }
+}
+?>

+ 2675 - 2675
main/newscorm/learnpath_functions.inc.php

@@ -1,2730 +1,2730 @@
-<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
-==============================================================================
-*/
-
-/**
-==============================================================================
-* This is a function library for the learning path.
-*
-* Due to the face that the learning path has been built upon the resoucelinker,
-* naming conventions have changed at least 2 times. You can see here in order the :
-* 1. name used in the first version of the resourcelinker
-* 2. name used in the first version of the LP
-* 3. name used in the second (current) version of the LP
-*
-*       1.       2.        3.
-*   Category = Chapter = Module
-*   Item (?) = Item    = Step
-*
-* @author  Denes Nagy <darkden@evk.bke.hu>, main author
-* @author  Roan Embrechts, some code cleaning
-* @author	Yannick Warnier <yannick.warnier@dokeos.com>, multi-level learnpath behaviour + new SCORM tool
-* @access  public
-* @package dokeos.learnpath
-* @todo rename functions to coding conventions: not deleteitem but delete_item, etc
-* @todo rewrite functions to comply with phpDocumentor
-* @todo remove code duplication
+<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
+/*
 ==============================================================================
-*/
-
-/**
- * This function deletes an item
- * @param integer 	$id: the item we want to delete
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
+==============================================================================
+*/
+
+/**
+==============================================================================
+* This is a function library for the learning path.
+*
+* Due to the face that the learning path has been built upon the resoucelinker,
+* naming conventions have changed at least 2 times. You can see here in order the :
+* 1. name used in the first version of the resourcelinker
+* 2. name used in the first version of the LP
+* 3. name used in the second (current) version of the LP
+*
+*       1.       2.        3.
+*   Category = Chapter = Module
+*   Item (?) = Item    = Step
+*
+* @author  Denes Nagy <darkden@evk.bke.hu>, main author
+* @author  Roan Embrechts, some code cleaning
+* @author	Yannick Warnier <yannick.warnier@dokeos.com>, multi-level learnpath behaviour + new SCORM tool
+* @access  public
+* @package dokeos.learnpath
+* @todo rename functions to coding conventions: not deleteitem but delete_item, etc
+* @todo rewrite functions to comply with phpDocumentor
+* @todo remove code duplication
+==============================================================================
+*/
+
+/**
+ * This function deletes an item
+ * @param integer 	$id: the item we want to delete
  * @return boolean	True if item was deleted, false if not found or error
- **/
-function deleteitem($id)
-{
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-	//get the display order for this item before it is deleted
-	$sql = "SELECT display_order, parent_item_id FROM $tbl_lp_item WHERE id=$id";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	if (mysql_num_rows($result) == 0)
-	{
-		return false;
-	}
-	$row = mysql_fetch_row($result);
-	$display_order = $row[0];
-	$parent_item_id = $row[1];
-	// delete the item
-	$sql = "DELETE FROM $tbl_learnpath_item WHERE id='$id'";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	if ($result === false)
-	{
-		return false;
-	}
-	// update the other items and chapters
-	$sql = "UPDATE $tbl_learnpath_item SET display_order = display_order-1 WHERE display_order > $display_order AND parent_item_id = $parent_item_id";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$sql = "UPDATE $tbl_learnpath_chapter SET display_order = display_order-1 WHERE display_order > $display_order AND parent_item_id = $parent_item_id";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	//return
-	return true;
-}
-
-/**
- * This function deletes a module(chapter) and all its steps(items).
- *
- * @param integer id of the chapter we want to delete
- * @return boolean	True on success and false if not found or error
- **/
-function deletemodule($parent_item_id)
-{
-	global $learnpath_id;
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-
-	//Added for multi-level behaviour - slightly recursive
-	$sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id=$learnpath_id";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	while ($row = mysql_fetch_array($result))
-	{
-		if ($row['parent_item_id'] == $parent_item_id)
-		{
-			//delete every subchapter
-			if (deletemodule($row['id']) === false)
-			{
-				return false;
-			}
-		}
-	}
-
-	//get this chapter's display order
-	$sql = "SELECT display_order, parent_item_id FROM $tbl_learnpath_chapter WHERE id=$parent_item_id and lp_id=$learnpath_id";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	if (mysql_num_rows($result) == 0)
-	{
-		return false;
-	}
-	$row = mysql_fetch_row($result);
-
-	$display_order = $row[0];
-	$parent_id = $row[1];
-
-	//delete the chapter itself
-	$sql = "DELETE FROM $tbl_learnpath_chapter WHERE (id=$parent_item_id and lp_id=$learnpath_id)";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	//delete items from that chapter
-	$sql2 = "DELETE FROM $tbl_learnpath_item WHERE parent_item_id=$parent_item_id";
-	$result = Database::query($sql2, __FILE__, __LINE__);
-
-	//update all other chapters accordingly
-	$sql = "UPDATE $tbl_learnpath_item SET display_order = display_order-1 WHERE display_order > $display_order AND parent_item_id = $parent_id";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$sql = "UPDATE $tbl_learnpath_chapter SET display_order = display_order-1 WHERE display_order > $display_order AND parent_item_id = $parent_id";
-	$result = Database::query($sql, __FILE__, __LINE__);
-
-	return true;
-}
-
-/**
- * This function deletes an entire path.
- *
- * @param integer 	$id: the path we want to delete
+ **/
+function deleteitem($id)
+{
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+	//get the display order for this item before it is deleted
+	$sql = "SELECT display_order, parent_item_id FROM $tbl_lp_item WHERE id=$id";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	if (mysql_num_rows($result) == 0)
+	{
+		return false;
+	}
+	$row = mysql_fetch_row($result);
+	$display_order = $row[0];
+	$parent_item_id = $row[1];
+	// delete the item
+	$sql = "DELETE FROM $tbl_learnpath_item WHERE id='$id'";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	if ($result === false)
+	{
+		return false;
+	}
+	// update the other items and chapters
+	$sql = "UPDATE $tbl_learnpath_item SET display_order = display_order-1 WHERE display_order > $display_order AND parent_item_id = $parent_item_id";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$sql = "UPDATE $tbl_learnpath_chapter SET display_order = display_order-1 WHERE display_order > $display_order AND parent_item_id = $parent_item_id";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	//return
+	return true;
+}
+
+/**
+ * This function deletes a module(chapter) and all its steps(items).
+ *
+ * @param integer id of the chapter we want to delete
+ * @return boolean	True on success and false if not found or error
+ **/
+function deletemodule($parent_item_id)
+{
+	global $learnpath_id;
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+
+	//Added for multi-level behaviour - slightly recursive
+	$sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id=$learnpath_id";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	while ($row = mysql_fetch_array($result))
+	{
+		if ($row['parent_item_id'] == $parent_item_id)
+		{
+			//delete every subchapter
+			if (deletemodule($row['id']) === false)
+			{
+				return false;
+			}
+		}
+	}
+
+	//get this chapter's display order
+	$sql = "SELECT display_order, parent_item_id FROM $tbl_learnpath_chapter WHERE id=$parent_item_id and lp_id=$learnpath_id";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	if (mysql_num_rows($result) == 0)
+	{
+		return false;
+	}
+	$row = mysql_fetch_row($result);
+
+	$display_order = $row[0];
+	$parent_id = $row[1];
+
+	//delete the chapter itself
+	$sql = "DELETE FROM $tbl_learnpath_chapter WHERE (id=$parent_item_id and lp_id=$learnpath_id)";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	//delete items from that chapter
+	$sql2 = "DELETE FROM $tbl_learnpath_item WHERE parent_item_id=$parent_item_id";
+	$result = Database::query($sql2, __FILE__, __LINE__);
+
+	//update all other chapters accordingly
+	$sql = "UPDATE $tbl_learnpath_item SET display_order = display_order-1 WHERE display_order > $display_order AND parent_item_id = $parent_id";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$sql = "UPDATE $tbl_learnpath_chapter SET display_order = display_order-1 WHERE display_order > $display_order AND parent_item_id = $parent_id";
+	$result = Database::query($sql, __FILE__, __LINE__);
+
+	return true;
+}
+
+/**
+ * This function deletes an entire path.
+ *
+ * @param integer 	$id: the path we want to delete
  * @return	void
- **/
-function deletepath($path_id)
-{
-	$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-
-	$sql = "DELETE FROM $tbl_learnpath_main WHERE lp_id='$path_id'";
-	$result = Database::query($sql, __FILE__, __LINE__);
-
-	//@TODO check how this function is used before uncommenting the following
-	//also delete all elements inside that path
-	$sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id=$path_id";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	while ($row = mysql_fetch_array($result))
-	{
-		deletemodule($row['id']);
-	}
-}
-
-/**
- * This function moves an item.
- *
- * @param string    $direction: move the given chapter up or down
- * @param integer   Item ID
- * @param integer   $moduleid: the id of the chapter the element resides in
+ **/
+function deletepath($path_id)
+{
+	$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+
+	$sql = "DELETE FROM $tbl_learnpath_main WHERE lp_id='$path_id'";
+	$result = Database::query($sql, __FILE__, __LINE__);
+
+	//@TODO check how this function is used before uncommenting the following
+	//also delete all elements inside that path
+	$sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id=$path_id";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	while ($row = mysql_fetch_array($result))
+	{
+		deletemodule($row['id']);
+	}
+}
+
+/**
+ * This function moves an item.
+ *
+ * @param string    $direction: move the given chapter up or down
+ * @param integer   Item ID
+ * @param integer   $moduleid: the id of the chapter the element resides in
  * @return	boolean	Returns false on error
- * @note    With this new version, the moveitem deals with items AND directories (not the base-level modules). This is a lot more complicated but is a temporary step towards new database structure as 'everything is an item'
- **/
-function moveitem($direction, $id, $moduleid, $type = 'item')
-{
-	global $learnpath_id;
-	$tbl_learnpath_item     = Database::get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter  = Database::get_course_table(TABLE_LEARNPATH_CHAPTER);
-
-	$tree = get_learnpath_tree($learnpath_id);
-	$orig_order = 0;
-	$orig_type = '';
-	$orig_id = $id;
-	foreach ($tree[$moduleid] as $row)
-	{
-		//if this is the element we want (be it a chapter or an item), get its data
-		if (($row['id'] == $id) && ($row['type'] == $type))
-		{
-			$orig_order = $row['display_order'];
-			$orig_type = $row['type'];
-			break;
-		}
-	}
-
-	$dest_order = 0;
-	$dest_type = '';
-	$dest_id = 0;
-	if ($direction == "up")
-	{
-		if (!empty ($tree[$moduleid][$orig_order -1]))
-		{
-			$dest_order = $orig_order -1;
-			$dest_type = $tree[$moduleid][$orig_order -1]['type'];
-			$dest_id = $tree[$moduleid][$orig_order -1]['id'];
-		}
-		else
-		{
-			return false;
-		}
-	}
-	else
-	{
-		//move down
-		if (!empty ($tree[$moduleid][$orig_order +1]))
-		{
-			$dest_order = $orig_order +1;
-			$dest_type = $tree[$moduleid][$orig_order +1]['type'];
-			$dest_id = $tree[$moduleid][$orig_order +1]['id'];
-		}
-		else
-		{
-			return false;
-		}
-	}
-
-	$sql1 = '';
-	$sql2 = '';
-	if ($orig_type == 'chapter')
-	{
-		$sql1 = "UPDATE $tbl_learnpath_chapter SET display_order = ".$dest_order." WHERE (id=$orig_id and parent_item_id=$moduleid)";
-	}
-	elseif ($orig_type == 'item')
-	{
-		$sql1 = "UPDATE $tbl_learnpath_item SET display_order = ".$dest_order." WHERE (id=$orig_id and parent_item_id=$moduleid)";
-	}
-	else
-	{
-		return false;
-	}
-
-	if ($dest_type == 'chapter')
-	{
-		$sql2 = "UPDATE $tbl_learnpath_chapter SET display_order = ".$orig_order." WHERE (id='$dest_id' and parent_item_id=$moduleid)";
-	}
-	elseif ($dest_type == 'item')
-	{
-		$sql2 = "UPDATE $tbl_learnpath_item SET display_order = ".$orig_order." WHERE (id='$dest_id' and parent_item_id=$moduleid)";
-	}
-	else
-	{
-		return false;
-	}
-	Database::query($sql1, __FILE__, __LINE__);
-	Database::query($sql2, __FILE__, __LINE__);
-}
-
-/**
- * This function moves a module (also called chapter or category).
- *
- * @param   string $direction: move the given chapter up or down
- * @param   integer $id: the id of the chapter we want to move
+ * @note    With this new version, the moveitem deals with items AND directories (not the base-level modules). This is a lot more complicated but is a temporary step towards new database structure as 'everything is an item'
+ **/
+function moveitem($direction, $id, $moduleid, $type = 'item')
+{
+	global $learnpath_id;
+	$tbl_learnpath_item     = Database::get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter  = Database::get_course_table(TABLE_LEARNPATH_CHAPTER);
+
+	$tree = get_learnpath_tree($learnpath_id);
+	$orig_order = 0;
+	$orig_type = '';
+	$orig_id = $id;
+	foreach ($tree[$moduleid] as $row)
+	{
+		//if this is the element we want (be it a chapter or an item), get its data
+		if (($row['id'] == $id) && ($row['type'] == $type))
+		{
+			$orig_order = $row['display_order'];
+			$orig_type = $row['type'];
+			break;
+		}
+	}
+
+	$dest_order = 0;
+	$dest_type = '';
+	$dest_id = 0;
+	if ($direction == "up")
+	{
+		if (!empty ($tree[$moduleid][$orig_order -1]))
+		{
+			$dest_order = $orig_order -1;
+			$dest_type = $tree[$moduleid][$orig_order -1]['type'];
+			$dest_id = $tree[$moduleid][$orig_order -1]['id'];
+		}
+		else
+		{
+			return false;
+		}
+	}
+	else
+	{
+		//move down
+		if (!empty ($tree[$moduleid][$orig_order +1]))
+		{
+			$dest_order = $orig_order +1;
+			$dest_type = $tree[$moduleid][$orig_order +1]['type'];
+			$dest_id = $tree[$moduleid][$orig_order +1]['id'];
+		}
+		else
+		{
+			return false;
+		}
+	}
+
+	$sql1 = '';
+	$sql2 = '';
+	if ($orig_type == 'chapter')
+	{
+		$sql1 = "UPDATE $tbl_learnpath_chapter SET display_order = ".$dest_order." WHERE (id=$orig_id and parent_item_id=$moduleid)";
+	}
+	elseif ($orig_type == 'item')
+	{
+		$sql1 = "UPDATE $tbl_learnpath_item SET display_order = ".$dest_order." WHERE (id=$orig_id and parent_item_id=$moduleid)";
+	}
+	else
+	{
+		return false;
+	}
+
+	if ($dest_type == 'chapter')
+	{
+		$sql2 = "UPDATE $tbl_learnpath_chapter SET display_order = ".$orig_order." WHERE (id='$dest_id' and parent_item_id=$moduleid)";
+	}
+	elseif ($dest_type == 'item')
+	{
+		$sql2 = "UPDATE $tbl_learnpath_item SET display_order = ".$orig_order." WHERE (id='$dest_id' and parent_item_id=$moduleid)";
+	}
+	else
+	{
+		return false;
+	}
+	Database::query($sql1, __FILE__, __LINE__);
+	Database::query($sql2, __FILE__, __LINE__);
+}
+
+/**
+ * This function moves a module (also called chapter or category).
+ *
+ * @param   string $direction: move the given chapter up or down
+ * @param   integer $id: the id of the chapter we want to move
  * @return	void
- **/
-function movemodule($direction, $id)
-{
-	global $learnpath_id;
-	$tbl_learnpath_chapter = Database :: get_course_learnpath_chapter_table();
-	if ($direction == "up")
-	{
-		$sortDirection = "DESC";
-	}
-	else
-	{
-		$sortDirection = "ASC";
-	}
-
-	// Select all chapters of first level (parent_item_id = 0)
-	$sql = "SELECT * FROM $tbl_learnpath_chapter where (lp_id=$learnpath_id AND parent_item_id = 0) ORDER BY display_order $sortDirection";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$previousrow = "";
-
-	// see similar comment in moveitem() function
-	// @TODO: this only works for chapters in multi-level mode. Why not gather
-	// this function and moveitem to keep only one multi-uses function?
-	while ($row = mysql_fetch_array($result))
-	{
-		// step 2: performing the move (only happens when passed trhough step 1 at least once)
-		if (!empty ($this_cat_order))
-		{
-			$next_cat_order = $row["display_order"];
-			$next_cat_id = $row["id"];
-
-			$sql1 = "UPDATE $tbl_learnpath_chapter SET display_order = '$next_cat_order' WHERE (id='$this_cat_id' and lp_id=$learnpath_id)";
-			$sql2 = "UPDATE $tbl_learnpath_chapter SET display_order = '$this_cat_order' WHERE (id='$next_cat_id' and lp_id=$learnpath_id)";
-			Database::query($sql1, __FILE__, __LINE__);
-			Database::query($sql2, __FILE__, __LINE__);
-			unset ($this_cat_order);
-			unset ($this_cat_id);
-			unset ($next_cat_order);
-			unset ($next_cat_id);
-			break;
-		}
-
-		// step 1: looking for the order of the row we want to move
-		if ($row["id"] == $id)
-		{
-			$this_cat_order = $row["display_order"];
-			$this_cat_id = $id;
-		}
-	}
-
-}
-
-/**
- * Inserts a new element in a learnpath table (item or chapter)
- * @param		string	Element type ('chapter' or 'item')
- * @param		string	Chapter name
- * @param		string	Chapter description (optional)
- * @param		integer	Parent chapter ID (default: 0)
+ **/
+function movemodule($direction, $id)
+{
+	global $learnpath_id;
+	$tbl_learnpath_chapter = Database :: get_course_learnpath_chapter_table();
+	if ($direction == "up")
+	{
+		$sortDirection = "DESC";
+	}
+	else
+	{
+		$sortDirection = "ASC";
+	}
+
+	// Select all chapters of first level (parent_item_id = 0)
+	$sql = "SELECT * FROM $tbl_learnpath_chapter where (lp_id=$learnpath_id AND parent_item_id = 0) ORDER BY display_order $sortDirection";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$previousrow = "";
+
+	// see similar comment in moveitem() function
+	// @TODO: this only works for chapters in multi-level mode. Why not gather
+	// this function and moveitem to keep only one multi-uses function?
+	while ($row = mysql_fetch_array($result))
+	{
+		// step 2: performing the move (only happens when passed trhough step 1 at least once)
+		if (!empty ($this_cat_order))
+		{
+			$next_cat_order = $row["display_order"];
+			$next_cat_id = $row["id"];
+
+			$sql1 = "UPDATE $tbl_learnpath_chapter SET display_order = '$next_cat_order' WHERE (id='$this_cat_id' and lp_id=$learnpath_id)";
+			$sql2 = "UPDATE $tbl_learnpath_chapter SET display_order = '$this_cat_order' WHERE (id='$next_cat_id' and lp_id=$learnpath_id)";
+			Database::query($sql1, __FILE__, __LINE__);
+			Database::query($sql2, __FILE__, __LINE__);
+			unset ($this_cat_order);
+			unset ($this_cat_id);
+			unset ($next_cat_order);
+			unset ($next_cat_id);
+			break;
+		}
+
+		// step 1: looking for the order of the row we want to move
+		if ($row["id"] == $id)
+		{
+			$this_cat_order = $row["display_order"];
+			$this_cat_id = $id;
+		}
+	}
+
+}
+
+/**
+ * Inserts a new element in a learnpath table (item or chapter)
+ * @param		string	Element type ('chapter' or 'item')
+ * @param		string	Chapter name
+ * @param		string	Chapter description (optional)
+ * @param		integer	Parent chapter ID (default: 0)
  * @param		integer Learnpath ID
- * @param		mixed		If type 'item', then array(prereq_id=>value, prereq_..)
+ * @param		mixed		If type 'item', then array(prereq_id=>value, prereq_..)
  * @return	integer	The new chapter ID, or false on failure
- * @TODO	Finish this function before it is used. Currently only chapters can be added using it.
- * @note This function is currently never used!
- */
-function insert_item($type = 'item', $name, $chapter_description = '', $parent_id = 0, $learnpath_id = 0, $params = null)
-{
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-
-	// getting the last order number from the chapters table, in this learnpath, for the parent chapter given
+ * @TODO	Finish this function before it is used. Currently only chapters can be added using it.
+ * @note This function is currently never used!
+ */
+function insert_item($type = 'item', $name, $chapter_description = '', $parent_id = 0, $learnpath_id = 0, $params = null)
+{
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+
+	// getting the last order number from the chapters table, in this learnpath, for the parent chapter given
 	$sql = "SELECT * FROM $tbl_learnpath_chapter
 			WHERE lp_id=$learnpath_id
-			AND parent_item_id = $parent_id
-			ORDER BY display_order DESC";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$row = mysql_fetch_array($result);
-	$last_chapter_order = $row["display_order"];
-
-	// getting the last order number of the items
+			AND parent_item_id = $parent_id
+			ORDER BY display_order DESC";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$row = mysql_fetch_array($result);
+	$last_chapter_order = $row["display_order"];
+
+	// getting the last order number of the items
 	$sql = "SELECT * FROM $tbl_learnpath_item
-			AND parent_item_id = $parent_id
-			ORDER BY display_order DESC";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$row = mysql_fetch_array($result);
-	$last_item_order = $row["display_order"];
-	$new_order = max($last_chapter_order, $last_item_order) + 1;
-
-	if ($type === 'chapter')
-	{
+			AND parent_item_id = $parent_id
+			ORDER BY display_order DESC";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$row = mysql_fetch_array($result);
+	$last_item_order = $row["display_order"];
+	$new_order = max($last_chapter_order, $last_item_order) + 1;
+
+	if ($type === 'chapter')
+	{
 		$sql = "INSERT INTO $tbl_learnpath_chapter
 						(lp_id, chapter_name, chapter_description, display_order)
 						VALUES ('".domesticate($learnpath_id)."',
-						'".domesticate(htmlspecialchars($chapter_name))."',
+						'".domesticate(htmlspecialchars($chapter_name))."',
 						'".domesticate(htmlspecialchars($chapter_description))."',
-						$new_order )";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		if ($result === false)
-		{
-			return false;
-		}
-		$id = Database :: get_last_insert_id();
-	}
-	elseif ($type === 'item')
-	{
+						$new_order )";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		if ($result === false)
+		{
+			return false;
+		}
+		$id = Database :: get_last_insert_id();
+	}
+	elseif ($type === 'item')
+	{
 		$sql = "INSERT INTO $tbl_learnpath_item
 						(parent_item_id, item_type, item_id, display_order)
 						VALUES ('".domesticate($parent_id)."',
-						'".domesticate(htmlspecialchars($item_type))."',
+						'".domesticate(htmlspecialchars($item_type))."',
 						'".domesticate(htmlspecialchars($item_id))."',
-						$new_order )";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		if ($result === false)
-		{
-			return false;
-		}
-		$id = Database :: get_last_insert_id();
-	}
-	return $id;
-}
-
-/**
- * This function returns an array with all the learnpath categories/chapters
- * @return array List of learnpath chapter titles
- **/
-function array_learnpath_categories()
-{
+						$new_order )";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		if ($result === false)
+		{
+			return false;
+		}
+		$id = Database :: get_last_insert_id();
+	}
+	return $id;
+}
+
+/**
+ * This function returns an array with all the learnpath categories/chapters
+ * @return array List of learnpath chapter titles
+ **/
+function array_learnpath_categories()
+{
 	#global $tbl_learnpath_chapter;
-	global $learnpath_id;
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-
-	$sql = "SELECT * FROM  $tbl_learnpath_chapter  WHERE (lp_id=$learnpath_id) ORDER BY display_order ASC";
-	$result = Database::query($sql, __FILE__, __LINE__);
-
-	while ($row = mysql_fetch_array($result))
-	{
-		$array_learnpath_categories[] = array ($row["id"], $row["chapter_name"]);
-	}
-	//$array_learnpath_categories=array($array_learnpath_categories_name,$array_learnpath_categories_id);
-	return $array_learnpath_categories;
-}
-
-/**
-* Displays the learnpath chapters(=modules,categories) and their contents.
-* @param    integer     Chapter ID to display now (enables recursive behaviour)
-* @param    array       The array as returned by get_learnpath_tree, with all the elements of a learnpath compiled and structured into the array, by chapter id
-* @param    integer     Level (the depth of the call - helps in display)
-* @todo eliminate all global $lang declarations, use get_lang, improve structure.
-* @author   Denes Nagy
-* @author   Roan Embrechts
-* @author   Yannick Warnier <yannick.warnier@dokeos.com> - complete redesign for multi-level learnpath chapters
-*/
-function display_learnpath_chapters($parent_item_id = 0, $tree = array (), $level = 0)
-{
-	//error_log('New LP - In learnpath_functions::display_learnpath_chapters',0);
-	global $color2;
-	global $xml_output;
-	global $learnpath_id;
-	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-
-
-	// @todo: coding standards: Language variables are CaMMelCaSe, all other variables should use the underscoring method.
-	$lang_move_down = get_lang('_move_down');
-	$lang_move_up = get_lang('lang_move_up');
-	$lang_edit_learnpath_module = get_lang('lang_edit_learnpath_module');
-	$lang_delete_learnpath_module = get_lang('lang_delete_learnpath_module');
-	$lang_nochapters = get_lang('lang_nochapters');
-	$lang_prerequisites = get_lang('lang_prerequisites');
-	$lang_prerequisites_limit = get_lang('lang_prerequisites_limit');
-	$lang_add_learnpath_item = get_lang('lang_add_learnpath_item');
-	$lang_add_item = get_lang('lang_add_item');
-	$lang_title_and_desc = get_lang('lang_title_and_desc');
-	$lang_change_order = get_lang('lang_change_order');
-	$lang_add_prereqi = get_lang('lang_add_prereqi');
-	$lang_add_title_and_desc = get_lang('lang_add_title_and_desc');
-	$lang_delete = get_lang('Delete');
-
-	if ($parent_item_id === 0)
-	{
-		// this is the first time we use the function, define the tree and display learnpath name
-
-		$tree = get_learnpath_tree($learnpath_id);
-
-		$num_modules = count($tree);
-		//$num_modules=mysql_num_rows($result);
-		if ($num_modules == 0)
-		{
-			// do not diplay useless information
-			//echo "<tr><td>&nbsp;$lang_nochapters</td></tr>";
-		}
-		else
-		{
-			echo "  <tr align='center' valign='top'>\n"."    <td><b>&nbsp;$lang_title_and_desc </b></td>\n"."    <td><b>&nbsp;$lang_add_item </b></td>\n";
-			if (is_prereq($learnpath_id))
-			{
-				echo "    <td bgcolor='#ddddee'><b>&nbsp;$lang_prerequisites_limit </b></td>\n";
-			}
-			else
-				echo "    <td><b>&nbsp;$lang_prerequisites </b></td>\n";
-
-			echo "    <td colspan='2'><b>&nbsp;$lang_change_order </b></td><td><b>&nbsp;$lang_add_prereqi </b></td>\n"."    <td><b>&nbsp;$lang_add_title_and_desc </b></td><td><b>&nbsp;$lang_delete </b></td>\n"."  </tr>\n";
-		}
-	}
-
-	$i = 1;
-	$counter = 0;
-	$num_modules = count($tree[$parent_item_id]);
-
-	//while ($row=mysql_fetch_array($result))
-	if (isset ($tree[$parent_item_id]))
-	{
-		foreach ($tree[$parent_item_id] as $row)
-		{
-			if ($row['item_type'] === 'dokeos_chapter')
-			{
-				$xml_output .= "<chapter>";
-				$xml_output .= "<chaptertitle>".$row["title"]."</chaptertitle>";
-				$xml_output .= "<chapterdescription>".$row["description"]."</chapterdescription>";
-
-				$counter ++;
-				if (($counter % 2) == 0)
-				{
-					$oddclass = "row_odd";
-				}
-				else
-				{
-					$oddclass = "row_even";
-				}
-
-				//echo '<tr class="'.$oddclass.'">'."\n".'  <td>'.str_repeat("&nbsp;&gt;", $level)."<img src='../img/documents.gif' alt='folder'/><a href='".api_get_self()."?lp_id=$learnpath_id&item_id={$row['id']}&action=add&type=learnpathitem&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9'><b>&nbsp;".$row['title']."</b></a>"."<br /><i><div align='justify'>&nbsp;".str_repeat("&nbsp;&nbsp;&nbsp;", $level)."</i></td>\n".'  <td  align="center"><a href="'.api_get_self()."?lp_id=$learnpath_id&item_id={$row['id']}&action=add&type=learnpathitem&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9"><img src='../img/0.gif' width='13' height='13' border='0' title='$lang_add_learnpath_item'></a></td>\n"."  <td";
-				echo '<tr class="'.$oddclass.'">'."\n".'  <td>'.str_repeat("&nbsp;&gt;", $level)."<img src='../img/documents.gif' alt='folder'/><a href='".api_get_self()."?lp_id=$learnpath_id&parent_item_id=".$row['id']."&action=add_sub_item'><b>&nbsp;".$row['title']."</b></a>"."<br /><i><div align='justify'>&nbsp;".str_repeat("&nbsp;&nbsp;&nbsp;", $level)."</i></td>\n".'  <td  align="center"><a href="'.api_get_self()."?lp_id=$learnpath_id&parent_item_id=".$row['id']."&action=add_sub_item\"><img src='../img/0.gif' width='13' height='13' border='0' title='$lang_add_learnpath_item'></a></td>\n"."  <td";
-				if (is_prereq($learnpath_id))
-				{
-					echo " bgcolor='#ddddee'";
-				}
-				echo ">".$row['prerequisite']."</td>\n";
-
-				// showing the edit, delete and move icons
-				if (is_allowed_to_edit())
-				{
-					$myaction = 'move_item';
-					if ($i < $num_modules)
-					{
-
-						// if we are still under the number of chapters in this section, show "move down"
-						//echo "  <td align=center>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=".$myaction."&amp;direction=down&amp;moduleid=".$parent_item_id."&amp;id=".$row["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/down.gif\" border=\"0\" title=\"$lang_move_down\">"."</a></td>\n";
-						echo "  <td align=center>"."<a href='".api_get_self()."?lp_id=$learnpath_id&action=".$myaction."&direction=down&moduleid=".$parent_item_id."&id=".$row["id"]."'>"."<img src=\"../img/down.gif\" border=\"0\" title=\"$lang_move_down\">"."</a></td>\n";
-					}
-					else
-					{
-						echo '  <td align="center">&nbsp;</td>'."\n";
-					}
-
-					if ($i > 1)
-					{
-						//echo '  <td align="center">'."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=".$myaction."&amp;direction=up&amp;moduleid=".$parent_item_id."&amp;id=".$row["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/up.gif\" border=\"0\" title=\"$lang_move_up\">"."</a>"."</td>\n";
-						echo '  <td align="center">'."<a href='".api_get_self()."?lp_id=$learnpath_id&action=".$myaction."&direction=up&moduleid=".$parent_item_id."&id=".$row["id"]."'>"."<img src=\"../img/up.gif\" border=\"0\" title=\"$lang_move_up\">"."</a>"."</td>\n";
-					}
-					else
-					{
-						echo '  <td align="center">&nbsp;</td>'."\n";
-					}
-
-					echo "  <td align='center'>&nbsp;</td>\n";
-					//echo "  <td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=editmodule&amp;id=".$row["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath_module\">"."</a>"."</td>\n";
-					echo "  <td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&action=edititem&id=".$row["id"]."'>"."<img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath_module\">"."</a>"."</td>\n";
-
-					//echo "  <td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=deletemodule&amp;id=".$row["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9 onclick=\"return confirmation('".$row['chapter_name']."');\">"."<img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath_module\">"."</a>"."</td>\n";
-					echo "  <td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&action=delete_item&id=".$row["id"]."' onclick=\"return confirmation('".$row['title']."');\">"."<img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath_module\">"."</a>"."</td>\n";
-				}
-
-				echo "</tr>\n";
-				$i ++;
-
-				$xml_output .= "<items>";
-
-				#display_learnpath_items($row["id"]);
-				display_learnpath_chapters($row['id'], $tree, $level +1);
-
-				$xml_output .= "</items>";
-				$xml_output .= "</chapter>";
-
-			}
-			else //if //($row['item_type'] === 'item')
-			{
-				$row_items = $row;
-				echo "<tr>\n  <td colspan='2' valign='top'>";
-				//require('resourcelinker.inc.php');
-				display_addedresource_link_in_learnpath($row_items["item_type"], $row_items["ref"], '', $row_items["id"], 'builder', 'icon', $level);
-
-				if ($row_items["description"])
-				{
-					echo "<div align='justify'>&nbsp;&nbsp;&nbsp;{$row_items['description']}";
-				}
-
-				echo "</td>";
-
-				if (is_prereq($learnpath_id))
-				{
-					echo '<td bgcolor="#EEEEFF">';
-				}
-				else
-				{
-					echo "<td>";
-				}
-
-				if (is_allowed_to_edit())
-				{
-
-					if ($row_items["prerequisite"] <> '')
-					{
-						$prereq = $row_items["prerequisite"];
-
-						//if ($row_items["prereq_type"] == 'i')
-						//{
-							//item
-							$sql_items2 = "SELECT * FROM $tbl_lp_item WHERE id='$prereq'"; //check if prereq has been deleted
-							$result_items2 = Database::query($sql_items2, __FILE__, __LINE__);
-							$number_items2 = Database::num_rows($result_items2);
-							if ($number_items2 == 0)
-							{
-								echo get_lang('prereq_deleted_error');
-							}
-							$row_items2 = mysql_fetch_array($result_items2);
-							display_addedresource_link_in_learnpath($row_items2["item_type"], $row_items2["ref"], '', $row_items2["id"], 'builder', '', 0);
-							if ((($row_items2["item_type"] == TOOL_QUIZ) or ($row_items2["item_type"] == 'HotPotatoes')) and ($row_items['prerequisite']))
-							{
-								//echo "&nbsp;({$row_items2['title']})";
-							}
-						//}
-						/*
-						if ($row_items["prereq_type"] == 'c')
-						{
-							//chapter
-							$sql_items2 = "SELECT * FROM $tbl_lp_item WHERE id='$prereq' AND item_type='dokeos_chapter'"; //check if prereq has been deleted
-							$result_items2 = Database::query($sql_items2, __FILE__, __LINE__);
-							$number_items2 = Database::num_rows($result_items2);
-							if ($number_items2 == 0)
-							{
-								echo "<font color='red'>$lang_prereq_deleted_error</font>";
-							}
-							$row_items2 = mysql_fetch_array($result_items2);
-							echo " {$row_items2['title']}";
-						}*/
-					}
-					echo "</font></td>";
-					$xml_output .= "<element_type>".$row_items["item_type"]."</element_type>";
-					$xml_output .= "<element_id>".$row_items["item_id"]."</element_id>";
-
-					// move
-					if ($i < $num_modules)
-					{
-						echo "<td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=moveitem&amp;type=item&amp;direction=down&amp;moduleid=".$parent_item_id."&amp;id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/down.gif\" border=\"0\" title=\"$lang_move_down\">"."</a>"."</td>";
-					}
-					else
-					{
-						echo "<td width='30' align='center'>&nbsp;</td>";
-					}
-
-					if ($i > 1)
-					{
-						echo "<td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=moveitem&amp;type=item&amp;direction=up&amp;moduleid=".$parent_item_id."&amp;id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/up.gif\" border=\"0\" title=\"$lang_move_up\">"."</a>";
-					}
-					else
-					{
-						echo "<td width='30' align='center'>&nbsp;</td>";
-					}
-					echo "</td>"."<td align='center'>";
-
-					// edit prereq
-					echo "<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=edititemprereq&amp;id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/scormpre.gif\" border=\"0\" title=\"$lang_add_prereq\">"."</a>"."</td>";
-
-					// edit
-					echo "<td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=edititem&amp;id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath_item\">"."</a>"."</td>";
-
-					// delete
-					echo "<td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&action=deleteitem&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath_item\" onclick=\"return confirmation('".$row_items["item_type"]."');\">"."</a>";
-				}
-				$i ++;
-				echo "</td></tr>";
-
-			}
-		}
-	}
-}
-
-/**
- * Displays all learning paths.
- * @return	void
- * @todo eliminate all global $lang declarations, use get_lang, improve structure.
- */
-function display_all_learnpath()
-{
-	global $tbl_tool, $color2;
-	global $xml_output, $lang_edit_learnpath, $lang_delete_learnpath, $lang_publish, $lang_no_publish, $lang_add_learnpath_chapter_to_path;
-	$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
-
-	$sql = "SELECT * FROM  $tbl_learnpath_main  ORDER BY learnpath_name";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$i = 1;
-	$num_modules = mysql_num_rows($result);
-
-	while ($row = mysql_fetch_array($result))
-	{
-		//other grey color : #E6E6E6
-		echo "<tr><td bgcolor=\"$color2\" width=400><b>&nbsp;";
-		echo "<a href='learnpath_handler.php?&lp_id={$row['lp_id']}'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>{$row['learnpath_name']}</a>";
-		echo "</b><br><i><div class=text align=justify>{$row['learnpath_description']}</div></i></td>";
-
-		// showing the edit, delete and publish icons
-		if (is_allowed_to_edit())
-		{
-			echo "<td bgcolor=\"$color2\" align=center><a href='learnpath_handler.php?lp_id={$row['lp_id']}&action=add&type=learnpathcategory'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src='../img/0.gif' width='13' height='13' border='0' title='$lang_add_learnpath_chapter_to_path'></a></td>";
-			echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=editpath&id=".$row["lp_id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath\"></a></td>";
-			echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=deletepath&id=".$row["lp_id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath\" onclick=\"return confirmation('".$row2['learnpath_name']."');\"></a></td>";
-			$id = $row["lp_id"];
-			$sql2 = "SELECT * FROM $tbl_learnpath_main where lp_id=$id";
-			$result2 = Database::query($sql2, __FILE__, __LINE__);
-			$row2 = mysql_fetch_array($result2);
-			$name = $row2['learnpath_name'];
-			$sql3 = "SELECT * FROM $tbl_tool where (name=\"$name\" and image='scormbuilder.gif')";
-			$result3 = Database::query($sql3, __FILE__, __LINE__);
-			$row3 = mysql_fetch_array($result3);
-			if (($row3["visibility"]) == '1')
-			{
-				echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=publishpath&set=i&id=".$row["lp_id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/visible.gif\" border=\"0\" title=\"$lang_no_publish\"></a></td>";
-			}
-			else
-			{
-				echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=publishpath&set=v&id=".$row["lp_id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/invisible.gif\" border=\"0\" title=\"$lang_publish\"></a></td>";
-			}
-		}
-		$i ++;
-		echo "<tr><td>&nbsp;</td></tr>";
-	}
-}
-
-/**
- * Displays the learning path items/steps.
- * @param		integer		Category ID
- * @return	void
- * @todo eliminate all global $lang declarations, use get_lang, improve structure.
- */
-function display_learnpath_items($categoryid)
-{
-	global $xml_output;
-	global $lang_prerequisites, $lang_move_down, $lang_move_up, $lang_edit_learnpath_item, $lang_delete_learnpath_item, $learnpath_id, $lang_add_prereq, $lang_prereq_deleted_error, $lang_pre_short, $langThisItem;
-	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-
-	$sql_items = "SELECT * FROM $tbl_lp_item WHERE parent_item_id='$categoryid' ORDER BY display_order ASC";
-	$result_items = Database::query($sql_items,__FILE__,__LINE__);
-	$number_items = Database::num_rows($result_items);
-	$i = 1;
-	error_log('Selected item under '.$categoryid,0);
-
-	while ($row_items = Database::fetch_array($result_items))
-	{
-		echo "<tr><td colspan='2' valign='top'>";
-		display_addedresource_link_in_learnpath($row_items["item_type"], $row_items["ref"], '', $row_items["id"], 'builder', 'icon');
-		if ($row_items["description"])
-		{
-			echo "<div align='justify'><font color='#999999'>&nbsp;&nbsp;&nbsp;{$row_items['description']}</font>";
-		}
-		echo "</td>";
-		if (is_prereq($learnpath_id))
-		{
-			echo '<td bgcolor="#EEEEFF">';
-		}
-		else
-		{
-			echo "<td>";
-		}
-
-		if (is_allowed_to_edit())
-		{
-			error_log('Is allowed to edit item'.$row_items['id'],0);
-			//TODO: fix by adding true prerequisites parsing (and cycle through)
-			//Over simplification here, we transform prereq_id field into prerequisite field
-			if ($row_items["prerequisite"] <> '')
-			{
-				$prereq = $row_items["prerequisite"];
-
-				//if ($row_items["prereq_type"] == 'i')
-				//{
-					//item
-					$sql_items2 = "SELECT * FROM $tbl_lp_item WHERE id='$prereq'"; //check if prereq has been deleted
-					$result_items2 = Database::query($sql_items2);
-					$number_items2 = Database::num_rows($result_items2);
-					if ($number_items2 == 0)
-					{
-						echo "<font color=red>$lang_prereq_deleted_error</font>";
-					}
-					$row_items2 = Database::fetch_array($result_items2);
-					display_addedresource_link_in_learnpath($row_items2["item_type"], $row_items2["ref"], '', $row_items2["id"], 'builder', '');
-					if ((($row_items2["item_type"] == 'Exercise') or ($row_items2["item_type"] == 'HotPotatoes')) and ($row_items['prerequisites']))
-					{
-						echo "&nbsp;({$row_items2['title']})";
-					}
-				//}
-				/*if ($row_items["prereq_type"] == 'c')
-				{
-					//chapter
-					$sql_items2 = "SELECT * FROM $tbl_learnpath_chapter WHERE id='$prereq'"; //check if prereq has been deleted
-					$result_items2 = Database::query($sql_items2,__FILE__,__LINE__);
-					$number_items2 = Database::num_rows($result_items2);
-					if ($number_items2 == 0)
-					{
-						echo "<font color=red>$lang_prereq_deleted_error</font>";
-					}
-					$row_items2 = Database::fetch_array($result_items2);
-					echo " {$row_items2['chapter_name']}";
-				}*/
-			}
-			echo "</font></td>";
-			$xml_output .= "<element_type>".$row_items["item_type"]."</element_type>";
-			$xml_output .= "<element_id>".$row_items["id"]."</element_id>";
-
-			// move
-			if ($i < $number_items)
-			{
-				echo "<td align='center'><a href='".api_get_self()."?lp_id=$learnpath_id&action=moveitem&direction=down&moduleid=".$categoryid."&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/down.gif\" border=\"0\" title=\"$lang_move_down\"></a></td>";
-			}
-			else
-			{
-				echo "<td width='30' align='center'>&nbsp;</td>";
-			}
-
-			if ($i > 1)
-			{
-				echo "<td align='center'><a href='".api_get_self()."?lp_id=$learnpath_id&action=moveitem&direction=up&moduleid=".$categoryid."&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/up.gif\" border=\"0\" title=\"$lang_move_up\"></a>";
-			}
-			else
-			{
-				echo "<td width='30' align='center'>&nbsp;</td>";
-			}
-			echo "</td><td align='center'>";
-
-			// edit prereq
-			echo "<a href='".api_get_self()."?lp_id=$learnpath_id&action=edititemprereq&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/scormpre.gif\" border=\"0\" title=\"$lang_add_prereq\"></a></td>";
-
-			// edit
-			echo "<td align='center'><a href='".api_get_self()."?lp_id=$learnpath_id&action=edititem&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath_item\"></a></td>";
-
-			// delete
-			echo "<td align='center'>";
-			echo "<a href='".api_get_self()."?lp_id=$learnpath_id&action=deleteitem&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath_item\" onclick=\"return confirmation('".$langThisItem."');\"></a>";
-		}
-		$i ++;
-		echo "</td></tr>";
-	}
-}
-
-/**
- * This function returns the items belonging to the chapter that contains the given item (brother items)
- * @param	integer	Item id
- * @return	array		Table containing the items
- */
-function learnpath_items($itemid)
-{
-	global $xml_output;
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-
-	$sql_items = "SELECT parent_item_id FROM $tbl_lp_item WHERE id='$itemid'";
-	$moduleid_sql = Database::query($sql_items);
-	$moduleid_array = mysql_fetch_array($moduleid_sql); //first row of the results
-	$moduleid = $moduleid_array["parent_item_id"];
-
-	$sql_items = "SELECT * FROM $tbl_lp_item WHERE parent_item_id='$moduleid' ORDER BY display_order ASC";
-	$result_items = Database::query($sql_items);
-	$ar = mysql_fetch_array($result_items);
-	while ($ar != '')
-	{
-		$result[] = $ar;
-		$ar = mysql_fetch_array($result_items);
-	}
-	return $result;
-
-}
-
-/**
- * This function returns the chapters belonging to the path that contais the given chapter (brother chapters)
- * @param	integer	Learnpath id
- * @return array		Table containing the chapters
- */
-function learnpath_chapters($learnpath_id)
-{
-	global $xml_output, $learnpath_id;
-	//$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-
-
-	$sql_items = "SELECT * FROM $tbl_lp_item WHERE lp_id='$learnpath_id' AND item_type='dokeos_chapter' ORDER BY display_order ASC";
-	//$sql_items = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id='$learnpath_id' ORDER BY display_order ASC";
-	$result_items = Database::query($sql_items, __FILE__, __LINE__);
-	$ar = mysql_fetch_array($result_items);
-	while ($ar != '')
-	{
-		$result[] = $ar;
-		$ar = mysql_fetch_array($result_items);
-	}
-	return $result;
-
-}
-
-/**
- * This function tells if a learnpath contains items which are prerequisite to other items
- * @param	integer	Learnpath id
- * @return	boolean	True if this learnpath contains an item which is a prerequisite to something
- */
-function is_prereq($learnpath_id)
-{
-	global $xml_output;
-	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-
-	$prereq = false;
-
-	$sql_items = "SELECT * FROM $tbl_lp_item WHERE lp_id='$learnpath_id' AND parent_item_id=0 ORDER BY display_order ASC";
-	$result_items = Database::query($sql_items,__FILE__,__LINE__);
-	while ($ar = Database::fetch_array($result_items))
-	{
-		$c = $ar['id'];
-		$sql_items2 = "SELECT * FROM $tbl_lp_item WHERE lp_id = $learnpath_id AND parent_item_id='$c' ORDER BY display_order ASC";
-		$result_items2 = Database::query($sql_items2,__FILE__,__LINE__);
-		while ($ar2 = Database::fetch_array($result_items2))
-		{
-			if ($ar2['prerequisite'] != '')
-			{
-				$prereq = true;
-			}
-		}
-	}
-	return ($prereq);
-}
-
-/**
- * This function returns the prerequisite sentence
- * @param	integer	Item ID
- * @return	string 	Prerequisite warning text
- */
-function prereqcheck($id_in_path)
-{
-	//1 Initialise and import working vars
-	global $learnpath_id, $_user;
-	global $langPrereqToEnter, $langPrereqTestLimit1, $langPrereqTestLimit2, $langPrereqTestLimitNow, $langPrereqFirstNeedTo, $langPrereqModuleMinimum1, $langPrereqModuleMinimum2;
-	$tbl_learnpath_user = Database :: get_course_table(TABLE_LEARNPATH_USER);
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-
-	//2 Initialise return value
-	$prereq = false;
-
-	//3 Get item data from the database
-	$sql_items = "SELECT * FROM $tbl_learnpath_item WHERE id='$id_in_path'";
-	$result_items = Database::query($sql_items);
-	$row = mysql_fetch_array($result_items);
-	//4 Check prerequisite's type
-	if ($row['prereq_type'] == 'i')
-	{
-		//4.a If prerequisite is of type 'i' (item)
-		//4.a.1 Get data ready for use
-		$id_in_path3 = $row['prereq_id'];
-		$prereq_limit = $row['prereq_completion_limit'];
-
-		//4.a.2 Get data from the user-item relation
-		if ($_user['user_id'] == '')
-		{
-			$user_id = '0';
-		}
-		else
-		{
-			$user_id = $_user['user_id'];
-		}
-		$sql_items3 = "SELECT * FROM $tbl_learnpath_user WHERE (learnpath_item_id='$id_in_path3' and user_id=$user_id)";
-		$result_items3 = Database::query($sql_items3);
-		$row3 = mysql_fetch_array($result_items3);
-
-		//4.a.3 Get the link that needs to be shown for the current item (not the prereq)
-		$stepname = display_addedresource_link_in_learnpath($row['item_type'], $row['ref'], '', $id_in_path, 'builder', 'nolink');
-		//this is the step we want to open
-		$stepname = trim($stepname); //to remove occasional line breaks and white spaces
-
-		//4.a.4 Get the prerequisite item
-		$sql6 = "SELECT * FROM $tbl_learnpath_item WHERE (id='$id_in_path3')";
-		$result6 = Database::query($sql6);
-		$row6 = mysql_fetch_array($result6);
-		//4.a.5 Get a link to the prerequisite item
-		$prereqname = display_addedresource_link_in_learnpath($row6['item_type'], $row6['ref'], '', $id_in_path3, 'builder', 'nolink'); //this is the prereq of the step we want to open
-
-		//4.a.5 Initialise limit value
-		$limitok = true;
-		//4.a.6 Get prerequisite limit
-		if ($prereq_limit)
-		{
-			//4.a.6.a If the completion limit exists
-			if ($row3['score'] < $prereq_limit)
-			{
-				//4.a.6.a.a If the completion limit hasn't been reached, then display the corresponding message
-				$prereq = $langPrereqToEnter.$stepname.$langPrereqTestLimit1."$prereq_limit".$langPrereqTestLimit2.$prereqname.". (".$langPrereqTestLimitNow.$row3['score'].")";
-			}
-			else
-			{
-				//4.a.6.a.b The completion limit has been reached. Prepare to return false (no prereq hanging)
-				$prereq = false;
-			}
-		}
-		else
-		{
-			//4.a.6.b If the completion limit doesn't exist
-			if ($row3['status'] == "completed" or $row3['status'] == 'passed')
-			{
-				//4.a.6.b.a If the prerequisite status is 'completed'
-				$prereq = false;
-			}
-			else
-			{
-				//4.a.6.b.b The prerequisite status is not 'completed', return corresponding message
-				$prereq = $langPrereqToEnter.$stepname.$langPrereqFirstNeedTo.$prereqname.'.';
-			}
-		}
-
-	}
-	elseif ($row['prereq_type'] == 'c')
-	{
-		//4.b If prerequisite is of type 'c' (chapter)
-		//4.b.1 Get data ready to use
-		$id_in_path2 = $row['prereq_id'];
-		//4.b.2 Get all items in the prerequisite chapter
-		$sql_items3 = "SELECT * FROM $tbl_lp_item WHERE parent_item_id='$id_in_path2'";
-		$result_items3 = Database::query($sql_items3);
-		$allcompleted = true;
-		while ($row3 = mysql_fetch_array($result_items3))
-		{
-			//4.b.3 Cycle through items in the prerequisite chapter
-			//4.b.3.1 Get data ready to use
-			$id_in_path4 = $row3['id'];
-			if ($_user['user_id'] == '')
-			{
-				$user_id = '0';
-			}
-			else
-			{
-				$user_id = $_user['user_id'];
-			}
-			//4.b.3.2 Get user-item relation
-			$sql_items4 = "SELECT * FROM $tbl_learnpath_user WHERE (learnpath_item_id='$id_in_path4' and user_id=$user_id)";
-			$result_items4 = Database::query($sql_items4);
-			$row4 = mysql_fetch_array($result_items4);
-			//4.b.3.3 If any of these elements is not 'completed', the overall completion status is false
-			if ($row4['status'] != "completed" and $row4['status'] != 'passed')
-			{
-				$allcompleted = false;
-			}
-		}
-		if ($allcompleted)
-		{
-			//4.b.4.a All items were completed, prepare to return that there is no prerequisite blocking the way
-			$prereq = false;
-		}
-		else
-		{
-			//4.b.4.b Something was not completed. Return corresponding message
-			$sql5 = "SELECT * FROM $tbl_learnpath_chapter WHERE (lp_id='$learnpath_id' and id='$id_in_path2')";
-			$result5 = Database::query($sql5);
-			$row5 = mysql_fetch_array($result5);
-			$prereqmodulename = trim($row5['chapter_name']);
-			$prereq = $langPrereqModuleMinimum1.$prereqmodulename.$langPrereqModuleMinimum2;
-		}
-	}
-	else
-	{
-		//5 If prerequisite type undefined, no prereq
-		$prereq = false;
-	}
-	//6 Return the message (or false if no prerequisite waiting)
-	return ($prereq);
-}
-
-/**
- * Constructs the tree that will be used to build the learnpath structure
- * @params  integer     Learnpath_id
- * @return  array       Tree of the learnpath structure
- * @author  Yannick Warnier <yannick.warnier@dokeos.com>
- * @comment This is a temporary function, which exists while the chapters and items
- *          are still in separate tables in the database. This function gathers the data in a unique tree.
- **/
-function get_learnpath_tree($learnpath_id)
-{
-	//error_log('New LP - In learnpath_functions::get_learnpath_tree',0);
-	//init elems
+	global $learnpath_id;
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+
+	$sql = "SELECT * FROM  $tbl_learnpath_chapter  WHERE (lp_id=$learnpath_id) ORDER BY display_order ASC";
+	$result = Database::query($sql, __FILE__, __LINE__);
+
+	while ($row = mysql_fetch_array($result))
+	{
+		$array_learnpath_categories[] = array ($row["id"], $row["chapter_name"]);
+	}
+	//$array_learnpath_categories=array($array_learnpath_categories_name,$array_learnpath_categories_id);
+	return $array_learnpath_categories;
+}
+
+/**
+* Displays the learnpath chapters(=modules,categories) and their contents.
+* @param    integer     Chapter ID to display now (enables recursive behaviour)
+* @param    array       The array as returned by get_learnpath_tree, with all the elements of a learnpath compiled and structured into the array, by chapter id
+* @param    integer     Level (the depth of the call - helps in display)
+* @todo eliminate all global $lang declarations, use get_lang, improve structure.
+* @author   Denes Nagy
+* @author   Roan Embrechts
+* @author   Yannick Warnier <yannick.warnier@dokeos.com> - complete redesign for multi-level learnpath chapters
+*/
+function display_learnpath_chapters($parent_item_id = 0, $tree = array (), $level = 0)
+{
+	//error_log('New LP - In learnpath_functions::display_learnpath_chapters',0);
+	global $color2;
+	global $xml_output;
+	global $learnpath_id;
+	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+
+
+	// @todo: coding standards: Language variables are CaMMelCaSe, all other variables should use the underscoring method.
+	$lang_move_down = get_lang('_move_down');
+	$lang_move_up = get_lang('lang_move_up');
+	$lang_edit_learnpath_module = get_lang('lang_edit_learnpath_module');
+	$lang_delete_learnpath_module = get_lang('lang_delete_learnpath_module');
+	$lang_nochapters = get_lang('lang_nochapters');
+	$lang_prerequisites = get_lang('lang_prerequisites');
+	$lang_prerequisites_limit = get_lang('lang_prerequisites_limit');
+	$lang_add_learnpath_item = get_lang('lang_add_learnpath_item');
+	$lang_add_item = get_lang('lang_add_item');
+	$lang_title_and_desc = get_lang('lang_title_and_desc');
+	$lang_change_order = get_lang('lang_change_order');
+	$lang_add_prereqi = get_lang('lang_add_prereqi');
+	$lang_add_title_and_desc = get_lang('lang_add_title_and_desc');
+	$lang_delete = get_lang('Delete');
+
+	if ($parent_item_id === 0)
+	{
+		// this is the first time we use the function, define the tree and display learnpath name
+
+		$tree = get_learnpath_tree($learnpath_id);
+
+		$num_modules = count($tree);
+		//$num_modules=mysql_num_rows($result);
+		if ($num_modules == 0)
+		{
+			// do not diplay useless information
+			//echo "<tr><td>&nbsp;$lang_nochapters</td></tr>";
+		}
+		else
+		{
+			echo "  <tr align='center' valign='top'>\n"."    <td><b>&nbsp;$lang_title_and_desc </b></td>\n"."    <td><b>&nbsp;$lang_add_item </b></td>\n";
+			if (is_prereq($learnpath_id))
+			{
+				echo "    <td bgcolor='#ddddee'><b>&nbsp;$lang_prerequisites_limit </b></td>\n";
+			}
+			else
+				echo "    <td><b>&nbsp;$lang_prerequisites </b></td>\n";
+
+			echo "    <td colspan='2'><b>&nbsp;$lang_change_order </b></td><td><b>&nbsp;$lang_add_prereqi </b></td>\n"."    <td><b>&nbsp;$lang_add_title_and_desc </b></td><td><b>&nbsp;$lang_delete </b></td>\n"."  </tr>\n";
+		}
+	}
+
+	$i = 1;
+	$counter = 0;
+	$num_modules = count($tree[$parent_item_id]);
+
+	//while ($row=mysql_fetch_array($result))
+	if (isset ($tree[$parent_item_id]))
+	{
+		foreach ($tree[$parent_item_id] as $row)
+		{
+			if ($row['item_type'] === 'dokeos_chapter')
+			{
+				$xml_output .= "<chapter>";
+				$xml_output .= "<chaptertitle>".$row["title"]."</chaptertitle>";
+				$xml_output .= "<chapterdescription>".$row["description"]."</chapterdescription>";
+
+				$counter ++;
+				if (($counter % 2) == 0)
+				{
+					$oddclass = "row_odd";
+				}
+				else
+				{
+					$oddclass = "row_even";
+				}
+
+				//echo '<tr class="'.$oddclass.'">'."\n".'  <td>'.str_repeat("&nbsp;&gt;", $level)."<img src='../img/documents.gif' alt='folder'/><a href='".api_get_self()."?lp_id=$learnpath_id&item_id={$row['id']}&action=add&type=learnpathitem&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9'><b>&nbsp;".$row['title']."</b></a>"."<br /><i><div align='justify'>&nbsp;".str_repeat("&nbsp;&nbsp;&nbsp;", $level)."</i></td>\n".'  <td  align="center"><a href="'.api_get_self()."?lp_id=$learnpath_id&item_id={$row['id']}&action=add&type=learnpathitem&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9"><img src='../img/0.gif' width='13' height='13' border='0' title='$lang_add_learnpath_item'></a></td>\n"."  <td";
+				echo '<tr class="'.$oddclass.'">'."\n".'  <td>'.str_repeat("&nbsp;&gt;", $level)."<img src='../img/documents.gif' alt='folder'/><a href='".api_get_self()."?lp_id=$learnpath_id&parent_item_id=".$row['id']."&action=add_sub_item'><b>&nbsp;".$row['title']."</b></a>"."<br /><i><div align='justify'>&nbsp;".str_repeat("&nbsp;&nbsp;&nbsp;", $level)."</i></td>\n".'  <td  align="center"><a href="'.api_get_self()."?lp_id=$learnpath_id&parent_item_id=".$row['id']."&action=add_sub_item\"><img src='../img/0.gif' width='13' height='13' border='0' title='$lang_add_learnpath_item'></a></td>\n"."  <td";
+				if (is_prereq($learnpath_id))
+				{
+					echo " bgcolor='#ddddee'";
+				}
+				echo ">".$row['prerequisite']."</td>\n";
+
+				// showing the edit, delete and move icons
+				if (is_allowed_to_edit())
+				{
+					$myaction = 'move_item';
+					if ($i < $num_modules)
+					{
+
+						// if we are still under the number of chapters in this section, show "move down"
+						//echo "  <td align=center>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=".$myaction."&amp;direction=down&amp;moduleid=".$parent_item_id."&amp;id=".$row["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/down.gif\" border=\"0\" title=\"$lang_move_down\">"."</a></td>\n";
+						echo "  <td align=center>"."<a href='".api_get_self()."?lp_id=$learnpath_id&action=".$myaction."&direction=down&moduleid=".$parent_item_id."&id=".$row["id"]."'>"."<img src=\"../img/down.gif\" border=\"0\" title=\"$lang_move_down\">"."</a></td>\n";
+					}
+					else
+					{
+						echo '  <td align="center">&nbsp;</td>'."\n";
+					}
+
+					if ($i > 1)
+					{
+						//echo '  <td align="center">'."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=".$myaction."&amp;direction=up&amp;moduleid=".$parent_item_id."&amp;id=".$row["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/up.gif\" border=\"0\" title=\"$lang_move_up\">"."</a>"."</td>\n";
+						echo '  <td align="center">'."<a href='".api_get_self()."?lp_id=$learnpath_id&action=".$myaction."&direction=up&moduleid=".$parent_item_id."&id=".$row["id"]."'>"."<img src=\"../img/up.gif\" border=\"0\" title=\"$lang_move_up\">"."</a>"."</td>\n";
+					}
+					else
+					{
+						echo '  <td align="center">&nbsp;</td>'."\n";
+					}
+
+					echo "  <td align='center'>&nbsp;</td>\n";
+					//echo "  <td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=editmodule&amp;id=".$row["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath_module\">"."</a>"."</td>\n";
+					echo "  <td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&action=edititem&id=".$row["id"]."'>"."<img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath_module\">"."</a>"."</td>\n";
+
+					//echo "  <td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=deletemodule&amp;id=".$row["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9 onclick=\"return confirmation('".$row['chapter_name']."');\">"."<img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath_module\">"."</a>"."</td>\n";
+					echo "  <td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&action=delete_item&id=".$row["id"]."' onclick=\"return confirmation('".$row['title']."');\">"."<img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath_module\">"."</a>"."</td>\n";
+				}
+
+				echo "</tr>\n";
+				$i ++;
+
+				$xml_output .= "<items>";
+
+				#display_learnpath_items($row["id"]);
+				display_learnpath_chapters($row['id'], $tree, $level +1);
+
+				$xml_output .= "</items>";
+				$xml_output .= "</chapter>";
+
+			}
+			else //if //($row['item_type'] === 'item')
+			{
+				$row_items = $row;
+				echo "<tr>\n  <td colspan='2' valign='top'>";
+				//require('resourcelinker.inc.php');
+				display_addedresource_link_in_learnpath($row_items["item_type"], $row_items["ref"], '', $row_items["id"], 'builder', 'icon', $level);
+
+				if ($row_items["description"])
+				{
+					echo "<div align='justify'>&nbsp;&nbsp;&nbsp;{$row_items['description']}";
+				}
+
+				echo "</td>";
+
+				if (is_prereq($learnpath_id))
+				{
+					echo '<td bgcolor="#EEEEFF">';
+				}
+				else
+				{
+					echo "<td>";
+				}
+
+				if (is_allowed_to_edit())
+				{
+
+					if ($row_items["prerequisite"] <> '')
+					{
+						$prereq = $row_items["prerequisite"];
+
+						//if ($row_items["prereq_type"] == 'i')
+						//{
+							//item
+							$sql_items2 = "SELECT * FROM $tbl_lp_item WHERE id='$prereq'"; //check if prereq has been deleted
+							$result_items2 = Database::query($sql_items2, __FILE__, __LINE__);
+							$number_items2 = Database::num_rows($result_items2);
+							if ($number_items2 == 0)
+							{
+								echo get_lang('prereq_deleted_error');
+							}
+							$row_items2 = mysql_fetch_array($result_items2);
+							display_addedresource_link_in_learnpath($row_items2["item_type"], $row_items2["ref"], '', $row_items2["id"], 'builder', '', 0);
+							if ((($row_items2["item_type"] == TOOL_QUIZ) or ($row_items2["item_type"] == 'HotPotatoes')) and ($row_items['prerequisite']))
+							{
+								//echo "&nbsp;({$row_items2['title']})";
+							}
+						//}
+						/*
+						if ($row_items["prereq_type"] == 'c')
+						{
+							//chapter
+							$sql_items2 = "SELECT * FROM $tbl_lp_item WHERE id='$prereq' AND item_type='dokeos_chapter'"; //check if prereq has been deleted
+							$result_items2 = Database::query($sql_items2, __FILE__, __LINE__);
+							$number_items2 = Database::num_rows($result_items2);
+							if ($number_items2 == 0)
+							{
+								echo "<font color='red'>$lang_prereq_deleted_error</font>";
+							}
+							$row_items2 = mysql_fetch_array($result_items2);
+							echo " {$row_items2['title']}";
+						}*/
+					}
+					echo "</font></td>";
+					$xml_output .= "<element_type>".$row_items["item_type"]."</element_type>";
+					$xml_output .= "<element_id>".$row_items["item_id"]."</element_id>";
+
+					// move
+					if ($i < $num_modules)
+					{
+						echo "<td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=moveitem&amp;type=item&amp;direction=down&amp;moduleid=".$parent_item_id."&amp;id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/down.gif\" border=\"0\" title=\"$lang_move_down\">"."</a>"."</td>";
+					}
+					else
+					{
+						echo "<td width='30' align='center'>&nbsp;</td>";
+					}
+
+					if ($i > 1)
+					{
+						echo "<td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=moveitem&amp;type=item&amp;direction=up&amp;moduleid=".$parent_item_id."&amp;id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/up.gif\" border=\"0\" title=\"$lang_move_up\">"."</a>";
+					}
+					else
+					{
+						echo "<td width='30' align='center'>&nbsp;</td>";
+					}
+					echo "</td>"."<td align='center'>";
+
+					// edit prereq
+					echo "<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=edititemprereq&amp;id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/scormpre.gif\" border=\"0\" title=\"$lang_add_prereq\">"."</a>"."</td>";
+
+					// edit
+					echo "<td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&amp;action=edititem&amp;id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath_item\">"."</a>"."</td>";
+
+					// delete
+					echo "<td align='center'>"."<a href='".api_get_self()."?lp_id=$learnpath_id&action=deleteitem&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>"."<img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath_item\" onclick=\"return confirmation('".$row_items["item_type"]."');\">"."</a>";
+				}
+				$i ++;
+				echo "</td></tr>";
+
+			}
+		}
+	}
+}
+
+/**
+ * Displays all learning paths.
+ * @return	void
+ * @todo eliminate all global $lang declarations, use get_lang, improve structure.
+ */
+function display_all_learnpath()
+{
+	global $tbl_tool, $color2;
+	global $xml_output, $lang_edit_learnpath, $lang_delete_learnpath, $lang_publish, $lang_no_publish, $lang_add_learnpath_chapter_to_path;
+	$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
+
+	$sql = "SELECT * FROM  $tbl_learnpath_main  ORDER BY learnpath_name";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$i = 1;
+	$num_modules = mysql_num_rows($result);
+
+	while ($row = mysql_fetch_array($result))
+	{
+		//other grey color : #E6E6E6
+		echo "<tr><td bgcolor=\"$color2\" width=400><b>&nbsp;";
+		echo "<a href='learnpath_handler.php?&lp_id={$row['lp_id']}'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9>{$row['learnpath_name']}</a>";
+		echo "</b><br><i><div class=text align=justify>{$row['learnpath_description']}</div></i></td>";
+
+		// showing the edit, delete and publish icons
+		if (is_allowed_to_edit())
+		{
+			echo "<td bgcolor=\"$color2\" align=center><a href='learnpath_handler.php?lp_id={$row['lp_id']}&action=add&type=learnpathcategory'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src='../img/0.gif' width='13' height='13' border='0' title='$lang_add_learnpath_chapter_to_path'></a></td>";
+			echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=editpath&id=".$row["lp_id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath\"></a></td>";
+			echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=deletepath&id=".$row["lp_id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath\" onclick=\"return confirmation('".$row2['learnpath_name']."');\"></a></td>";
+			$id = $row["lp_id"];
+			$sql2 = "SELECT * FROM $tbl_learnpath_main where lp_id=$id";
+			$result2 = Database::query($sql2, __FILE__, __LINE__);
+			$row2 = mysql_fetch_array($result2);
+			$name = $row2['learnpath_name'];
+			$sql3 = "SELECT * FROM $tbl_tool where (name=\"$name\" and image='scormbuilder.gif')";
+			$result3 = Database::query($sql3, __FILE__, __LINE__);
+			$row3 = mysql_fetch_array($result3);
+			if (($row3["visibility"]) == '1')
+			{
+				echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=publishpath&set=i&id=".$row["lp_id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/visible.gif\" border=\"0\" title=\"$lang_no_publish\"></a></td>";
+			}
+			else
+			{
+				echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=publishpath&set=v&id=".$row["lp_id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/invisible.gif\" border=\"0\" title=\"$lang_publish\"></a></td>";
+			}
+		}
+		$i ++;
+		echo "<tr><td>&nbsp;</td></tr>";
+	}
+}
+
+/**
+ * Displays the learning path items/steps.
+ * @param		integer		Category ID
+ * @return	void
+ * @todo eliminate all global $lang declarations, use get_lang, improve structure.
+ */
+function display_learnpath_items($categoryid)
+{
+	global $xml_output;
+	global $lang_prerequisites, $lang_move_down, $lang_move_up, $lang_edit_learnpath_item, $lang_delete_learnpath_item, $learnpath_id, $lang_add_prereq, $lang_prereq_deleted_error, $lang_pre_short, $langThisItem;
+	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+
+	$sql_items = "SELECT * FROM $tbl_lp_item WHERE parent_item_id='$categoryid' ORDER BY display_order ASC";
+	$result_items = Database::query($sql_items,__FILE__,__LINE__);
+	$number_items = Database::num_rows($result_items);
+	$i = 1;
+	error_log('Selected item under '.$categoryid,0);
+
+	while ($row_items = Database::fetch_array($result_items))
+	{
+		echo "<tr><td colspan='2' valign='top'>";
+		display_addedresource_link_in_learnpath($row_items["item_type"], $row_items["ref"], '', $row_items["id"], 'builder', 'icon');
+		if ($row_items["description"])
+		{
+			echo "<div align='justify'><font color='#999999'>&nbsp;&nbsp;&nbsp;{$row_items['description']}</font>";
+		}
+		echo "</td>";
+		if (is_prereq($learnpath_id))
+		{
+			echo '<td bgcolor="#EEEEFF">';
+		}
+		else
+		{
+			echo "<td>";
+		}
+
+		if (is_allowed_to_edit())
+		{
+			error_log('Is allowed to edit item'.$row_items['id'],0);
+			//TODO: fix by adding true prerequisites parsing (and cycle through)
+			//Over simplification here, we transform prereq_id field into prerequisite field
+			if ($row_items["prerequisite"] <> '')
+			{
+				$prereq = $row_items["prerequisite"];
+
+				//if ($row_items["prereq_type"] == 'i')
+				//{
+					//item
+					$sql_items2 = "SELECT * FROM $tbl_lp_item WHERE id='$prereq'"; //check if prereq has been deleted
+					$result_items2 = Database::query($sql_items2);
+					$number_items2 = Database::num_rows($result_items2);
+					if ($number_items2 == 0)
+					{
+						echo "<font color=red>$lang_prereq_deleted_error</font>";
+					}
+					$row_items2 = Database::fetch_array($result_items2);
+					display_addedresource_link_in_learnpath($row_items2["item_type"], $row_items2["ref"], '', $row_items2["id"], 'builder', '');
+					if ((($row_items2["item_type"] == 'Exercise') or ($row_items2["item_type"] == 'HotPotatoes')) and ($row_items['prerequisites']))
+					{
+						echo "&nbsp;({$row_items2['title']})";
+					}
+				//}
+				/*if ($row_items["prereq_type"] == 'c')
+				{
+					//chapter
+					$sql_items2 = "SELECT * FROM $tbl_learnpath_chapter WHERE id='$prereq'"; //check if prereq has been deleted
+					$result_items2 = Database::query($sql_items2,__FILE__,__LINE__);
+					$number_items2 = Database::num_rows($result_items2);
+					if ($number_items2 == 0)
+					{
+						echo "<font color=red>$lang_prereq_deleted_error</font>";
+					}
+					$row_items2 = Database::fetch_array($result_items2);
+					echo " {$row_items2['chapter_name']}";
+				}*/
+			}
+			echo "</font></td>";
+			$xml_output .= "<element_type>".$row_items["item_type"]."</element_type>";
+			$xml_output .= "<element_id>".$row_items["id"]."</element_id>";
+
+			// move
+			if ($i < $number_items)
+			{
+				echo "<td align='center'><a href='".api_get_self()."?lp_id=$learnpath_id&action=moveitem&direction=down&moduleid=".$categoryid."&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/down.gif\" border=\"0\" title=\"$lang_move_down\"></a></td>";
+			}
+			else
+			{
+				echo "<td width='30' align='center'>&nbsp;</td>";
+			}
+
+			if ($i > 1)
+			{
+				echo "<td align='center'><a href='".api_get_self()."?lp_id=$learnpath_id&action=moveitem&direction=up&moduleid=".$categoryid."&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/up.gif\" border=\"0\" title=\"$lang_move_up\"></a>";
+			}
+			else
+			{
+				echo "<td width='30' align='center'>&nbsp;</td>";
+			}
+			echo "</td><td align='center'>";
+
+			// edit prereq
+			echo "<a href='".api_get_self()."?lp_id=$learnpath_id&action=edititemprereq&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/scormpre.gif\" border=\"0\" title=\"$lang_add_prereq\"></a></td>";
+
+			// edit
+			echo "<td align='center'><a href='".api_get_self()."?lp_id=$learnpath_id&action=edititem&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath_item\"></a></td>";
+
+			// delete
+			echo "<td align='center'>";
+			echo "<a href='".api_get_self()."?lp_id=$learnpath_id&action=deleteitem&id=".$row_items["id"]."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath_item\" onclick=\"return confirmation('".$langThisItem."');\"></a>";
+		}
+		$i ++;
+		echo "</td></tr>";
+	}
+}
+
+/**
+ * This function returns the items belonging to the chapter that contains the given item (brother items)
+ * @param	integer	Item id
+ * @return	array		Table containing the items
+ */
+function learnpath_items($itemid)
+{
+	global $xml_output;
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+
+	$sql_items = "SELECT parent_item_id FROM $tbl_lp_item WHERE id='$itemid'";
+	$moduleid_sql = Database::query($sql_items);
+	$moduleid_array = mysql_fetch_array($moduleid_sql); //first row of the results
+	$moduleid = $moduleid_array["parent_item_id"];
+
+	$sql_items = "SELECT * FROM $tbl_lp_item WHERE parent_item_id='$moduleid' ORDER BY display_order ASC";
+	$result_items = Database::query($sql_items);
+	$ar = mysql_fetch_array($result_items);
+	while ($ar != '')
+	{
+		$result[] = $ar;
+		$ar = mysql_fetch_array($result_items);
+	}
+	return $result;
+
+}
+
+/**
+ * This function returns the chapters belonging to the path that contais the given chapter (brother chapters)
+ * @param	integer	Learnpath id
+ * @return array		Table containing the chapters
+ */
+function learnpath_chapters($learnpath_id)
+{
+	global $xml_output, $learnpath_id;
+	//$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+
+
+	$sql_items = "SELECT * FROM $tbl_lp_item WHERE lp_id='$learnpath_id' AND item_type='dokeos_chapter' ORDER BY display_order ASC";
+	//$sql_items = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id='$learnpath_id' ORDER BY display_order ASC";
+	$result_items = Database::query($sql_items, __FILE__, __LINE__);
+	$ar = mysql_fetch_array($result_items);
+	while ($ar != '')
+	{
+		$result[] = $ar;
+		$ar = mysql_fetch_array($result_items);
+	}
+	return $result;
+
+}
+
+/**
+ * This function tells if a learnpath contains items which are prerequisite to other items
+ * @param	integer	Learnpath id
+ * @return	boolean	True if this learnpath contains an item which is a prerequisite to something
+ */
+function is_prereq($learnpath_id)
+{
+	global $xml_output;
+	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+
+	$prereq = false;
+
+	$sql_items = "SELECT * FROM $tbl_lp_item WHERE lp_id='$learnpath_id' AND parent_item_id=0 ORDER BY display_order ASC";
+	$result_items = Database::query($sql_items,__FILE__,__LINE__);
+	while ($ar = Database::fetch_array($result_items))
+	{
+		$c = $ar['id'];
+		$sql_items2 = "SELECT * FROM $tbl_lp_item WHERE lp_id = $learnpath_id AND parent_item_id='$c' ORDER BY display_order ASC";
+		$result_items2 = Database::query($sql_items2,__FILE__,__LINE__);
+		while ($ar2 = Database::fetch_array($result_items2))
+		{
+			if ($ar2['prerequisite'] != '')
+			{
+				$prereq = true;
+			}
+		}
+	}
+	return ($prereq);
+}
+
+/**
+ * This function returns the prerequisite sentence
+ * @param	integer	Item ID
+ * @return	string 	Prerequisite warning text
+ */
+function prereqcheck($id_in_path)
+{
+	//1 Initialise and import working vars
+	global $learnpath_id, $_user;
+	global $langPrereqToEnter, $langPrereqTestLimit1, $langPrereqTestLimit2, $langPrereqTestLimitNow, $langPrereqFirstNeedTo, $langPrereqModuleMinimum1, $langPrereqModuleMinimum2;
+	$tbl_learnpath_user = Database :: get_course_table(TABLE_LEARNPATH_USER);
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+
+	//2 Initialise return value
+	$prereq = false;
+
+	//3 Get item data from the database
+	$sql_items = "SELECT * FROM $tbl_learnpath_item WHERE id='$id_in_path'";
+	$result_items = Database::query($sql_items);
+	$row = mysql_fetch_array($result_items);
+	//4 Check prerequisite's type
+	if ($row['prereq_type'] == 'i')
+	{
+		//4.a If prerequisite is of type 'i' (item)
+		//4.a.1 Get data ready for use
+		$id_in_path3 = $row['prereq_id'];
+		$prereq_limit = $row['prereq_completion_limit'];
+
+		//4.a.2 Get data from the user-item relation
+		if ($_user['user_id'] == '')
+		{
+			$user_id = '0';
+		}
+		else
+		{
+			$user_id = $_user['user_id'];
+		}
+		$sql_items3 = "SELECT * FROM $tbl_learnpath_user WHERE (learnpath_item_id='$id_in_path3' and user_id=$user_id)";
+		$result_items3 = Database::query($sql_items3);
+		$row3 = mysql_fetch_array($result_items3);
+
+		//4.a.3 Get the link that needs to be shown for the current item (not the prereq)
+		$stepname = display_addedresource_link_in_learnpath($row['item_type'], $row['ref'], '', $id_in_path, 'builder', 'nolink');
+		//this is the step we want to open
+		$stepname = trim($stepname); //to remove occasional line breaks and white spaces
+
+		//4.a.4 Get the prerequisite item
+		$sql6 = "SELECT * FROM $tbl_learnpath_item WHERE (id='$id_in_path3')";
+		$result6 = Database::query($sql6);
+		$row6 = mysql_fetch_array($result6);
+		//4.a.5 Get a link to the prerequisite item
+		$prereqname = display_addedresource_link_in_learnpath($row6['item_type'], $row6['ref'], '', $id_in_path3, 'builder', 'nolink'); //this is the prereq of the step we want to open
+
+		//4.a.5 Initialise limit value
+		$limitok = true;
+		//4.a.6 Get prerequisite limit
+		if ($prereq_limit)
+		{
+			//4.a.6.a If the completion limit exists
+			if ($row3['score'] < $prereq_limit)
+			{
+				//4.a.6.a.a If the completion limit hasn't been reached, then display the corresponding message
+				$prereq = $langPrereqToEnter.$stepname.$langPrereqTestLimit1."$prereq_limit".$langPrereqTestLimit2.$prereqname.". (".$langPrereqTestLimitNow.$row3['score'].")";
+			}
+			else
+			{
+				//4.a.6.a.b The completion limit has been reached. Prepare to return false (no prereq hanging)
+				$prereq = false;
+			}
+		}
+		else
+		{
+			//4.a.6.b If the completion limit doesn't exist
+			if ($row3['status'] == "completed" or $row3['status'] == 'passed')
+			{
+				//4.a.6.b.a If the prerequisite status is 'completed'
+				$prereq = false;
+			}
+			else
+			{
+				//4.a.6.b.b The prerequisite status is not 'completed', return corresponding message
+				$prereq = $langPrereqToEnter.$stepname.$langPrereqFirstNeedTo.$prereqname.'.';
+			}
+		}
+
+	}
+	elseif ($row['prereq_type'] == 'c')
+	{
+		//4.b If prerequisite is of type 'c' (chapter)
+		//4.b.1 Get data ready to use
+		$id_in_path2 = $row['prereq_id'];
+		//4.b.2 Get all items in the prerequisite chapter
+		$sql_items3 = "SELECT * FROM $tbl_lp_item WHERE parent_item_id='$id_in_path2'";
+		$result_items3 = Database::query($sql_items3);
+		$allcompleted = true;
+		while ($row3 = mysql_fetch_array($result_items3))
+		{
+			//4.b.3 Cycle through items in the prerequisite chapter
+			//4.b.3.1 Get data ready to use
+			$id_in_path4 = $row3['id'];
+			if ($_user['user_id'] == '')
+			{
+				$user_id = '0';
+			}
+			else
+			{
+				$user_id = $_user['user_id'];
+			}
+			//4.b.3.2 Get user-item relation
+			$sql_items4 = "SELECT * FROM $tbl_learnpath_user WHERE (learnpath_item_id='$id_in_path4' and user_id=$user_id)";
+			$result_items4 = Database::query($sql_items4);
+			$row4 = mysql_fetch_array($result_items4);
+			//4.b.3.3 If any of these elements is not 'completed', the overall completion status is false
+			if ($row4['status'] != "completed" and $row4['status'] != 'passed')
+			{
+				$allcompleted = false;
+			}
+		}
+		if ($allcompleted)
+		{
+			//4.b.4.a All items were completed, prepare to return that there is no prerequisite blocking the way
+			$prereq = false;
+		}
+		else
+		{
+			//4.b.4.b Something was not completed. Return corresponding message
+			$sql5 = "SELECT * FROM $tbl_learnpath_chapter WHERE (lp_id='$learnpath_id' and id='$id_in_path2')";
+			$result5 = Database::query($sql5);
+			$row5 = mysql_fetch_array($result5);
+			$prereqmodulename = trim($row5['chapter_name']);
+			$prereq = $langPrereqModuleMinimum1.$prereqmodulename.$langPrereqModuleMinimum2;
+		}
+	}
+	else
+	{
+		//5 If prerequisite type undefined, no prereq
+		$prereq = false;
+	}
+	//6 Return the message (or false if no prerequisite waiting)
+	return ($prereq);
+}
+
+/**
+ * Constructs the tree that will be used to build the learnpath structure
+ * @params  integer     Learnpath_id
+ * @return  array       Tree of the learnpath structure
+ * @author  Yannick Warnier <yannick.warnier@dokeos.com>
+ * @comment This is a temporary function, which exists while the chapters and items
+ *          are still in separate tables in the database. This function gathers the data in a unique tree.
+ **/
+function get_learnpath_tree($learnpath_id)
+{
+	//error_log('New LP - In learnpath_functions::get_learnpath_tree',0);
+	//init elems
 	#global $tbl_learnpath_item, $tbl_learnpath_chapter;
-	/*
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-	*/
-	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-
-	$tree = array ();
-	$chapters = array ();
-	//$chapters = array();
-	//$chapters_by_parent = array();
-	//$items = array();
-	//$items_by_chapter = array();
-	$all_items_by_chapter = array ();
-	$sql = "SELECT * FROM $tbl_lp_item WHERE lp_id = ".$learnpath_id." AND item_type='dokeos_chapter' ORDER BY display_order";
-	//error_log('New LP - learnpath_functions - get_learnpath_tree: '.$sql,0);
-	$res = Database::query($sql, __FILE__, __LINE__);
-	// format the $chapters_by_parent array so we have a suitable structure to work with
-	while ($row = Database::fetch_array($res))
-	{
-		$chapters[] = $row;
-		//shouldn't be necessary (check no null value)
-		if (empty ($row['parent_item_id']))
-		{
-			$row['parent_item_id'] = 0;
-		}
-		//$chapters_by_parent[$row['parent_item_id']][$row['previous_item_id']] = $row;
-		$all_items_by_chapter[$row['parent_item_id']][$row['display_order']] = $row;
-		$all_items_by_chapter[$row['parent_item_id']][$row['display_order']]['type'] = 'dokeos_chapter';
-	}
-
-	// now for every item in each chapter, get a suitable structure too
-	foreach ($chapters as $row)
-	{
-		// select items from this chapter
-		$sql = "SELECT * FROM $tbl_lp_item WHERE lp_id = $learnpath_id AND parent_item_id = ".$row['id']." ORDER BY display_order";
-		//error_log('New LP - learnpath_functions - get_learnpath_tree: '.$sql,0);
-		$res = Database::query($sql, __FILE__, __LINE__);
-		//error_log('New LP - learnpath_functions - get_learnpath_tree: Found '.Database::num_rows($res).' results',0);
-		while ($myrow = mysql_fetch_array($res, MYSQL_ASSOC))
-		{
-			//$items[] = $myrow;
-			//$items_by_chapter[$myrow['parent_item_id']][$myrow['display_order']] = $myrow;
-			$all_items_by_chapter[$row['id']][$myrow['display_order']] = $myrow;
-			$all_items_by_chapter[$row['id']][$myrow['display_order']]['type'] = 'item';
-		}
-	}
-	//array_multisort($all_items_by_chapter[0], SORT_ASC, SORT_NUMERIC);
-	foreach ($all_items_by_chapter as $key => $subrow)
-	{
-		ksort($all_items_by_chapter[$key]);
-	}
-
-	//all items should now be well-ordered
-	//error_log('New LP - In get_learnpath_tree, returning '.print_r($all_items_by_chapter,true),0);
-	return $all_items_by_chapter;
-}
-
-/**
- * Gives a list of sequencial elements IDs for next/previous actions
- * @param   array   The elements tree as returned by get_learnpath_tree()
- * @param   integer The chapter id to start from
- * @param   boolean Whether to include chapters or not
- * @return  array   List of elements in the first to last order
- * @author  Yannick Warnier <yannick.warnier@dokeos.com>
- **/
-function get_ordered_items_list($tree, $chapter = 0, $include_chapters = false)
-{
-	$list = array ();
-	foreach ($tree[$chapter] as $order => $elem)
-	{
-		if ($elem['type'] == 'chapter')
-		{
-			if ($include_chapters === true)
-			{
-				$list[] = array ('id' => $elem['id'], 'type' => $elem['type']);
-			}
-			$res = get_ordered_items_list($tree, $elem['id'], $include_chapters);
-			foreach ($res as $elem)
-			{
-				$list[] = $elem;
-			}
-		}
-		elseif ($elem['type'] == 'item')
-		{
-			$list[] = array ('id' => $elem['id'], 'type' => $elem['type'], 'item_type' => $elem['item_type'], 'parent_item_id' => $elem['parent_item_id'], 'item_id' => $elem['item_id']);
-		}
-	}
-	return $list;
-}
-
-/**
+	/*
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+	*/
+	$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+
+	$tree = array ();
+	$chapters = array ();
+	//$chapters = array();
+	//$chapters_by_parent = array();
+	//$items = array();
+	//$items_by_chapter = array();
+	$all_items_by_chapter = array ();
+	$sql = "SELECT * FROM $tbl_lp_item WHERE lp_id = ".$learnpath_id." AND item_type='dokeos_chapter' ORDER BY display_order";
+	//error_log('New LP - learnpath_functions - get_learnpath_tree: '.$sql,0);
+	$res = Database::query($sql, __FILE__, __LINE__);
+	// format the $chapters_by_parent array so we have a suitable structure to work with
+	while ($row = Database::fetch_array($res))
+	{
+		$chapters[] = $row;
+		//shouldn't be necessary (check no null value)
+		if (empty ($row['parent_item_id']))
+		{
+			$row['parent_item_id'] = 0;
+		}
+		//$chapters_by_parent[$row['parent_item_id']][$row['previous_item_id']] = $row;
+		$all_items_by_chapter[$row['parent_item_id']][$row['display_order']] = $row;
+		$all_items_by_chapter[$row['parent_item_id']][$row['display_order']]['type'] = 'dokeos_chapter';
+	}
+
+	// now for every item in each chapter, get a suitable structure too
+	foreach ($chapters as $row)
+	{
+		// select items from this chapter
+		$sql = "SELECT * FROM $tbl_lp_item WHERE lp_id = $learnpath_id AND parent_item_id = ".$row['id']." ORDER BY display_order";
+		//error_log('New LP - learnpath_functions - get_learnpath_tree: '.$sql,0);
+		$res = Database::query($sql, __FILE__, __LINE__);
+		//error_log('New LP - learnpath_functions - get_learnpath_tree: Found '.Database::num_rows($res).' results',0);
+		while ($myrow = mysql_fetch_array($res, MYSQL_ASSOC))
+		{
+			//$items[] = $myrow;
+			//$items_by_chapter[$myrow['parent_item_id']][$myrow['display_order']] = $myrow;
+			$all_items_by_chapter[$row['id']][$myrow['display_order']] = $myrow;
+			$all_items_by_chapter[$row['id']][$myrow['display_order']]['type'] = 'item';
+		}
+	}
+	//array_multisort($all_items_by_chapter[0], SORT_ASC, SORT_NUMERIC);
+	foreach ($all_items_by_chapter as $key => $subrow)
+	{
+		ksort($all_items_by_chapter[$key]);
+	}
+
+	//all items should now be well-ordered
+	//error_log('New LP - In get_learnpath_tree, returning '.print_r($all_items_by_chapter,true),0);
+	return $all_items_by_chapter;
+}
+
+/**
+ * Gives a list of sequencial elements IDs for next/previous actions
+ * @param   array   The elements tree as returned by get_learnpath_tree()
+ * @param   integer The chapter id to start from
+ * @param   boolean Whether to include chapters or not
+ * @return  array   List of elements in the first to last order
+ * @author  Yannick Warnier <yannick.warnier@dokeos.com>
+ **/
+function get_ordered_items_list($tree, $chapter = 0, $include_chapters = false)
+{
+	$list = array ();
+	foreach ($tree[$chapter] as $order => $elem)
+	{
+		if ($elem['type'] == 'chapter')
+		{
+			if ($include_chapters === true)
+			{
+				$list[] = array ('id' => $elem['id'], 'type' => $elem['type']);
+			}
+			$res = get_ordered_items_list($tree, $elem['id'], $include_chapters);
+			foreach ($res as $elem)
+			{
+				$list[] = $elem;
+			}
+		}
+		elseif ($elem['type'] == 'item')
+		{
+			$list[] = array ('id' => $elem['id'], 'type' => $elem['type'], 'item_type' => $elem['item_type'], 'parent_item_id' => $elem['parent_item_id'], 'item_id' => $elem['item_id']);
+		}
+	}
+	return $list;
+}
+
+/**
  * Displays the structure of a chapter recursively. Takes the result of get_learnpath_tree as argument
- * @param	array		Chapter structure
- * @param	integer	Chapter ID (start point in the tree)
+ * @param	array		Chapter structure
+ * @param	integer	Chapter ID (start point in the tree)
  * @param	integer	Learnpath ID
- * @param	integer	User ID
+ * @param	integer	User ID
  * @param	boolean	Indicates if the style is wrapped (true) or extended (false)
- * @param	integer	Level reached so far in the tree depth (enables recursive behaviour)
- * @return	array		Number of items, Number of items completed
+ * @param	integer	Level reached so far in the tree depth (enables recursive behaviour)
+ * @return	array		Number of items, Number of items completed
  * @author	Many changes by Yannick Warnier <yannick.warnier@dokeos.com>
- **/
-function display_toc_chapter_contents($tree, $parent_item_id = 0, $learnpath_id, $uid, $wrap, $level = 0)
-{
-		#global $tbl_learnpath_user;
-	$tbl_learnpath_user = Database :: get_course_table(TABLE_LEARNPATH_USER);
-	$num = 0;
-	$num_completed = 0;
-	foreach ($tree[$parent_item_id] as $order => $elem)
-	{
-
-		$bold = false;
-		if (!empty ($_SESSION['cur_open']) && ($elem['id'] == $_SESSION['cur_open']))
-		{
-			$bold = true;
-		}
-		if ($elem['type'] === 'chapter')
-		{
-			if ($wrap)
-			{
-				echo str_repeat("&nbsp;&nbsp;", $level).shorten(strip_tags($elem['chapter_name']), (35 - 3 * $level))."<br />\n";
-			}
-			else
-			{
-				echo "<tr><td colspan='3'>".str_repeat("&nbsp;&nbsp;", $level).shorten($elem['chapter_name'], (35 - 3 * $level))."</td></tr>\n";
-			}
-
-			if ($wrap)
-			{
-				if ($elem['chapter_description'] != '')
-				{
-					echo "<div class='description'>".str_repeat("&nbsp;&nbsp;", $level)."&nbsp;".shorten($elem['chapter_description'], (35 - 3 * $level))."</div>\n";
-				}
-			}
-			else
-			{
-				if ($elem['chapter_description'] != '')
-				{
-					echo "<tr><td colspan='3'><div class='description'>".str_repeat("&nbsp;&nbsp;", $level)."&nbsp;".shorten($elem['chapter_description'], (35 - 3 * $level))."</div></td></tr>\n";
-				}
-			}
-			list ($a, $b) = display_toc_chapter_contents($tree, $elem['id'], $learnpath_id, $uid, $wrap, $level +1);
-			$num += $a;
-			$num_completed += $b;
-
-		}
-		elseif ($elem['type'] === 'item')
-		{
-			// If this element is an item (understand: not a directory/module)
-			$sql0 = "SELECT * FROM $tbl_learnpath_user WHERE (user_id='".$uid."' and learnpath_item_id='".$elem['id']."' and lp_id='".$learnpath_id."')";
-			$result0 = Database::query($sql0, __FILE__, __LINE__);
-			$row0 = mysql_fetch_array($result0);
-
-			$completed = '';
-			if (($row0['status'] == 'completed') or ($row0['status'] == 'passed'))
-			{
-				$completed = 'completed';
-				$num_completed ++;
-			}
-
-			if ($wrap)
-			{
-				echo str_repeat("&nbsp;&nbsp;", $level)."<a name='{$elem['id']}' />\n";
-			}
-			else
-			{
-				echo "<tr><td>".str_repeat("&nbsp;&nbsp;", $level-1)."<a name='{$elem['id']}' />\n";
-			}
-
-			if ($wrap)
-			{
-				$icon = 'wrap';
-			}
-
-			if ($bold)
-			{
-				echo "<b>";
-			}
-			display_addedresource_link_in_learnpath($elem['item_type'], $elem['ref'], $completed, $elem['id'], 'player', $icon);
-			if ($bold)
-			{
-				echo "</b>";
-			}
-			if ($wrap)
-			{
-				echo "<br />\n";
-			}
-			else
-			{
-				echo "</td></tr>\n";
-			}
-
-			$num ++;
-		}
-	}
-	return array ($num, $num_completed);
-}
-
-/**
- * Returns a string to display in the tracking frame within the contents.php page (for example)
- * @param   integer     Learnpath id
- * @param   integer     Current user id
- * @param   integer     Starting chapter id
- * @param   array       Tree of elements as returned by get_learnpath_tree()
- * @param   integer     Level of recursivity we have reached
- * @param   integer     Counter of elements already displayed
- * @author  Yannick Warnier <yannick.warnier@dokeos.com>
- * @note : forced display because of display_addedresource_link_in_learnpath behaviour (outputing a string would be better)
- **/
-function get_tracking_table($learnpath_id, $user_id, $parent_item_id = 0, $tree = false, $level = 0, $counter = 0)
-{
-	$tbl_learnpath_chapter = Database :: get_course_learnpath_chapter_table();
-	$tbl_learnpath_item = Database :: get_course_learnpath_item_table();
-	$tbl_learnpath_user = Database :: get_course_learnpath_user_table();
-	//$mytable = '';
-	$include_chapters = true;
-
-	if (!is_array($tree))
-	{
-		//get a tree of the current learnpath elements
-		$tree = get_learnpath_tree($learnpath_id);
-	}
-	foreach ($tree[$parent_item_id] as $order => $elem)
-	{
-		if (($counter % 2) == 0)
-		{
-			$oddclass = 'row_odd';
-		}
-		else
-		{
-			$oddclass = 'row_even';
-		}
-
-		if ($elem['type'] == 'chapter')
-		{
-			if ($include_chapters === true)
-			{
-				//$mytable .= "<tr class='$oddclass'><td colspan = '3'>".str_repeat('&nbsp;',$level*2+2).$elem['chapter_name']."</td></tr>\n";
-				echo "<tr class='$oddclass'><td colspan = '3'>".str_repeat('&nbsp;', $level * 2 + 2).$elem['chapter_name']."</td></tr>\n";
-			}
-			$counter ++;
-			//$mytable .= get_tracking_table($learnpath_id, $user_id, $elem['id'], $tree, $level + 1, $counter );
-			get_tracking_table($learnpath_id, $user_id, $elem['id'], $tree, $level +1, $counter);
-
-		}
-		elseif ($elem['type'] == 'item')
-		{
-
-			$sql = "SELECT * FROM $tbl_learnpath_user "."WHERE user_id = $user_id "."AND lp_id = $learnpath_id "."AND learnpath_item_id = ".$elem['id'];
-			$res = Database::query($sql, __FILE__, __LINE__);
-			$myrow = mysql_fetch_array($res);
-
-			if (($myrow['status'] == 'completed') || ($myrow['status'] == 'passed'))
-			{
-				$color = 'blue';
-				$statusmessage = get_lang('Complete');
-			}
-			else
-			{
-				$color = 'black';
-				$statusmessage = get_lang('Incomplete');
-			}
-
-			$link = get_addedresource_link_in_learnpath($elem['item_type'], $elem['id'], $elem['item_id']);
-			//$link = display_addedresource_link_in_learnpath($elem['item_type'], $elem['id'], $row['status'], $elem['item_id'], 'player', 'none');
-
-			//$mytable .= "<tr class='$oddclass'>"
-			echo "<tr class='$oddclass'>"."<td class='mystatus'>".str_repeat("&nbsp;", $level * 2 + 2);
-			//."<a href='$link?SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9' target='toc'>hop</a>"
-			display_addedresource_link_in_learnpath($elem['item_type'], $elem['ref'], $myrow['status'], $elem['id'], 'player', 'wrap');
-			//we should also add the total score here
-			echo "<td>"."<font color='$color'><div class='mystatus'>".$statusmessage."</div></font>"."</td>"."<td>"."<div class='mystatus' align='center'>". ($myrow['score'] == 0 ? '-' : $myrow['score'])."</div>"."</td>"."</tr>\n";
-			$counter ++;
-		}
-	}
-	//return $mytable;
-	return true;
-}
-
-/**
- * This function returns false if there is at least one item in the path
- * @param	Learnpath ID
+ **/
+function display_toc_chapter_contents($tree, $parent_item_id = 0, $learnpath_id, $uid, $wrap, $level = 0)
+{
+		#global $tbl_learnpath_user;
+	$tbl_learnpath_user = Database :: get_course_table(TABLE_LEARNPATH_USER);
+	$num = 0;
+	$num_completed = 0;
+	foreach ($tree[$parent_item_id] as $order => $elem)
+	{
+
+		$bold = false;
+		if (!empty ($_SESSION['cur_open']) && ($elem['id'] == $_SESSION['cur_open']))
+		{
+			$bold = true;
+		}
+		if ($elem['type'] === 'chapter')
+		{
+			if ($wrap)
+			{
+				echo str_repeat("&nbsp;&nbsp;", $level).shorten(strip_tags($elem['chapter_name']), (35 - 3 * $level))."<br />\n";
+			}
+			else
+			{
+				echo "<tr><td colspan='3'>".str_repeat("&nbsp;&nbsp;", $level).shorten($elem['chapter_name'], (35 - 3 * $level))."</td></tr>\n";
+			}
+
+			if ($wrap)
+			{
+				if ($elem['chapter_description'] != '')
+				{
+					echo "<div class='description'>".str_repeat("&nbsp;&nbsp;", $level)."&nbsp;".shorten($elem['chapter_description'], (35 - 3 * $level))."</div>\n";
+				}
+			}
+			else
+			{
+				if ($elem['chapter_description'] != '')
+				{
+					echo "<tr><td colspan='3'><div class='description'>".str_repeat("&nbsp;&nbsp;", $level)."&nbsp;".shorten($elem['chapter_description'], (35 - 3 * $level))."</div></td></tr>\n";
+				}
+			}
+			list ($a, $b) = display_toc_chapter_contents($tree, $elem['id'], $learnpath_id, $uid, $wrap, $level +1);
+			$num += $a;
+			$num_completed += $b;
+
+		}
+		elseif ($elem['type'] === 'item')
+		{
+			// If this element is an item (understand: not a directory/module)
+			$sql0 = "SELECT * FROM $tbl_learnpath_user WHERE (user_id='".$uid."' and learnpath_item_id='".$elem['id']."' and lp_id='".$learnpath_id."')";
+			$result0 = Database::query($sql0, __FILE__, __LINE__);
+			$row0 = mysql_fetch_array($result0);
+
+			$completed = '';
+			if (($row0['status'] == 'completed') or ($row0['status'] == 'passed'))
+			{
+				$completed = 'completed';
+				$num_completed ++;
+			}
+
+			if ($wrap)
+			{
+				echo str_repeat("&nbsp;&nbsp;", $level)."<a name='{$elem['id']}' />\n";
+			}
+			else
+			{
+				echo "<tr><td>".str_repeat("&nbsp;&nbsp;", $level-1)."<a name='{$elem['id']}' />\n";
+			}
+
+			if ($wrap)
+			{
+				$icon = 'wrap';
+			}
+
+			if ($bold)
+			{
+				echo "<b>";
+			}
+			display_addedresource_link_in_learnpath($elem['item_type'], $elem['ref'], $completed, $elem['id'], 'player', $icon);
+			if ($bold)
+			{
+				echo "</b>";
+			}
+			if ($wrap)
+			{
+				echo "<br />\n";
+			}
+			else
+			{
+				echo "</td></tr>\n";
+			}
+
+			$num ++;
+		}
+	}
+	return array ($num, $num_completed);
+}
+
+/**
+ * Returns a string to display in the tracking frame within the contents.php page (for example)
+ * @param   integer     Learnpath id
+ * @param   integer     Current user id
+ * @param   integer     Starting chapter id
+ * @param   array       Tree of elements as returned by get_learnpath_tree()
+ * @param   integer     Level of recursivity we have reached
+ * @param   integer     Counter of elements already displayed
+ * @author  Yannick Warnier <yannick.warnier@dokeos.com>
+ * @note : forced display because of display_addedresource_link_in_learnpath behaviour (outputing a string would be better)
+ **/
+function get_tracking_table($learnpath_id, $user_id, $parent_item_id = 0, $tree = false, $level = 0, $counter = 0)
+{
+	$tbl_learnpath_chapter = Database :: get_course_learnpath_chapter_table();
+	$tbl_learnpath_item = Database :: get_course_learnpath_item_table();
+	$tbl_learnpath_user = Database :: get_course_learnpath_user_table();
+	//$mytable = '';
+	$include_chapters = true;
+
+	if (!is_array($tree))
+	{
+		//get a tree of the current learnpath elements
+		$tree = get_learnpath_tree($learnpath_id);
+	}
+	foreach ($tree[$parent_item_id] as $order => $elem)
+	{
+		if (($counter % 2) == 0)
+		{
+			$oddclass = 'row_odd';
+		}
+		else
+		{
+			$oddclass = 'row_even';
+		}
+
+		if ($elem['type'] == 'chapter')
+		{
+			if ($include_chapters === true)
+			{
+				//$mytable .= "<tr class='$oddclass'><td colspan = '3'>".str_repeat('&nbsp;',$level*2+2).$elem['chapter_name']."</td></tr>\n";
+				echo "<tr class='$oddclass'><td colspan = '3'>".str_repeat('&nbsp;', $level * 2 + 2).$elem['chapter_name']."</td></tr>\n";
+			}
+			$counter ++;
+			//$mytable .= get_tracking_table($learnpath_id, $user_id, $elem['id'], $tree, $level + 1, $counter );
+			get_tracking_table($learnpath_id, $user_id, $elem['id'], $tree, $level +1, $counter);
+
+		}
+		elseif ($elem['type'] == 'item')
+		{
+
+			$sql = "SELECT * FROM $tbl_learnpath_user "."WHERE user_id = $user_id "."AND lp_id = $learnpath_id "."AND learnpath_item_id = ".$elem['id'];
+			$res = Database::query($sql, __FILE__, __LINE__);
+			$myrow = mysql_fetch_array($res);
+
+			if (($myrow['status'] == 'completed') || ($myrow['status'] == 'passed'))
+			{
+				$color = 'blue';
+				$statusmessage = get_lang('Complete');
+			}
+			else
+			{
+				$color = 'black';
+				$statusmessage = get_lang('Incomplete');
+			}
+
+			$link = get_addedresource_link_in_learnpath($elem['item_type'], $elem['id'], $elem['item_id']);
+			//$link = display_addedresource_link_in_learnpath($elem['item_type'], $elem['id'], $row['status'], $elem['item_id'], 'player', 'none');
+
+			//$mytable .= "<tr class='$oddclass'>"
+			echo "<tr class='$oddclass'>"."<td class='mystatus'>".str_repeat("&nbsp;", $level * 2 + 2);
+			//."<a href='$link?SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9' target='toc'>hop</a>"
+			display_addedresource_link_in_learnpath($elem['item_type'], $elem['ref'], $myrow['status'], $elem['id'], 'player', 'wrap');
+			//we should also add the total score here
+			echo "<td>"."<font color='$color'><div class='mystatus'>".$statusmessage."</div></font>"."</td>"."<td>"."<div class='mystatus' align='center'>". ($myrow['score'] == 0 ? '-' : $myrow['score'])."</div>"."</td>"."</tr>\n";
+			$counter ++;
+		}
+	}
+	//return $mytable;
+	return true;
+}
+
+/**
+ * This function returns false if there is at least one item in the path
+ * @param	Learnpath ID
  * @return	boolean	True if nothing was found, false otherwise
- */
-function is_empty($id)
-{
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-
-	$sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id=$id ORDER BY display_order ASC";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$num_modules = mysql_num_rows($result);
-	$empty = true;
-
-	if ($num_modules != 0)
-	{
-		while ($row = mysql_fetch_array($result))
-		{
-
-			$num_items = 0;
-			$parent_item_id = $row['id'];
-			$sql2 = "SELECT * FROM $tbl_learnpath_item WHERE (parent_item_id=$parent_item_id) ORDER BY display_order ASC";
-			$result2 = Database::query($sql2, __FILE__, __LINE__);
-			$num_items = mysql_num_rows($result2);
-			if ($num_items > 0)
-			{
-				$empty = false;
-			}
-
-		}
-	}
-
-	return ($empty);
-
-}
-
-/**
+ */
+function is_empty($id)
+{
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+
+	$sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id=$id ORDER BY display_order ASC";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$num_modules = mysql_num_rows($result);
+	$empty = true;
+
+	if ($num_modules != 0)
+	{
+		while ($row = mysql_fetch_array($result))
+		{
+
+			$num_items = 0;
+			$parent_item_id = $row['id'];
+			$sql2 = "SELECT * FROM $tbl_learnpath_item WHERE (parent_item_id=$parent_item_id) ORDER BY display_order ASC";
+			$result2 = Database::query($sql2, __FILE__, __LINE__);
+			$num_items = mysql_num_rows($result2);
+			if ($num_items > 0)
+			{
+				$empty = false;
+			}
+
+		}
+	}
+
+	return ($empty);
+
+}
+
+/**
  * This function writes $content to $filename
- * @param	string	Destination filename
- * @param	string	Learnpath name
- * @param	integer	Learnpath ID
- * @param	string	Content to write
+ * @param	string	Destination filename
+ * @param	string	Learnpath name
+ * @param	integer	Learnpath ID
+ * @param	string	Content to write
  * @return	void
- */
-function exporttofile($filename, $LPname, $LPid, $content)
-{
-
-	global $circle1_files; //this keeps all the files which are exported [0]:filename [1]:LP name
-	//the $circle1_files variable is going to be used to a deep extent in the imsmanifest.xml
-	global $expdir;
-
-	if (!$handle = fopen($expdir.'/'.$filename, 'w'))
-	{
-		echo "Cannot open file ($filename)";
-	}
-	if (fwrite($handle, $content) === FALSE)
-	{
-		echo "Cannot write to file ($filename)";
-		exit;
-	}
-	fclose($handle);
-
-	$circle1_files[0][] = $filename;
-	$circle1_files[1][] = $LPname;
-	$circle1_files[2][] = $LPid;
-
-}
-
-/**
- * This function exports the given Dokeos test
- * @param	integer	Test ID
- * @return string 	The test itself as an HTML string
- */
-function export_exercise($item_id)
-{
-
-	global $expdir, $_course, $_configuration, $_SESSION, $_SERVER, $language_interface, $langExerciseNotFound, $langQuestion, $langOk;
-
-	$exerciseId = $item_id;
-
-	require_once ('../exercice/exercise.class.php');
-	require_once ('../exercice/question.class.php');
-	require_once ('../exercice/answer.class.php');
-	require_once ('../exercice/exercise.lib.php');
-
-	// answer types
-	define('UNIQUE_ANSWER', 1);
-	define('MULTIPLE_ANSWER', 2);
-	define('FILL_IN_BLANKS', 3);
-	define('MATCHING', 4);
-	define('FREE_ANSWER', 5);
-
-	include_once (api_get_path(LIBRARY_PATH).'/text.lib.php');
-
-	$TBL_EXERCISES = Database :: get_course_table(TABLE_QUIZ_TEST);
-
-	/*******************************/
-	/* Clears the exercise session */
-	/*******************************/
-	if (isset ($_SESSION['objExercise']))
-	{
-		api_session_unregister('objExercise');
-		unset ($objExercise);
-	}
-	if (isset ($_SESSION['objQuestion']))
-	{
-		api_session_unregister('objQuestion');
-		unset ($objQuestion);
-	}
-	if (isset ($_SESSION['objAnswer']))
-	{
-		api_session_unregister('objAnswer');
-		unset ($objAnswer);
-	}
-	if (isset ($_SESSION['questionList']))
-	{
-		api_session_unregister('questionList');
-		unset ($questionList);
-	}
-	if (isset ($_SESSION['exerciseResult']))
-	{
-		api_session_unregister('exerciseResult');
-		unset ($exerciseResult);
-	}
-
-	// if the object is not in the session
-	if (!isset ($_SESSION['objExercise']))
-	{
-		// construction of Exercise
-		$objExercise = new Exercise();
-
-		$sql = "SELECT title,description,sound,type,random,active FROM $TBL_EXERCISES WHERE id='$exerciseId'";
-		// if the specified exercise doesn't exist or is disabled
-		if (!$objExercise->read($exerciseId) || (!$objExercise->selectStatus() && !$is_allowedToEdit && ($origin != 'learnpath')))
-		{
-			die($langExerciseNotFound);
-		}
-
-		// saves the object into the session
-		api_session_register('objExercise');
-	}
-
-	$exerciseTitle = $objExercise->selectTitle();
-	$exerciseDescription = $objExercise->selectDescription();
-	$exerciseSound = $objExercise->selectSound();
-	$randomQuestions = $objExercise->isRandom();
-	$exerciseType = $objExercise->selectType();
-
-	if (!isset ($_SESSION['questionList']))
-	{
-		// selects the list of question ID
-		$questionList = $randomQuestions ? $objExercise->selectRandomList() : $objExercise->selectQuestionList();
-
-		// saves the question list into the session
-		api_session_register('questionList');
-	}
-
-	$nbrQuestions = sizeof($questionList);
-
-	// if questionNum comes from POST and not from GET
-	if (!$questionNum || $_POST['questionNum'])
-	{
-		// only used for sequential exercises (see $exerciseType)
-		if (!$questionNum)
-		{
-			$questionNum = 1;
-		}
-		else
-		{
-			$questionNum ++;
-		}
-	}
-
-	$exerciseTitle = api_parse_tex($exerciseTitle);
-
-	$test .= "<h3>".$exerciseTitle."</h3>";
-
-	if (!empty ($exerciseSound))
-	{
-		$test .= "<a href=\"../document/download.php?doc_url=%2Faudio%2F".$exerciseSound."\"&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9 target=\"_blank\"><img src=\"../img/sound.gif\" border=\"0\" align=\"absmiddle\" alt=".get_lang("Sound")."\" /></a>";
-	}
-
-	$exerciseDescription = api_parse_tex($exerciseDescription);
-
-	// --------- writing the .js file with to check the correct answers begin -----------------------
-	$scriptfilename = "Exercice".$item_id.".js";
-	$s = "<script type=\"text/javascript\" src='../js/".$scriptfilename."'></script>";
-	$test .= $s;
-
-	$content = "function evaluate() {
-		alert('Test evaluated.');
-		}
-		";
-
-	if (!$handle = fopen($expdir.'/js/'.$scriptfilename, 'w'))
-	{
-		echo "Cannot open file ($scriptfilename)";
-	}
-	if (fwrite($handle, $content) === FALSE)
-	{
-		echo "Cannot write to file ($filename)";
-		exit;
-	}
-	fclose($handle);
-	// --------- writing the .js file with to check the correct answers end -----------------------
-
-	$s = "
-		<p>$exerciseDescription</p>
-		<table width='100%' border='0' cellpadding='1' cellspacing='0'>
-		 <form method='post' action=''><input type=\"hidden\" name=\"SQMSESSID\" value=\"36812c2dea7d8d6e708d5e6a2f09b0b9\" />
-		 <input type='hidden' name='formSent' value='1' />
-		 <input type='hidden' name='exerciseType' value='".$exerciseType."' />
-		 <input type='hidden' name='questionNum' value='".$questionNum."' />
-		 <input type='hidden' name='nbrQuestions' value='".$nbrQuestions."' />
-		 <tr>
-		  <td>
-		  <table width='100%' cellpadding='4' cellspacing='2' border='0'>";
-
-	$exerciseType = 1; //so to list all questions in one page
-	$test .= $s;
-
-	$i = 0;
-
-	foreach ($questionList as $questionId) {
-		$i ++;
-
-		// for sequential exercises
-		if ($exerciseType == 2) {
-			// if it is not the right question, goes to the next loop iteration
-			if ($questionNum != $i)
-			{
-				continue;
-			} else {
-				// if the user has already answered this question
-				if (isset ($exerciseResult[$questionId])) {
-					// construction of the Question object
-					$objQuestionTmp = new Question();
-
-					// reads question informations
-					$objQuestionTmp->read($questionId);
-
-					$questionName = $objQuestionTmp->selectTitle();
-
-					// destruction of the Question object
-					unset ($objQuestionTmp);
-
-					$test .= '<tr><td>'.get_lang("AlreadyAnswered").' &quot;'.$questionName.'&quot;</td></tr>';
-
-					break;
-				}
-			}
-		}
-
-		echo $s = "<tr bgcolor='#e6e6e6'><td valign='top' colspan='2'>".get_lang('Question')." ";
-		//Call the showQuestion() function from exercise.lib.php. This basically displays the question in a table
-		$test .= showQuestion($questionId, false, 'export', $i, $nbrQuestions);
-
-	} // end foreach()
-
-	$s = "</table></td></tr><tr><td><br/><input type='button' value='".$langOk."' onClick=\"javascript:evaluate();alert('Evaluated.');\">";
-	$s .= "</td></tr></form></table>";
-	$s .= "<script type='text/javascript'> loadPage(); </script>";
-	$b = 2;
-	$test .= $s;
-	return ($test);
-}
-
-/**
- * This function exports the given item
- * @param	integer	Id from learnpath_items table
- * @param	integer	Item id
- * @param	string	Itm type
+ */
+function exporttofile($filename, $LPname, $LPid, $content)
+{
+
+	global $circle1_files; //this keeps all the files which are exported [0]:filename [1]:LP name
+	//the $circle1_files variable is going to be used to a deep extent in the imsmanifest.xml
+	global $expdir;
+
+	if (!$handle = fopen($expdir.'/'.$filename, 'w'))
+	{
+		echo "Cannot open file ($filename)";
+	}
+	if (fwrite($handle, $content) === FALSE)
+	{
+		echo "Cannot write to file ($filename)";
+		exit;
+	}
+	fclose($handle);
+
+	$circle1_files[0][] = $filename;
+	$circle1_files[1][] = $LPname;
+	$circle1_files[2][] = $LPid;
+
+}
+
+/**
+ * This function exports the given Dokeos test
+ * @param	integer	Test ID
+ * @return string 	The test itself as an HTML string
+ */
+function export_exercise($item_id)
+{
+
+	global $expdir, $_course, $_configuration, $_SESSION, $_SERVER, $language_interface, $langExerciseNotFound, $langQuestion, $langOk;
+
+	$exerciseId = $item_id;
+
+	require_once ('../exercice/exercise.class.php');
+	require_once ('../exercice/question.class.php');
+	require_once ('../exercice/answer.class.php');
+	require_once ('../exercice/exercise.lib.php');
+
+	// answer types
+	define('UNIQUE_ANSWER', 1);
+	define('MULTIPLE_ANSWER', 2);
+	define('FILL_IN_BLANKS', 3);
+	define('MATCHING', 4);
+	define('FREE_ANSWER', 5);
+
+	include_once (api_get_path(LIBRARY_PATH).'/text.lib.php');
+
+	$TBL_EXERCISES = Database :: get_course_table(TABLE_QUIZ_TEST);
+
+	/*******************************/
+	/* Clears the exercise session */
+	/*******************************/
+	if (isset ($_SESSION['objExercise']))
+	{
+		api_session_unregister('objExercise');
+		unset ($objExercise);
+	}
+	if (isset ($_SESSION['objQuestion']))
+	{
+		api_session_unregister('objQuestion');
+		unset ($objQuestion);
+	}
+	if (isset ($_SESSION['objAnswer']))
+	{
+		api_session_unregister('objAnswer');
+		unset ($objAnswer);
+	}
+	if (isset ($_SESSION['questionList']))
+	{
+		api_session_unregister('questionList');
+		unset ($questionList);
+	}
+	if (isset ($_SESSION['exerciseResult']))
+	{
+		api_session_unregister('exerciseResult');
+		unset ($exerciseResult);
+	}
+
+	// if the object is not in the session
+	if (!isset ($_SESSION['objExercise']))
+	{
+		// construction of Exercise
+		$objExercise = new Exercise();
+
+		$sql = "SELECT title,description,sound,type,random,active FROM $TBL_EXERCISES WHERE id='$exerciseId'";
+		// if the specified exercise doesn't exist or is disabled
+		if (!$objExercise->read($exerciseId) || (!$objExercise->selectStatus() && !$is_allowedToEdit && ($origin != 'learnpath')))
+		{
+			die($langExerciseNotFound);
+		}
+
+		// saves the object into the session
+		api_session_register('objExercise');
+	}
+
+	$exerciseTitle = $objExercise->selectTitle();
+	$exerciseDescription = $objExercise->selectDescription();
+	$exerciseSound = $objExercise->selectSound();
+	$randomQuestions = $objExercise->isRandom();
+	$exerciseType = $objExercise->selectType();
+
+	if (!isset ($_SESSION['questionList']))
+	{
+		// selects the list of question ID
+		$questionList = $randomQuestions ? $objExercise->selectRandomList() : $objExercise->selectQuestionList();
+
+		// saves the question list into the session
+		api_session_register('questionList');
+	}
+
+	$nbrQuestions = sizeof($questionList);
+
+	// if questionNum comes from POST and not from GET
+	if (!$questionNum || $_POST['questionNum'])
+	{
+		// only used for sequential exercises (see $exerciseType)
+		if (!$questionNum)
+		{
+			$questionNum = 1;
+		}
+		else
+		{
+			$questionNum ++;
+		}
+	}
+
+	$exerciseTitle = api_parse_tex($exerciseTitle);
+
+	$test .= "<h3>".$exerciseTitle."</h3>";
+
+	if (!empty ($exerciseSound))
+	{
+		$test .= "<a href=\"../document/download.php?doc_url=%2Faudio%2F".$exerciseSound."\"&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9 target=\"_blank\"><img src=\"../img/sound.gif\" border=\"0\" align=\"absmiddle\" alt=".get_lang("Sound")."\" /></a>";
+	}
+
+	$exerciseDescription = api_parse_tex($exerciseDescription);
+
+	// --------- writing the .js file with to check the correct answers begin -----------------------
+	$scriptfilename = "Exercice".$item_id.".js";
+	$s = "<script type=\"text/javascript\" src='../js/".$scriptfilename."'></script>";
+	$test .= $s;
+
+	$content = "function evaluate() {
+		alert('Test evaluated.');
+		}
+		";
+
+	if (!$handle = fopen($expdir.'/js/'.$scriptfilename, 'w'))
+	{
+		echo "Cannot open file ($scriptfilename)";
+	}
+	if (fwrite($handle, $content) === FALSE)
+	{
+		echo "Cannot write to file ($filename)";
+		exit;
+	}
+	fclose($handle);
+	// --------- writing the .js file with to check the correct answers end -----------------------
+
+	$s = "
+		<p>$exerciseDescription</p>
+		<table width='100%' border='0' cellpadding='1' cellspacing='0'>
+		 <form method='post' action=''><input type=\"hidden\" name=\"SQMSESSID\" value=\"36812c2dea7d8d6e708d5e6a2f09b0b9\" />
+		 <input type='hidden' name='formSent' value='1' />
+		 <input type='hidden' name='exerciseType' value='".$exerciseType."' />
+		 <input type='hidden' name='questionNum' value='".$questionNum."' />
+		 <input type='hidden' name='nbrQuestions' value='".$nbrQuestions."' />
+		 <tr>
+		  <td>
+		  <table width='100%' cellpadding='4' cellspacing='2' border='0'>";
+
+	$exerciseType = 1; //so to list all questions in one page
+	$test .= $s;
+
+	$i = 0;
+
+	foreach ($questionList as $questionId) {
+		$i ++;
+
+		// for sequential exercises
+		if ($exerciseType == 2) {
+			// if it is not the right question, goes to the next loop iteration
+			if ($questionNum != $i)
+			{
+				continue;
+			} else {
+				// if the user has already answered this question
+				if (isset ($exerciseResult[$questionId])) {
+					// construction of the Question object
+					$objQuestionTmp = new Question();
+
+					// reads question informations
+					$objQuestionTmp->read($questionId);
+
+					$questionName = $objQuestionTmp->selectTitle();
+
+					// destruction of the Question object
+					unset ($objQuestionTmp);
+
+					$test .= '<tr><td>'.get_lang("AlreadyAnswered").' &quot;'.$questionName.'&quot;</td></tr>';
+
+					break;
+				}
+			}
+		}
+
+		echo $s = "<tr bgcolor='#e6e6e6'><td valign='top' colspan='2'>".get_lang('Question')." ";
+		//Call the showQuestion() function from exercise.lib.php. This basically displays the question in a table
+		$test .= showQuestion($questionId, false, 'export', $i, $nbrQuestions);
+
+	} // end foreach()
+
+	$s = "</table></td></tr><tr><td><br/><input type='button' value='".$langOk."' onClick=\"javascript:evaluate();alert('Evaluated.');\">";
+	$s .= "</td></tr></form></table>";
+	$s .= "<script type='text/javascript'> loadPage(); </script>";
+	$b = 2;
+	$test .= $s;
+	return ($test);
+}
+
+/**
+ * This function exports the given item
+ * @param	integer	Id from learnpath_items table
+ * @param	integer	Item id
+ * @param	string	Itm type
  * @param	boolean	Shall the SCORM communications features be added? (true). Default: false.
- * @return	void (outputs a zip file)
+ * @return	void (outputs a zip file)
  * @todo	Try using the SCORM communications addition (adding a button and several javascript calls to the SCORM API) elsewhere than just in the export feature, so it doesn't look like an incoherent feature
- */
-
-function exportitem($id, $item_id, $item_type, $add_scorm_communications = false)
-{
-
-	global $circle1_files, $expdir, $_course, $_SESSION, $GLOBALS;
-	global $timeNoSecFormat, $dateFormatLong, $language_interface, $langPubl, $langDone, $langThisCourseDescriptionIsEmpty, $lang_course_description, $lang_introduction_text, $_cid, $langHotPotatoesFinished, $lang_author, $lang_date, $lang_groups, $lang_users, $lang_ass, $lang_dropbox, $test, $langQuestion;
-
-	//	$_course=$_SESSION['course'];
-	require_once (api_get_path(LIBRARY_PATH)."database.lib.php");
-	//$tbl_learnpath_item     = Database::get_course_learnpath_item_table();
-
-	include_once ('exercise.class.php');
-	include_once ('question.class.php');
-	include_once ('answer.class.php');
-	include_once ('exercise.lib.php');
-
-	include_once ('../lang/english/announcements.inc.php'); //this line is here only for $langPubl in announcements
-	include_once ("../lang/".$language_interface."/announcements.inc.php"); //this line is here only for $langPubl in announcements
-	include_once ('../lang/english/course_description.inc.php'); //this line is here only for $langThisCourseDescriptionIsEmpty
-	include_once ("../lang/".$language_interface."/course_description.inc.php"); //				 -||-
-	include_once ('../lang/english/resourcelinker.inc.php');
-	include_once ("../lang/".$language_interface."/resourcelinker.inc.php");
-	include_once ('../lang/english/learnpath.inc.php');
-	include_once ("../lang/".$language_interface."/learnpath.inc.php");
-	include_once ('../lang/english/exercice.inc.php');
-	include_once ("../lang/".$language_interface."/exercice.inc.php");
-
-	include_once (api_get_path(LIBRARY_PATH).'text.lib.php');
+ */
+
+function exportitem($id, $item_id, $item_type, $add_scorm_communications = false)
+{
+
+	global $circle1_files, $expdir, $_course, $_SESSION, $GLOBALS;
+	global $timeNoSecFormat, $dateFormatLong, $language_interface, $langPubl, $langDone, $langThisCourseDescriptionIsEmpty, $lang_course_description, $lang_introduction_text, $_cid, $langHotPotatoesFinished, $lang_author, $lang_date, $lang_groups, $lang_users, $lang_ass, $lang_dropbox, $test, $langQuestion;
+
+	//	$_course=$_SESSION['course'];
+	require_once (api_get_path(LIBRARY_PATH)."database.lib.php");
+	//$tbl_learnpath_item     = Database::get_course_learnpath_item_table();
+
+	include_once ('exercise.class.php');
+	include_once ('question.class.php');
+	include_once ('answer.class.php');
+	include_once ('exercise.lib.php');
+
+	include_once ('../lang/english/announcements.inc.php'); //this line is here only for $langPubl in announcements
+	include_once ("../lang/".$language_interface."/announcements.inc.php"); //this line is here only for $langPubl in announcements
+	include_once ('../lang/english/course_description.inc.php'); //this line is here only for $langThisCourseDescriptionIsEmpty
+	include_once ("../lang/".$language_interface."/course_description.inc.php"); //				 -||-
+	include_once ('../lang/english/resourcelinker.inc.php');
+	include_once ("../lang/".$language_interface."/resourcelinker.inc.php");
+	include_once ('../lang/english/learnpath.inc.php');
+	include_once ("../lang/".$language_interface."/learnpath.inc.php");
+	include_once ('../lang/english/exercice.inc.php');
+	include_once ("../lang/".$language_interface."/exercice.inc.php");
+
+	include_once (api_get_path(LIBRARY_PATH).'text.lib.php');
 	include_once ("../resourcelinker/resourcelinker.inc.php");
-
-	$LPname = display_addedresource_link_in_learnpath($item_type, $item_id, '', $id, 'builder', 'nolink');
-
+
+	$LPname = display_addedresource_link_in_learnpath($item_type, $item_id, '', $id, 'builder', 'nolink');
+
 	$expcontent = "<!--
-		This is an exported file from Dokeos Learning Path belonging to a Scorm compliant content package.
-		Do not modify or replace individually.
-
-		Export module author : Denes Nagy <darkden@evk.bke.hu>
-
-		-->
-
-		";
-	//files needed for communicating with the scos
-	$scocomfiles = "<script type='text/javascript' src='../js/APIWrapper.js'></script>"."<script type='text/javascript' src='../js/SCOFunctions.js'></script>";
-	$expcontent .= '<html><head><link rel="stylesheet" href="../css/default.css" type="text/css" media="screen,projection" />'.$scocomfiles.'</head><body>';
-
-	$donebutton .= "<script type='text/javascript'>
-			/* <![CDATA[ */
-			loadPage();
-			var   studentName = '!';
-			var   lmsStudentName = doLMSGetValue(  'cmi.core.student_name' );
-			if ( lmsStudentName  != '' )
-			{
-			   studentName = ' ' + lmsStudentName +   '!';
-			}
-			/* ]]> */
-			</script>
-			<br /><br />
-			<form><input type=\"hidden\" name=\"SQMSESSID\" value=\"36812c2dea7d8d6e708d5e6a2f09b0b9\" />
-				<table cols='3'	width='100%' align='center'>
-					<tr>
-					<td	align='middle'><input type = 'button' value	= '  ".$langDone."  ' onclick = \"doQuit('completed')\" id='button2' name='button2'></td>
-					</tr>
-				</table>
-			</form>";
-
+		This is an exported file from Dokeos Learning Path belonging to a Scorm compliant content package.
+		Do not modify or replace individually.
+
+		Export module author : Denes Nagy <darkden@evk.bke.hu>
+
+		-->
+
+		";
+	//files needed for communicating with the scos
+	$scocomfiles = "<script type='text/javascript' src='../js/APIWrapper.js'></script>"."<script type='text/javascript' src='../js/SCOFunctions.js'></script>";
+	$expcontent .= '<html><head><link rel="stylesheet" href="../css/default.css" type="text/css" media="screen,projection" />'.$scocomfiles.'</head><body>';
+
+	$donebutton .= "<script type='text/javascript'>
+			/* <![CDATA[ */
+			loadPage();
+			var   studentName = '!';
+			var   lmsStudentName = doLMSGetValue(  'cmi.core.student_name' );
+			if ( lmsStudentName  != '' )
+			{
+			   studentName = ' ' + lmsStudentName +   '!';
+			}
+			/* ]]> */
+			</script>
+			<br /><br />
+			<form><input type=\"hidden\" name=\"SQMSESSID\" value=\"36812c2dea7d8d6e708d5e6a2f09b0b9\" />
+				<table cols='3'	width='100%' align='center'>
+					<tr>
+					<td	align='middle'><input type = 'button' value	= '  ".$langDone."  ' onclick = \"doQuit('completed')\" id='button2' name='button2'></td>
+					</tr>
+				</table>
+			</form>";
+
 	/**
-	 * switch between the different element types, namely:
-	 * - Agenda
-	 * - Ad_Valvas
-	 * - Course_description
-	 * - Document
-	 * - Introduction_text
-	 * - HotPotatoes
-	 * - Exercise
-	 * - Post
-	 * - Forum						]
-	 * - Thread					]
-	 * - Dropbox				]
-	 * - Assignments	]  Theses elements are all replaced by a simple message in the exported document
-	 * - Groups					]
-	 * - Users						]
+	 * switch between the different element types, namely:
+	 * - Agenda
+	 * - Ad_Valvas
+	 * - Course_description
+	 * - Document
+	 * - Introduction_text
+	 * - HotPotatoes
+	 * - Exercise
+	 * - Post
+	 * - Forum						]
+	 * - Thread					]
+	 * - Dropbox				]
+	 * - Assignments	]  Theses elements are all replaced by a simple message in the exported document
+	 * - Groups					]
+	 * - Users						]
 	 * - Link _self
-	 * - Link _blank
-	 */
-	switch ($item_type)
-	{
-
-		//------------------------AGENDA BEGIN-------------------
-		case "Agenda" :
-			//1 Get agenda event data from the database table
-			$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA);
-			$sql = "SELECT * FROM ".$TABLEAGENDA." where (id=$item_id)";
-			$result = Database::query($sql, __FILE__, __LINE__);
-
-			//2 Prepare table output
-			$expcontent .= "<table class=\"data_table\" >";
-			$barreMois = "";
-
-			//3 For each event corresponding to this agenda, do the following:
-			while ($myrow = mysql_fetch_array($result))
-			{
-				//3.1 Make the blue month bar appear only once.
-				if ($barreMois != date("m", strtotime($myrow["start_date"])))
-				{
-					//3.1.1 Update the check value for the month bar
-					$barreMois = date("m", strtotime($myrow["start_date"]));
-					//3.1.2	Display the month bar
-					$expcontent .= "<tr><td id=\"title\" colspan=\"2\" class=\"month\" valign=\"top\">".api_ucfirst(format_locale_date("%B %Y", strtotime($myrow["start_date"])))."</td></tr>";
-				}
-
-				//3.2 Display the agenda items (of this month): the date, hour and title
-				$db_date = (int) date(d, strtotime($myrow["start_date"]));
-				if ($_GET["day"] <> $db_date)
-				{ //3.2.1.a If the day given in the URL (might not be set) is different from this element's day, use style 'data'
-					$expcontent .= "<tr><td class=\"data\" colspan='2'>";
-				}
-				else
-				{ //3.2.1.b Else (same day) use style 'datanow'
-					$expcontent .= "<tr><td class=\"datanow\" colspan='2'>";
-				}
-				//3.2.2 Mark an anchor for this date
-				$expcontent .= "<a name=\"".(int) date(d, strtotime($myrow["start_date"]))."\"></a>"; // anchoring
-				//3.2.3 Write the date and time of this event to the export string
-				$expcontent .= api_ucfirst(format_locale_date($dateFormatLong, strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
-				$expcontent .= api_ucfirst(strftime($timeNoSecFormat, strtotime($myrow["start_time"])))."";
-				//3.2.4 If a duration is set, write it, otherwise ignore
-				if ($myrow["duration"] == "")
-				{
-					$expcontent .= "<br />";
-				}
-				else
-				{
-					$expcontent .= " / ".$lang_lasting." ".$myrow["duration"]."<br/>";
-				}
-				//3.2.5 Write the title
-				$expcontent .= $myrow["title"];
-				$expcontent .= "</td></tr>";
-				//3.2.6 Prepare the content of the agenda item
-				$content = $myrow["content"];
-				//3.2.7 Make clickable???
-				$content = make_clickable($content);
-				$content = api_parse_tex($content);
-				//3.2.8 Write the prepared content to the export string
-				$expcontent .= "<tr><td class=\"text\" colspan='2'>";
-				$expcontent .= $content;
-				$expcontent .= "</td></tr>";
-
-				// displaying the agenda item of this month: the added resources
-				//     this part is not included into LP export
-				/*if (check_added_resources("Agenda", $myrow["id"]))
-				{
-				$content.= "<tr><td colspan='2'>";
-				$content.= "<i>".get_lang('AddedResources')."</i><br/>";
-				display_added_resources("Agenda", $myrow["id"]);
-				$content.= "</td></tr>";
-				}*/
-
-			}
-			//4 Finish the export string
-			$expcontent .= "<tr></table>";
-
-			break;
-			//------------------------ANNOUNCEMENT BEGIN-------------------
-		case "Ad_Valvas" :
-			//1 Get the announcement data from the database
-			$tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-			$sql = "SELECT * FROM $tbl_announcement where id='$item_id'";
-			$result = Database::query($sql, __FILE__, __LINE__);
-
-			//2 Initialise export string
-			$expcontent .= "<table class=\"data_table\">";
-
-			//3 For each announcement matching the query
-			while ($myrow = mysql_fetch_array($result))
-			{
-				//3.1 Get the __ field data
-				$content = $myrow[1];
-				//$content = nl2br($content);
-				//3.2 Prepare the data for export
-				$content = make_clickable($content);
-				$content = api_parse_tex($content);
-
-				//3.3 Get a UNIX(?<-mktime) Timestamp of the end_date for this announcement
-				$last_post_datetime = $myrow['end_date']; // post time format  datetime de mysql
-				list ($last_post_date, $last_post_time) = split(" ", $last_post_datetime);
-				list ($year, $month, $day) = explode("-", $last_post_date);
-				list ($hour, $min) = explode(":", $last_post_time);
-				$announceDate = mktime($hour, $min, 0, $month, $day, $year);
-
-				//3.4 Compare the end date to the last login date of the user (mark it in red if he has not already read it)
-				if ($announceDate > $_SESSION['user_last_login_datetime'])
-				{
-					$colorBecauseNew = " color=\"red\" ";
-				}
-				else
-				{
-					$colorBecauseNew = "  ";
-				}
-
-				//3.5 Write this content to the export string (formatted HTML array)
-				$expcontent .= "<tr>\n"."<td class=\"cell_header\">\n"."<font ".$colorBecauseNew.">".$langPubl." : ".api_ucfirst(format_locale_date($dateFormatLong, strtotime($last_post_date)))."</font>\n"."</td>\n"."</tr>\n"."<tr>\n"."<td>\n".$content."</td>\n"."</tr>\n";
-
-			} // while loop
-
-			//4 Finish the export string
-			$expcontent .= "</table>";
-
-			break;
-			//------------------------Course_description BEGIN-------------------
-		case "Course_description" :
-			//1 Get course description data from database
-			$tbl_course_description = Database :: get_course_table(TABLE_COURSE_DESCRIPTION);
-			$result = Database::query("SELECT id, title, content FROM ".$tbl_course_description." ORDER BY id", __FILE__, __LINE__);
-
-			//2 Check this element
-			if (mysql_num_rows($result))
-			{
-				//2.a This course has one (or more) description in the database
-				$expcontent .= "<hr noshade=\"noshade\" size=\"1\" />";
-				//2.a.1 For each description available for this course
-				while ($row = mysql_fetch_array($result))
-				{
-					//2.a.1.1 Write title to export string
-					$expcontent .= "<h4>".$row['title']."</h4>";
-					//2.a.1.2 Prepare content
-					$content = make_clickable(nl2br($row['content']));
-					$content = api_parse_tex($content);
-					//2.a.1.3 Write content to the export string
-					$expcontent .= $content;
-				}
-			}
-			else
-			{
-				//2.b This course has no description available
-				$expcontent .= "<br /><h4>$langThisCourseDescriptionIsEmpty</h4>";
-			}
-
-			break;
-			//------------------------DOCUMENT BEGIN-------------------
-		case "Document" :
-			//1 Get the document data from the database
-			$tbl_document = Database::get_course_table(TABLE_DOCUMENT);
-			$sql_query = "SELECT * FROM $tbl_document WHERE id=$item_id";
-			$sql_result = Database::query($sql_query, __FILE__, __LINE__);
-			$myrow = mysql_fetch_array($sql_result);
-			//2 Get the origin path of the document to treat it internally
-			$orig = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$myrow["path"];
-			//3 Make some kind of strange transformation to get the destination filepath ???
-			$pathname = explode("/", $myrow["path"]);
-			$last = count($pathname) - 1;
-			$filename = 'data/'.$filename.$pathname[$last];
-			$copyneeded = true;
-
+	 * - Link _blank
+	 */
+	switch ($item_type)
+	{
+
+		//------------------------AGENDA BEGIN-------------------
+		case "Agenda" :
+			//1 Get agenda event data from the database table
+			$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA);
+			$sql = "SELECT * FROM ".$TABLEAGENDA." where (id=$item_id)";
+			$result = Database::query($sql, __FILE__, __LINE__);
+
+			//2 Prepare table output
+			$expcontent .= "<table class=\"data_table\" >";
+			$barreMois = "";
+
+			//3 For each event corresponding to this agenda, do the following:
+			while ($myrow = mysql_fetch_array($result))
+			{
+				//3.1 Make the blue month bar appear only once.
+				if ($barreMois != date("m", strtotime($myrow["start_date"])))
+				{
+					//3.1.1 Update the check value for the month bar
+					$barreMois = date("m", strtotime($myrow["start_date"]));
+					//3.1.2	Display the month bar
+					$expcontent .= "<tr><td id=\"title\" colspan=\"2\" class=\"month\" valign=\"top\">".api_ucfirst(format_locale_date("%B %Y", strtotime($myrow["start_date"])))."</td></tr>";
+				}
+
+				//3.2 Display the agenda items (of this month): the date, hour and title
+				$db_date = (int) date(d, strtotime($myrow["start_date"]));
+				if ($_GET["day"] <> $db_date)
+				{ //3.2.1.a If the day given in the URL (might not be set) is different from this element's day, use style 'data'
+					$expcontent .= "<tr><td class=\"data\" colspan='2'>";
+				}
+				else
+				{ //3.2.1.b Else (same day) use style 'datanow'
+					$expcontent .= "<tr><td class=\"datanow\" colspan='2'>";
+				}
+				//3.2.2 Mark an anchor for this date
+				$expcontent .= "<a name=\"".(int) date(d, strtotime($myrow["start_date"]))."\"></a>"; // anchoring
+				//3.2.3 Write the date and time of this event to the export string
+				$expcontent .= api_ucfirst(format_locale_date($dateFormatLong, strtotime($myrow["start_date"])))."&nbsp;&nbsp;&nbsp;";
+				$expcontent .= api_ucfirst(strftime($timeNoSecFormat, strtotime($myrow["start_time"])))."";
+				//3.2.4 If a duration is set, write it, otherwise ignore
+				if ($myrow["duration"] == "")
+				{
+					$expcontent .= "<br />";
+				}
+				else
+				{
+					$expcontent .= " / ".$lang_lasting." ".$myrow["duration"]."<br/>";
+				}
+				//3.2.5 Write the title
+				$expcontent .= $myrow["title"];
+				$expcontent .= "</td></tr>";
+				//3.2.6 Prepare the content of the agenda item
+				$content = $myrow["content"];
+				//3.2.7 Make clickable???
+				$content = make_clickable($content);
+				$content = api_parse_tex($content);
+				//3.2.8 Write the prepared content to the export string
+				$expcontent .= "<tr><td class=\"text\" colspan='2'>";
+				$expcontent .= $content;
+				$expcontent .= "</td></tr>";
+
+				// displaying the agenda item of this month: the added resources
+				//     this part is not included into LP export
+				/*if (check_added_resources("Agenda", $myrow["id"]))
+				{
+				$content.= "<tr><td colspan='2'>";
+				$content.= "<i>".get_lang('AddedResources')."</i><br/>";
+				display_added_resources("Agenda", $myrow["id"]);
+				$content.= "</td></tr>";
+				}*/
+
+			}
+			//4 Finish the export string
+			$expcontent .= "<tr></table>";
+
+			break;
+			//------------------------ANNOUNCEMENT BEGIN-------------------
+		case "Ad_Valvas" :
+			//1 Get the announcement data from the database
+			$tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
+			$sql = "SELECT * FROM $tbl_announcement where id='$item_id'";
+			$result = Database::query($sql, __FILE__, __LINE__);
+
+			//2 Initialise export string
+			$expcontent .= "<table class=\"data_table\">";
+
+			//3 For each announcement matching the query
+			while ($myrow = mysql_fetch_array($result))
+			{
+				//3.1 Get the __ field data
+				$content = $myrow[1];
+				//$content = nl2br($content);
+				//3.2 Prepare the data for export
+				$content = make_clickable($content);
+				$content = api_parse_tex($content);
+
+				//3.3 Get a UNIX(?<-mktime) Timestamp of the end_date for this announcement
+				$last_post_datetime = $myrow['end_date']; // post time format  datetime de mysql
+				list ($last_post_date, $last_post_time) = split(" ", $last_post_datetime);
+				list ($year, $month, $day) = explode("-", $last_post_date);
+				list ($hour, $min) = explode(":", $last_post_time);
+				$announceDate = mktime($hour, $min, 0, $month, $day, $year);
+
+				//3.4 Compare the end date to the last login date of the user (mark it in red if he has not already read it)
+				if ($announceDate > $_SESSION['user_last_login_datetime'])
+				{
+					$colorBecauseNew = " color=\"red\" ";
+				}
+				else
+				{
+					$colorBecauseNew = "  ";
+				}
+
+				//3.5 Write this content to the export string (formatted HTML array)
+				$expcontent .= "<tr>\n"."<td class=\"cell_header\">\n"."<font ".$colorBecauseNew.">".$langPubl." : ".api_ucfirst(format_locale_date($dateFormatLong, strtotime($last_post_date)))."</font>\n"."</td>\n"."</tr>\n"."<tr>\n"."<td>\n".$content."</td>\n"."</tr>\n";
+
+			} // while loop
+
+			//4 Finish the export string
+			$expcontent .= "</table>";
+
+			break;
+			//------------------------Course_description BEGIN-------------------
+		case "Course_description" :
+			//1 Get course description data from database
+			$tbl_course_description = Database :: get_course_table(TABLE_COURSE_DESCRIPTION);
+			$result = Database::query("SELECT id, title, content FROM ".$tbl_course_description." ORDER BY id", __FILE__, __LINE__);
+
+			//2 Check this element
+			if (mysql_num_rows($result))
+			{
+				//2.a This course has one (or more) description in the database
+				$expcontent .= "<hr noshade=\"noshade\" size=\"1\" />";
+				//2.a.1 For each description available for this course
+				while ($row = mysql_fetch_array($result))
+				{
+					//2.a.1.1 Write title to export string
+					$expcontent .= "<h4>".$row['title']."</h4>";
+					//2.a.1.2 Prepare content
+					$content = make_clickable(nl2br($row['content']));
+					$content = api_parse_tex($content);
+					//2.a.1.3 Write content to the export string
+					$expcontent .= $content;
+				}
+			}
+			else
+			{
+				//2.b This course has no description available
+				$expcontent .= "<br /><h4>$langThisCourseDescriptionIsEmpty</h4>";
+			}
+
+			break;
+			//------------------------DOCUMENT BEGIN-------------------
+		case "Document" :
+			//1 Get the document data from the database
+			$tbl_document = Database::get_course_table(TABLE_DOCUMENT);
+			$sql_query = "SELECT * FROM $tbl_document WHERE id=$item_id";
+			$sql_result = Database::query($sql_query, __FILE__, __LINE__);
+			$myrow = mysql_fetch_array($sql_result);
+			//2 Get the origin path of the document to treat it internally
+			$orig = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$myrow["path"];
+			//3 Make some kind of strange transformation to get the destination filepath ???
+			$pathname = explode("/", $myrow["path"]);
+			$last = count($pathname) - 1;
+			$filename = 'data/'.$filename.$pathname[$last];
+			$copyneeded = true;
+
 			//htm files do not need to be copied as the ok button is inserted into them,
-			//so don't copy directly
-			$extension = explode(".", $pathname[$last]);
+			//so don't copy directly
+			$extension = explode(".", $pathname[$last]);
 			//This old condition was WRONG for names like design.html.old. Instead, we now get the extension
-			// by using preg_match to match case-insensitive (probably faster than 4 conditions)
-			//if (($extension[1]=='htm') or ($extension[1]=='html') or ($extension[1]=='HTM') or ($extension[1]=='HTML')) {
-			//4 Check the file extension
-			if (preg_match('/.*(\.htm(l)?)$/i', $pathname[$last]))
-			{
-				//4.a If this file ends with ".htm(l)", we consider it's an HTML file
-				//src tag check begin
-				//we now check if there is any src attribute in htm(l) files, if yes, we have to also export
-				//the target file (swf, mp3, video,...) of that src tag
-				//In case of absolute links (http://) this is not neccessary, but makes no error.
-				//however still missing : relative links case with subdirs -> the necessary dirs are not created in the exported package
-
-				//4.a.1 Get the file contents into $file
-				$file = file_get_contents($orig);
-
-				//4.a.2 Get all the src links in this file
+			// by using preg_match to match case-insensitive (probably faster than 4 conditions)
+			//if (($extension[1]=='htm') or ($extension[1]=='html') or ($extension[1]=='HTM') or ($extension[1]=='HTML')) {
+			//4 Check the file extension
+			if (preg_match('/.*(\.htm(l)?)$/i', $pathname[$last]))
+			{
+				//4.a If this file ends with ".htm(l)", we consider it's an HTML file
+				//src tag check begin
+				//we now check if there is any src attribute in htm(l) files, if yes, we have to also export
+				//the target file (swf, mp3, video,...) of that src tag
+				//In case of absolute links (http://) this is not neccessary, but makes no error.
+				//however still missing : relative links case with subdirs -> the necessary dirs are not created in the exported package
+
+				//4.a.1 Get the file contents into $file
+				$file = file_get_contents($orig);
+
+				//4.a.2 Get all the src links in this file
 				//preg_match_all("|((?i)src=\".*\" )|U",$file,$match);
-				$match = GetSRCTags($orig);
-
-				//4.a.3 For each src tag found, do the following:
-				for ($i = 0; $i < count($match); $i ++)
-				{
-					//4.a.3.1 Get the tag (split from the key)
-					list ($key, $srctag) = each($match);
-					$src = $srctag;
-
-					//4.a.3.2 Check the link kind (web or absolute/relative)
-					if (stristr($src, "http") === false)
-					{
-						//4.a.3.2.a Do something only if relative (otherwise the user will be able to see it too anyway)
-						//4.a.3.2.a.1 Get a proper URL and remove all './'
-						$src = urldecode($src); //mp3
-						//$src=str_replace('./','',$src);
-						$src = preg_replace('/^\.\//', '', $src);
-						//4.a.3.2.a.2 Remove the player link from the URL (only use the mp3 file)
-						$src = str_replace('mp3player.swf?son=', '', $src); //mp3
-						//4.a.3.2.a.3 Remove funny link parts
-						$src = str_replace('?0', '', $src); //mp3
-						//the previous lines are used when creating docs with Dokeos Document tool's htmlarea
-						//rows marked by 'mp3' are needed because the mp3 plugin inserts the swf-mp3 links in a very strange way
-						//and we can decode them with those 3 lines, hoping this will not cause errors in case of other htmls,
+				$match = GetSRCTags($orig);
+
+				//4.a.3 For each src tag found, do the following:
+				for ($i = 0; $i < count($match); $i ++)
+				{
+					//4.a.3.1 Get the tag (split from the key)
+					list ($key, $srctag) = each($match);
+					$src = $srctag;
+
+					//4.a.3.2 Check the link kind (web or absolute/relative)
+					if (stristr($src, "http") === false)
+					{
+						//4.a.3.2.a Do something only if relative (otherwise the user will be able to see it too anyway)
+						//4.a.3.2.a.1 Get a proper URL and remove all './'
+						$src = urldecode($src); //mp3
+						//$src=str_replace('./','',$src);
+						$src = preg_replace('/^\.\//', '', $src);
+						//4.a.3.2.a.2 Remove the player link from the URL (only use the mp3 file)
+						$src = str_replace('mp3player.swf?son=', '', $src); //mp3
+						//4.a.3.2.a.3 Remove funny link parts
+						$src = str_replace('?0', '', $src); //mp3
+						//the previous lines are used when creating docs with Dokeos Document tool's htmlarea
+						//rows marked by 'mp3' are needed because the mp3 plugin inserts the swf-mp3 links in a very strange way
+						//and we can decode them with those 3 lines, hoping this will not cause errors in case of other htmls,
 						//created by any other software
-						//4.a.3.2.a.4 Prepare source and destination paths
-						$source = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.dirname($myrow['path']).'/'.$src;
-						$dest = $expdir.'/data/'.$src;
-						//CopyNCreate($source,$dest);
-						rcopy($source, $dest);
-					} //else...?
-				}
-
-				//src tag check end
-
-				//sco communication insertion begin
-				//4.a.4 If we want to add SCORM actions and a "Done" button, do the following:
-				if ($add_scorm_communications === true)
-				{
-					if ($bodyclose = strpos($file, '</body>'))
-					{
-						$file = substr_replace($file, $scocomfiles.$donebutton, $bodyclose, 7);
-					}
-					elseif ($htmlclose = strpos($file, '</html>'))
-					{
-						$file = substr_replace($file, $scocomfiles.$donebutton, $htmlclose, 7);
-						$file .= '</html>';
-					}
-					else
-					{
-						$file .= $scocomfiles.$donebutton;
-					}
+						//4.a.3.2.a.4 Prepare source and destination paths
+						$source = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.dirname($myrow['path']).'/'.$src;
+						$dest = $expdir.'/data/'.$src;
+						//CopyNCreate($source,$dest);
+						rcopy($source, $dest);
+					} //else...?
+				}
+
+				//src tag check end
+
+				//sco communication insertion begin
+				//4.a.4 If we want to add SCORM actions and a "Done" button, do the following:
+				if ($add_scorm_communications === true)
+				{
+					if ($bodyclose = strpos($file, '</body>'))
+					{
+						$file = substr_replace($file, $scocomfiles.$donebutton, $bodyclose, 7);
+					}
+					elseif ($htmlclose = strpos($file, '</html>'))
+					{
+						$file = substr_replace($file, $scocomfiles.$donebutton, $htmlclose, 7);
+						$file .= '</html>';
+					}
+					else
+					{
+						$file .= $scocomfiles.$donebutton;
+					}
 				} //sco communication insertion end
-
-				//4.a.5 Replace the file's name by adding the element's ID before htm
-				// This will not work with uppercase HTML though. Maybe use the preg_replace syntax proposed...
-				$filename = str_replace('.htm', $id.'.htm', $filename);
-				//$filename=preg_replace('/.*(\.htm(l)?)$/i',$id.$1,$filename);
-				//4.a.6 Export these contents to a file and set the circle1_files array for later reuse
-				exporttofile($filename, $LPname, $id, $file);
-
-				//The file has been copied, so ask not to copy it again
-				$copyneeded = false;
-
-			} //if (htm(l) files) end
-
-			//5 If we still need to copy the file (e.g. it was not an HTML file), then copy and set circle1_files for later reuse
-			if ($copyneeded)
-			{
-				copy($orig, $expdir.'/'.$filename);
-				$circle1_files[0][] = $filename;
-				$circle1_files[1][] = $LPname;
-				$circle1_files[2][] = $id;
-			}
-
-			//echo $orig;
-			return;
-
-			//------------------------Introduction_text BEGIN-------------------
-		case "Introduction_text" :
-			//1 Get the introduction text data from the database
-			$TBL_INTRO = Database :: get_course_tool_intro_table();
-			$result = Database::query("SELECT * FROM ".$TBL_INTRO." WHERE id=1");
-			$myrow = mysql_fetch_array($result);
-			$intro = $myrow["intro_text"];
-			//2 Write introduction text to the export string
-			$expcontent .= "<br />".$intro;
-			break;
-
-			//------------------------HotPotatoes BEGIN-------------------
-		case "HotPotatoes" :
-			//1 Get HotPotatoes data from the document table
-			$tbl_document = Database::get_course_table(TABLE_DOCUMENT);
-			$result = Database::query("SELECT * FROM $tbl_document WHERE id=$item_id", __FILE__, __LINE__);
-			$myrow = mysql_fetch_array($result);
-			//2 Get the document path
-			$testfile = api_get_path(SYS_COURSE_PATH).$_course['path']."/document".urldecode($myrow['path']);
-			//3 Get the document contents into a string
-			$content = file_get_contents($testfile);
-			//4 Get the document filename (just the file, no path) - would probably be better to use PHP native function
-			$pathname = explode("/", $myrow["path"]);
-			$last = count($pathname) - 1;
-			$filename = 'data/'.$filename.$pathname[$last];
-
-			//4beta - get all linked files and copy them (procedure copied from documents type)
-			//Get all the src links in this file
-			$match = GetSRCTags($testfile);
-			//For each src tag found, do the following:
-			foreach ($match as $src)
-			{
-				//Check the link kind (web or absolute/relative)
-				if (stristr($src, "http") === false)
-				{
-					//Do something only if relative (otherwise the user will be able to see it too anyway)
-					//Get a proper URL and remove all './'
-					$src = urldecode($src); //mp3
-					$src = str_replace('./', '', $src);
-					//Remove the player link from the URL (only use the mp3 file)
-					$src = str_replace('mp3player.swf?son=', '', $src); //mp3
-					//Remove funny link parts
-					$src = str_replace('?0', '', $src); //mp3
-					//The previous lines are used when creating docs with Dokeos Document tool's htmlarea
-					//rows marked by 'mp3' are needed because the mp3 plugin inserts the swf-mp3 links in a very strange way
-					//and we can decode them with those 3 lines, hoping this will not cause errors in case of other htmls,
+
+				//4.a.5 Replace the file's name by adding the element's ID before htm
+				// This will not work with uppercase HTML though. Maybe use the preg_replace syntax proposed...
+				$filename = str_replace('.htm', $id.'.htm', $filename);
+				//$filename=preg_replace('/.*(\.htm(l)?)$/i',$id.$1,$filename);
+				//4.a.6 Export these contents to a file and set the circle1_files array for later reuse
+				exporttofile($filename, $LPname, $id, $file);
+
+				//The file has been copied, so ask not to copy it again
+				$copyneeded = false;
+
+			} //if (htm(l) files) end
+
+			//5 If we still need to copy the file (e.g. it was not an HTML file), then copy and set circle1_files for later reuse
+			if ($copyneeded)
+			{
+				copy($orig, $expdir.'/'.$filename);
+				$circle1_files[0][] = $filename;
+				$circle1_files[1][] = $LPname;
+				$circle1_files[2][] = $id;
+			}
+
+			//echo $orig;
+			return;
+
+			//------------------------Introduction_text BEGIN-------------------
+		case "Introduction_text" :
+			//1 Get the introduction text data from the database
+			$TBL_INTRO = Database :: get_course_tool_intro_table();
+			$result = Database::query("SELECT * FROM ".$TBL_INTRO." WHERE id=1");
+			$myrow = mysql_fetch_array($result);
+			$intro = $myrow["intro_text"];
+			//2 Write introduction text to the export string
+			$expcontent .= "<br />".$intro;
+			break;
+
+			//------------------------HotPotatoes BEGIN-------------------
+		case "HotPotatoes" :
+			//1 Get HotPotatoes data from the document table
+			$tbl_document = Database::get_course_table(TABLE_DOCUMENT);
+			$result = Database::query("SELECT * FROM $tbl_document WHERE id=$item_id", __FILE__, __LINE__);
+			$myrow = mysql_fetch_array($result);
+			//2 Get the document path
+			$testfile = api_get_path(SYS_COURSE_PATH).$_course['path']."/document".urldecode($myrow['path']);
+			//3 Get the document contents into a string
+			$content = file_get_contents($testfile);
+			//4 Get the document filename (just the file, no path) - would probably be better to use PHP native function
+			$pathname = explode("/", $myrow["path"]);
+			$last = count($pathname) - 1;
+			$filename = 'data/'.$filename.$pathname[$last];
+
+			//4beta - get all linked files and copy them (procedure copied from documents type)
+			//Get all the src links in this file
+			$match = GetSRCTags($testfile);
+			//For each src tag found, do the following:
+			foreach ($match as $src)
+			{
+				//Check the link kind (web or absolute/relative)
+				if (stristr($src, "http") === false)
+				{
+					//Do something only if relative (otherwise the user will be able to see it too anyway)
+					//Get a proper URL and remove all './'
+					$src = urldecode($src); //mp3
+					$src = str_replace('./', '', $src);
+					//Remove the player link from the URL (only use the mp3 file)
+					$src = str_replace('mp3player.swf?son=', '', $src); //mp3
+					//Remove funny link parts
+					$src = str_replace('?0', '', $src); //mp3
+					//The previous lines are used when creating docs with Dokeos Document tool's htmlarea
+					//rows marked by 'mp3' are needed because the mp3 plugin inserts the swf-mp3 links in a very strange way
+					//and we can decode them with those 3 lines, hoping this will not cause errors in case of other htmls,
 					//created by any other software
-					//Prepare source and destination paths
-					$source = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.dirname($myrow['path']).'/'.$src;
-					$dest = $expdir.'/data/'.$src;
-					//CopyNCreate($source,$dest);
-					rcopy($source, $dest);
-				} //else...?
-			}
-
-			//5 Prepare the special "close window" for this test
-			$closewindow = "<html><head><link rel='stylesheet' type='text/css' href='../css/default.css'></head><body>"."<br /><div class='message'>$langHotPotatoesFinished</div></body></html>";
-
-			//Finish is the function of HP to save scores, we insert our scorm function calls to its beginning
-			//'Score' is the variable that tracks the score in HP tests
-			//6
-			$mit = "function Finish(){";
-
-			$js_content = "var SaveScoreVariable = 0; // This variable is included by Dokeos LP export\n"."function mySaveScore() // This function is included by Dokeos LP export\n"."{\n"."   if (SaveScoreVariable==0)\n"."		{\n"."	   SaveScoreVariable = 1;\n".
-				//the following function are implemented in SCOFunctions.js
-	"      exitPageStatus = true;\n"."      computeTime();\n"."      doLMSSetValue( 'cmi.core.score.raw', Score );\n"."      doLMSSetValue( 'cmi.core.lesson_status', 'completed' );\n"."      doLMSCommit();\n"."      doLMSFinish();\n".
-				//				"      document.write('".$closewindow."');\n".
-		//if you insert the previous row, the test does not appear correctly !!!!
-	"		}\n"."}\n"."function Finish(){\n"." mySaveScore();";
-
-			$start = "<script type='text/javascript'> loadPage(); </script>";
-			//7 Replace the current MIT function call by our set of functions. In clear, transform HP to SCORM
-			$content = str_replace($mit, $js_content, $content);
-			//8 Finally, add the API loading calls (although that might have been done first)
-			$content = str_replace("</script>", "</script>".$scocomfiles.$start, $content);
-
+					//Prepare source and destination paths
+					$source = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.dirname($myrow['path']).'/'.$src;
+					$dest = $expdir.'/data/'.$src;
+					//CopyNCreate($source,$dest);
+					rcopy($source, $dest);
+				} //else...?
+			}
+
+			//5 Prepare the special "close window" for this test
+			$closewindow = "<html><head><link rel='stylesheet' type='text/css' href='../css/default.css'></head><body>"."<br /><div class='message'>$langHotPotatoesFinished</div></body></html>";
+
+			//Finish is the function of HP to save scores, we insert our scorm function calls to its beginning
+			//'Score' is the variable that tracks the score in HP tests
+			//6
+			$mit = "function Finish(){";
+
+			$js_content = "var SaveScoreVariable = 0; // This variable is included by Dokeos LP export\n"."function mySaveScore() // This function is included by Dokeos LP export\n"."{\n"."   if (SaveScoreVariable==0)\n"."		{\n"."	   SaveScoreVariable = 1;\n".
+				//the following function are implemented in SCOFunctions.js
+	"      exitPageStatus = true;\n"."      computeTime();\n"."      doLMSSetValue( 'cmi.core.score.raw', Score );\n"."      doLMSSetValue( 'cmi.core.lesson_status', 'completed' );\n"."      doLMSCommit();\n"."      doLMSFinish();\n".
+				//				"      document.write('".$closewindow."');\n".
+		//if you insert the previous row, the test does not appear correctly !!!!
+	"		}\n"."}\n"."function Finish(){\n"." mySaveScore();";
+
+			$start = "<script type='text/javascript'> loadPage(); </script>";
+			//7 Replace the current MIT function call by our set of functions. In clear, transform HP to SCORM
+			$content = str_replace($mit, $js_content, $content);
+			//8 Finally, add the API loading calls (although that might have been done first)
+			$content = str_replace("</script>", "</script>".$scocomfiles.$start, $content);
+
 			//9 Change the filename to add the database ID and export to a new file,
-			//  setting the circle1_files array for later reuse
-			$filename = str_replace('.htm', $id.'.htm', $filename);
-			exporttofile($filename, $LPname, $id, $content);
-
-			return;
-
-			//------------------------Dokeos test BEGIN-------------------
-		case "Exercise" :
-			//1 Use the export_exercise() function to do the job of constructing the question's HTML table
-			$expcontent .= export_exercise($item_id);
-			break;
-			//------------------------POST BEGIN---------------------------------------
-		case "Post" :
-			//1 Get the forum post data from the database
-			$tbl_posts =Database::get_course_table(TABLE_FORUM_POST);
-			$tbl_posts_text =Database::get_course_table(TOOL_FORUM_POST_TEXT_TABLE);
-			$result = Database::query("SELECT * FROM $tbl_posts where post_id=$item_id", __FILE__, __LINE__);
-			$myrow = mysql_fetch_array($result);
-			// grabbing the title of the post
-			$sql_titel = "SELECT * FROM $tbl_posts_text WHERE post_id=".$myrow["post_id"];
-			$result_titel = Database::query($sql_titel, __FILE__, __LINE__);
-			$myrow_titel = mysql_fetch_array($result_titel);
-
-			$posternom = $myrow['nom'];
-			$posterprenom = $myrow['prenom'];
-			$posttime = $myrow['post_time'];
-			$posttext = $myrow_titel['post_text'];
-			$posttitle = $myrow_titel['post_title'];
-			$posttext = str_replace('"', "'", $posttext);
-
-			//2 Export contents as an HTML table
-			$expcontent .= "<table border='0' cellpadding='3' cellspacing='1' width='100%'>
-							<tr>
-								<td colspan='2' bgcolor='#e6e6e6'><b>$posttitle</b><br />$posttext</td>
-							</tr>
-							<tr>
-								<td colspan='2'></td>
-							</tr>
-							<tr>
-								<td bgcolor='#cccccc' align='left'>$lang_author : $posterprenom $posternom</td>
-								<td align='right' bgcolor='#cccccc'>$lang_date : $posttime</td>
-							</tr>
-							<tr><td colspan='2' height='10'></td></tr>
-						</table>";
-			break;
-			//------------------------NOT IMPLEMENTED ITEMS BEGIN-------------------
-		case "Forum" :
-		case "Thread" :
-		case "Dropbox" :
-		case "Assignments" :
-		case "Groups" :
-		case "Users" :
-			//1 Instead of building something, put an info message
-			$langItemMissing1 = "There was a ";
-			$langItemMissing2 = "page (step) here in the original Dokeos Learning Path.";
-			$expcontent .= "<div class='message'>$langItemMissing1 $item_type $langItemMissing2</div>";
-			break;
-			//------------------------Link BEGIN-------------------------------------
-		case "Link _self" :
-		case "Link _blank" :
-			//1 Get the link data from the database
-			$TABLETOOLLINK = Database :: get_course_link_table();
-			$result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE id=$item_id", __FILE__, __LINE__);
-			$myrow = mysql_fetch_array($result);
-			$thelink = $myrow["url"];
-			//2 Check the link type (open in blank page or in current page)
-			if ($item_type == "Link _blank")
-			{
-				$target = "_blank";
-			}
-			//3 Write the link to the export string
-			$expcontent .= "<a href='$thelink?SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9' target='".$target."'>$LPname</a>";
-			//4 Change the element type for later changes (this is lost, however, so useless here)
-			$item_type = "Link"; //to put this to the filename
-			//$LPname="<a href='$thelink?SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9' target=".$target.">$LPname</a>";
-			//i am still not sure about Link export : to export them as files or they can appear in the TOC at once ?
-			//to enable the second possibility, unrem the row $LPname=...
-			break;
-	}
-
-	//now we add the Done button and the initialize function : loadpage()
-	//not in the case of Documents, HotP
-	if ($item_type != 'Exercise' and ($add_scorm_communications === true))
-	{
-		$expcontent .= $donebutton;
-	}
-	//End the export string with valid HTML tags
-	$expcontent .= "</body></html>";
-
-	//Prepare new file name
-	$filename = $item_type.$id.".htm";
-	//Write the export content to the new file
-	exporttofile('data/'.$filename, $LPname, $id, $expcontent);
-
-}
-
-/**
- * This function exports the given item's description into a separate file
- * @param	integer	Item id
- * @param	string	Item type
- * @param	string	Description
- * @return void
- */
-function exportdescription($id, $item_type, $description)
-{
-
-	global $expdir;
-
-	$filename = $item_type.$id.".desc";
-	$expcontent = $description;
-	exporttofile($expdir.$filename, 'description_of_'.$item_type.$id, 'description_of_item_'.$id, $expcontent);
-}
-
-/**
- * This function deletes an entire directory
- * @param	string	The directory path
- * @return boolean	True on success, false on failure
- */
-function deldir($dir)
-{
-	$dh = opendir($dir);
-	while ($file = readdir($dh))
-	{
-		if ($file != "." && $file != "..")
-		{
-			$fullpath = $dir."/".$file;
-			if (!is_dir($fullpath))
-			{
-				unlink($fullpath);
-			}
-			else
-			{
-				deldir($fullpath);
-			}
-		}
-	}
-
-	closedir($dh);
-
-	if (rmdir($dir))
-	{
-		return true;
-	}
-	else
-	{
-		return false;
-	}
-}
-
-/**
- * This functions exports the given path. This is the opener function, which is called first
- * @param	integer 	The path id
- * @return	resource	A zip file, containing a hopefully Scorm compliant course made from the LP. This might happen when we don't actually exit the function first :-)
- */
-function exportpath($learnpath_id)
-{
-	//1 Initialise variables
-	global $_course, $circle1_files, $LPnamesafe, $LPname, $expdir;
+			//  setting the circle1_files array for later reuse
+			$filename = str_replace('.htm', $id.'.htm', $filename);
+			exporttofile($filename, $LPname, $id, $content);
+
+			return;
+
+			//------------------------Dokeos test BEGIN-------------------
+		case "Exercise" :
+			//1 Use the export_exercise() function to do the job of constructing the question's HTML table
+			$expcontent .= export_exercise($item_id);
+			break;
+			//------------------------POST BEGIN---------------------------------------
+		case "Post" :
+			//1 Get the forum post data from the database
+			$tbl_posts =Database::get_course_table(TABLE_FORUM_POST);
+			$tbl_posts_text =Database::get_course_table(TOOL_FORUM_POST_TEXT_TABLE);
+			$result = Database::query("SELECT * FROM $tbl_posts where post_id=$item_id", __FILE__, __LINE__);
+			$myrow = mysql_fetch_array($result);
+			// grabbing the title of the post
+			$sql_titel = "SELECT * FROM $tbl_posts_text WHERE post_id=".$myrow["post_id"];
+			$result_titel = Database::query($sql_titel, __FILE__, __LINE__);
+			$myrow_titel = mysql_fetch_array($result_titel);
+
+			$posternom = $myrow['nom'];
+			$posterprenom = $myrow['prenom'];
+			$posttime = $myrow['post_time'];
+			$posttext = $myrow_titel['post_text'];
+			$posttitle = $myrow_titel['post_title'];
+			$posttext = str_replace('"', "'", $posttext);
+
+			//2 Export contents as an HTML table
+			$expcontent .= "<table border='0' cellpadding='3' cellspacing='1' width='100%'>
+							<tr>
+								<td colspan='2' bgcolor='#e6e6e6'><b>$posttitle</b><br />$posttext</td>
+							</tr>
+							<tr>
+								<td colspan='2'></td>
+							</tr>
+							<tr>
+								<td bgcolor='#cccccc' align='left'>$lang_author : $posterprenom $posternom</td>
+								<td align='right' bgcolor='#cccccc'>$lang_date : $posttime</td>
+							</tr>
+							<tr><td colspan='2' height='10'></td></tr>
+						</table>";
+			break;
+			//------------------------NOT IMPLEMENTED ITEMS BEGIN-------------------
+		case "Forum" :
+		case "Thread" :
+		case "Dropbox" :
+		case "Assignments" :
+		case "Groups" :
+		case "Users" :
+			//1 Instead of building something, put an info message
+			$langItemMissing1 = "There was a ";
+			$langItemMissing2 = "page (step) here in the original Dokeos Learning Path.";
+			$expcontent .= "<div class='message'>$langItemMissing1 $item_type $langItemMissing2</div>";
+			break;
+			//------------------------Link BEGIN-------------------------------------
+		case "Link _self" :
+		case "Link _blank" :
+			//1 Get the link data from the database
+			$TABLETOOLLINK = Database :: get_course_link_table();
+			$result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE id=$item_id", __FILE__, __LINE__);
+			$myrow = mysql_fetch_array($result);
+			$thelink = $myrow["url"];
+			//2 Check the link type (open in blank page or in current page)
+			if ($item_type == "Link _blank")
+			{
+				$target = "_blank";
+			}
+			//3 Write the link to the export string
+			$expcontent .= "<a href='$thelink?SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9' target='".$target."'>$LPname</a>";
+			//4 Change the element type for later changes (this is lost, however, so useless here)
+			$item_type = "Link"; //to put this to the filename
+			//$LPname="<a href='$thelink?SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9' target=".$target.">$LPname</a>";
+			//i am still not sure about Link export : to export them as files or they can appear in the TOC at once ?
+			//to enable the second possibility, unrem the row $LPname=...
+			break;
+	}
+
+	//now we add the Done button and the initialize function : loadpage()
+	//not in the case of Documents, HotP
+	if ($item_type != 'Exercise' and ($add_scorm_communications === true))
+	{
+		$expcontent .= $donebutton;
+	}
+	//End the export string with valid HTML tags
+	$expcontent .= "</body></html>";
+
+	//Prepare new file name
+	$filename = $item_type.$id.".htm";
+	//Write the export content to the new file
+	exporttofile('data/'.$filename, $LPname, $id, $expcontent);
+
+}
+
+/**
+ * This function exports the given item's description into a separate file
+ * @param	integer	Item id
+ * @param	string	Item type
+ * @param	string	Description
+ * @return void
+ */
+function exportdescription($id, $item_type, $description)
+{
+
+	global $expdir;
+
+	$filename = $item_type.$id.".desc";
+	$expcontent = $description;
+	exporttofile($expdir.$filename, 'description_of_'.$item_type.$id, 'description_of_item_'.$id, $expcontent);
+}
+
+/**
+ * This function deletes an entire directory
+ * @param	string	The directory path
+ * @return boolean	True on success, false on failure
+ */
+function deldir($dir)
+{
+	$dh = opendir($dir);
+	while ($file = readdir($dh))
+	{
+		if ($file != "." && $file != "..")
+		{
+			$fullpath = $dir."/".$file;
+			if (!is_dir($fullpath))
+			{
+				unlink($fullpath);
+			}
+			else
+			{
+				deldir($fullpath);
+			}
+		}
+	}
+
+	closedir($dh);
+
+	if (rmdir($dir))
+	{
+		return true;
+	}
+	else
+	{
+		return false;
+	}
+}
+
+/**
+ * This functions exports the given path. This is the opener function, which is called first
+ * @param	integer 	The path id
+ * @return	resource	A zip file, containing a hopefully Scorm compliant course made from the LP. This might happen when we don't actually exit the function first :-)
+ */
+function exportpath($learnpath_id)
+{
+	//1 Initialise variables
+	global $_course, $circle1_files, $LPnamesafe, $LPname, $expdir;
 	//$tbl_learnpath_main, $tbl_learnpath_chapter, $tbl_learnpath_item,
-	$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-
-	//where applicable, add a scorm "Done" button at the end of all contents
-	$add_scorm_button = true;
-
-	//2 Get the name of the LP
-	include_once (api_get_path(LIBRARY_PATH)."fileUpload.lib.php");
-	$sql = "SELECT * FROM $tbl_learnpath_main WHERE (lp_id=$learnpath_id)";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	$row = mysql_fetch_array($result);
-	$LPname = $row['learnpath_name'];
-	$LPnamesafe = replace_dangerous_char($LPname, 'strict');
-
+	$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+
+	//where applicable, add a scorm "Done" button at the end of all contents
+	$add_scorm_button = true;
+
+	//2 Get the name of the LP
+	include_once (api_get_path(LIBRARY_PATH)."fileUpload.lib.php");
+	$sql = "SELECT * FROM $tbl_learnpath_main WHERE (lp_id=$learnpath_id)";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	$row = mysql_fetch_array($result);
+	$LPname = $row['learnpath_name'];
+	$LPnamesafe = replace_dangerous_char($LPname, 'strict');
+
 	//3 Get a temporary dir for creating the zip file
-	$expdir = api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe;
-	$fromdir = '../scorm/export/'; //this dir contains some standard files
-
-	deldir($expdir); //make sure the temp dir is cleared
-	mkdir($expdir);
-	mkdir($expdir.'/css');
-	mkdir($expdir.'/data');
-	mkdir($expdir.'/js');
-	mkdir($expdir.'/data/images');
-	mkdir($expdir.'/data/audio');
-	mkdir($expdir.'/data/videos');
-
-		$circle1 = array (//this array contains the types of elements we want to export
-	'Chapter', 'Agenda', 'Ad_Valvas', 'Course_description', 'Document', 'Introduction_text', 'Link _self', 'Link _blank', 'Forum', 'Thread', 'Post', 'Exercise', 'HotPotatoes', 'Assignments', 'Dropbox', 'Users', 'Groups');
-	//$circle2=array('');
-
-	//4 Get the first level chapters - YW added parent_item_id condition for multi-level paths
+	$expdir = api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe;
+	$fromdir = '../scorm/export/'; //this dir contains some standard files
+
+	deldir($expdir); //make sure the temp dir is cleared
+	mkdir($expdir);
+	mkdir($expdir.'/css');
+	mkdir($expdir.'/data');
+	mkdir($expdir.'/js');
+	mkdir($expdir.'/data/images');
+	mkdir($expdir.'/data/audio');
+	mkdir($expdir.'/data/videos');
+
+		$circle1 = array (//this array contains the types of elements we want to export
+	'Chapter', 'Agenda', 'Ad_Valvas', 'Course_description', 'Document', 'Introduction_text', 'Link _self', 'Link _blank', 'Forum', 'Thread', 'Post', 'Exercise', 'HotPotatoes', 'Assignments', 'Dropbox', 'Users', 'Groups');
+	//$circle2=array('');
+
+	//4 Get the first level chapters - YW added parent_item_id condition for multi-level paths
 	$sql = "SELECT * FROM $tbl_learnpath_chapter
 			WHERE (lp_id=$learnpath_id and parent_item_id=0)
-			ORDER BY display_order ASC";
-	//to get all the elements, we should use the function that builds the table of content get_learnpath_tree
+			ORDER BY display_order ASC";
+	//to get all the elements, we should use the function that builds the table of content get_learnpath_tree
 	//WHERE (lp_id=$learnpath_id)
-	//ORDER BY parent_item_id, display_order ASC";
-	$result = Database::query($sql, __FILE__, __LINE__);
-
-	//5 export the items listed in Circle I one by one
-	while ($row = mysql_fetch_array($result))
-	{
-		//5.1 Get items data from the database for this chapter
-		$parent_item_id = $row['id'];
-		//$sql2a="SELECT * FROM $tbl_learnpath_chapter WHERE (lp_id=$learnpath_id and parent_item_id=$parent_item_id) ORDER BY display_order ASC";
+	//ORDER BY parent_item_id, display_order ASC";
+	$result = Database::query($sql, __FILE__, __LINE__);
+
+	//5 export the items listed in Circle I one by one
+	while ($row = mysql_fetch_array($result))
+	{
+		//5.1 Get items data from the database for this chapter
+		$parent_item_id = $row['id'];
+		//$sql2a="SELECT * FROM $tbl_learnpath_chapter WHERE (lp_id=$learnpath_id and parent_item_id=$parent_item_id) ORDER BY display_order ASC";
 		//$result2a=Database::query($sql,__FILE__,__LINE__);
-		$sql2b = "SELECT * FROM $tbl_learnpath_item WHERE (parent_item_id=$parent_item_id) ORDER BY display_order ASC";
-		$result2b = Database::query($sql2b, __FILE__, __LINE__);
-
-		while ($row2 = mysql_fetch_array($result2b))
-		{
-			//5.1.1 Check if the element is in the circle1 array
-			$tobeexported = false;
-			for ($i = 0; $i < count($circle1) && !$tobeexported; $i ++)
-			{
-				//if the type is found in the circle1 array, ask for export
-				if ($circle1[$i] == $row2['item_type'])
-				{
-					$tobeexported = true;
-				}
-			}
-			//5.1.2 If applicable, export the item to an HTML file (see exportitem function for more details)
-			if ($tobeexported)
-			{
-				exportitem($row2['id'], $row2['item_id'], $row2['item_type'], $add_scorm_button);
-				/*if ($row2['description']) {   //put the description of items to a separate file (.desc)
-					exportdescription($row2['id'],$row2['item_type'],$row2['description']);
-				}*/
-			}
-		} //end of items loop
-	} //end of first-level chapters loop
-
-	//6 export the other necceassary files
-	$filename = 'default.css';
-	copy('../css/'.$filename, $expdir.'/css/'.$filename);
-	$filename = 'ims_xml.xsd';
-	copy($fromdir.$filename, $expdir.'/'.$filename);
-	$filename = 'imscp_v1p1.xsd';
-	copy($fromdir.$filename, $expdir.'/'.$filename);
-	$filename = 'imsmd_v1p2.xsd';
-	copy($fromdir.$filename, $expdir.'/'.$filename);
-	$filename = 'APIWrapper.js';
-	copy($fromdir.$filename, $expdir.'/js/'.$filename);
-	$filename = 'SCOFunctions.js';
-	copy($fromdir.$filename, $expdir.'/js/'.$filename);
-
-	//in case circle1_files is not defined, build it
-	//$circle1_files
-	//7 create imsmanifest.xml
-	createimsmanifest($circle1_files, $learnpath_id);
-
-	//8 put the files in the exportdir into a zip and force download
-	include_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
-	//create zipfile of given directory
-	$zip_folder = new PclZip(api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe.".zip");
-
-	$zip_folder->create(api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe."/", PCLZIP_OPT_REMOVE_PATH, api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/");
-	//api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe); // whitout folder
-
-	// modified by imandak80
-
-	/*	copy(api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe.".zip",
-			 api_get_path('SYS_COURSE_PATH').$_course['path']."/document/".$LPnamesafe.".zip");
-	*/
-
-	$zipfoldername = api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe;
-	$zipfilename = $zipfoldername.".zip";
-	DocumentManager :: file_send_for_download($zipfilename, false, basename($LPnamesafe.".zip"));
-
-	//9 Delete the temporary zip file and directory
-	include_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
-	// in fileManage.lib.php
-	my_delete($zipfilename);
-	my_delete($zipfoldername);
-
-	//exit;
-
-	//0 Return the circle_files hash (array)
-	return ($circle1_files); //has been used before...
-}
-
-/**
- * Export SCORM content into a zip file
- *
- * Basically, all this function does is put the scorm directory back into a zip file (like the one
+		$sql2b = "SELECT * FROM $tbl_learnpath_item WHERE (parent_item_id=$parent_item_id) ORDER BY display_order ASC";
+		$result2b = Database::query($sql2b, __FILE__, __LINE__);
+
+		while ($row2 = mysql_fetch_array($result2b))
+		{
+			//5.1.1 Check if the element is in the circle1 array
+			$tobeexported = false;
+			for ($i = 0; $i < count($circle1) && !$tobeexported; $i ++)
+			{
+				//if the type is found in the circle1 array, ask for export
+				if ($circle1[$i] == $row2['item_type'])
+				{
+					$tobeexported = true;
+				}
+			}
+			//5.1.2 If applicable, export the item to an HTML file (see exportitem function for more details)
+			if ($tobeexported)
+			{
+				exportitem($row2['id'], $row2['item_id'], $row2['item_type'], $add_scorm_button);
+				/*if ($row2['description']) {   //put the description of items to a separate file (.desc)
+					exportdescription($row2['id'],$row2['item_type'],$row2['description']);
+				}*/
+			}
+		} //end of items loop
+	} //end of first-level chapters loop
+
+	//6 export the other necceassary files
+	$filename = 'default.css';
+	copy('../css/'.$filename, $expdir.'/css/'.$filename);
+	$filename = 'ims_xml.xsd';
+	copy($fromdir.$filename, $expdir.'/'.$filename);
+	$filename = 'imscp_v1p1.xsd';
+	copy($fromdir.$filename, $expdir.'/'.$filename);
+	$filename = 'imsmd_v1p2.xsd';
+	copy($fromdir.$filename, $expdir.'/'.$filename);
+	$filename = 'APIWrapper.js';
+	copy($fromdir.$filename, $expdir.'/js/'.$filename);
+	$filename = 'SCOFunctions.js';
+	copy($fromdir.$filename, $expdir.'/js/'.$filename);
+
+	//in case circle1_files is not defined, build it
+	//$circle1_files
+	//7 create imsmanifest.xml
+	createimsmanifest($circle1_files, $learnpath_id);
+
+	//8 put the files in the exportdir into a zip and force download
+	include_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
+	//create zipfile of given directory
+	$zip_folder = new PclZip(api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe.".zip");
+
+	$zip_folder->create(api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe."/", PCLZIP_OPT_REMOVE_PATH, api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/");
+	//api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe); // whitout folder
+
+	// modified by imandak80
+
+	/*	copy(api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe.".zip",
+			 api_get_path('SYS_COURSE_PATH').$_course['path']."/document/".$LPnamesafe.".zip");
+	*/
+
+	$zipfoldername = api_get_path('SYS_COURSE_PATH').$_course['path']."/temp/".$LPnamesafe;
+	$zipfilename = $zipfoldername.".zip";
+	DocumentManager :: file_send_for_download($zipfilename, false, basename($LPnamesafe.".zip"));
+
+	//9 Delete the temporary zip file and directory
+	include_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
+	// in fileManage.lib.php
+	my_delete($zipfilename);
+	my_delete($zipfoldername);
+
+	//exit;
+
+	//0 Return the circle_files hash (array)
+	return ($circle1_files); //has been used before...
+}
+
+/**
+ * Export SCORM content into a zip file
+ *
+ * Basically, all this function does is put the scorm directory back into a zip file (like the one
  * that was most probably used to import the course at first)
- * @param	string	Name of the SCORM path (or the directory under which it resides)
- * @param	array		Not used right now. Should replace the use of global $_course
+ * @param	string	Name of the SCORM path (or the directory under which it resides)
+ * @param	array		Not used right now. Should replace the use of global $_course
  * @return	void
  * @author	imandak80
- */
-function exportSCORM($scormname, $course)
-{
-	global $_course;
-
-	//initialize
-	$tmpname = api_get_path('SYS_COURSE_PATH').$_course['path']."/scorm";
-	$zipfoldername = $tmpname.$scormname;
-	$zipfilename = $zipfoldername.".zip";
-
-	//create zipfile of given directory
-	include_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
-	$zip_folder = new PclZip($zipfilename);
-	$list = 1;
-	//$list = $zip_folder->create($zipfoldername."/",PCLZIP_OPT_REMOVE_PATH,$tmpname.$scormname."/"); // whitout folder
-	$list = $zip_folder->create($zipfoldername."/", PCLZIP_OPT_REMOVE_PATH, $tmpname);
-	if ($list == 0)
-	{
-		//  echo "Error  : ".$zip_folder->errorInfo(true);
-	}
-
+ */
+function exportSCORM($scormname, $course)
+{
+	global $_course;
+
+	//initialize
+	$tmpname = api_get_path('SYS_COURSE_PATH').$_course['path']."/scorm";
+	$zipfoldername = $tmpname.$scormname;
+	$zipfilename = $zipfoldername.".zip";
+
+	//create zipfile of given directory
+	include_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
+	$zip_folder = new PclZip($zipfilename);
+	$list = 1;
+	//$list = $zip_folder->create($zipfoldername."/",PCLZIP_OPT_REMOVE_PATH,$tmpname.$scormname."/"); // whitout folder
+	$list = $zip_folder->create($zipfoldername."/", PCLZIP_OPT_REMOVE_PATH, $tmpname);
+	if ($list == 0)
+	{
+		//  echo "Error  : ".$zip_folder->errorInfo(true);
+	}
+
 	//send to client
-	DocumentManager :: file_send_for_download($zipfilename, false, basename($scormname.".zip"));
-
-	//clear
-	include_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
-	my_delete($zipfilename);
-}
-
-/**
- * This function returns an xml tag
+	DocumentManager :: file_send_for_download($zipfilename, false, basename($scormname.".zip"));
+
+	//clear
+	include_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
+	my_delete($zipfilename);
+}
+
+/**
+ * This function returns an xml tag
  * $data behaves as the content in case of full tags
- * $data is an array of attributes in case of returning an opening tag
- * @param	string
- * @param	string
- * @param	array
- * @param	string
- * @return string
- */
-function xmltagwrite($tagname, $which, $data, $linebreak = "yes")
-{
-	switch ($which)
-	{
-		case "open" :
-			$tag = "<".$tagname;
-			$i = 0;
-			while ($data[0][$i])
-			{
-				$tag .= " ".$data[0][$i]."=\"".$data[1][$i]."\"";
-				$i ++;
-			}
-			if ($tagname == 'file')
-			{
-				$closing = '/';
-			}
-			$tag .= $closing.">";
-			if ($linebreak != 'no_linebreak')
-			{
-				$tag .= "\n";
-			}
-			break;
-		case "close" :
-			$tag = "</".$tagname.">";
-			if ($linebreak != 'no_linebreak')
-			{
-				$tag .= "\n";
-			}
-			break;
-		case "full" :
-			$tag = "<".$tagname;
-			$tag .= ">".$data."</".$tagname.">";
-			if ($linebreak != 'no_linebreak')
-			{
-				$tag .= "\n";
-			}
-			break;
-	}
-	return $tag;
-}
-
-/**
- * This function writes the imsmanifest.xml and exports the chapter names
- * @param	array		Array containing filenames
- * @param	integer	Learnpath_id
+ * $data is an array of attributes in case of returning an opening tag
+ * @param	string
+ * @param	string
+ * @param	array
+ * @param	string
+ * @return string
+ */
+function xmltagwrite($tagname, $which, $data, $linebreak = "yes")
+{
+	switch ($which)
+	{
+		case "open" :
+			$tag = "<".$tagname;
+			$i = 0;
+			while ($data[0][$i])
+			{
+				$tag .= " ".$data[0][$i]."=\"".$data[1][$i]."\"";
+				$i ++;
+			}
+			if ($tagname == 'file')
+			{
+				$closing = '/';
+			}
+			$tag .= $closing.">";
+			if ($linebreak != 'no_linebreak')
+			{
+				$tag .= "\n";
+			}
+			break;
+		case "close" :
+			$tag = "</".$tagname.">";
+			if ($linebreak != 'no_linebreak')
+			{
+				$tag .= "\n";
+			}
+			break;
+		case "full" :
+			$tag = "<".$tagname;
+			$tag .= ">".$data."</".$tagname.">";
+			if ($linebreak != 'no_linebreak')
+			{
+				$tag .= "\n";
+			}
+			break;
+	}
+	return $tag;
+}
+
+/**
+ * This function writes the imsmanifest.xml and exports the chapter names
+ * @param	array		Array containing filenames
+ * @param	integer	Learnpath_id
  * @return	void
- */
-function createimsmanifest($circle1_files, $learnpath_id)
-{
-	global $charset;
-	global $_course, $LPname, $expdir, $LPnamesafe;
+ */
+function createimsmanifest($circle1_files, $learnpath_id)
+{
+	global $charset;
+	global $_course, $LPname, $expdir, $LPnamesafe;
 	//$tbl_learnpath_main, $tbl_learnpath_chapter, $tbl_learnpath_item,
-	$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
-	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-
-	include_once ('../metadata/md_funcs.php'); // RH: export metadata
-
-	//1.1 header
-	/*
-		$header='<?xml version="1.0" encoding="UTF-8"?><manifest identifier="'.$LPnamesafe.'" xmlns="http://www.imsglobal.org/xsd/imscp_v1p1" xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2.xsd" version="IMS CP 1.1.3">'."\n";
-	*/
-
-	//1.2
-	//charset should be dependent on content
-	//$mycharset = 'ISO-8859-1';
-	$mycharset = $charset;
-	$header = '<?xml version="1.0" encoding="'.$mycharset.'"?>'."\n<manifest identifier='".$LPnamesafe."' version='1.1'\n xmlns='http://www.imsproject.org/xsd/imscp_rootv1p1p2'\n xmlns:adlcp='http://www.adlnet.org/xsd/adlcp_rootv1p2'\n xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n xsi:schemaLocation='http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd\n http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd\n http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd'>\n";
-
-	$org .= xmltagwrite('metadata', 'open');
-	$org .= "  ".xmltagwrite('schema', 'full', 'ADL SCORM');
-	$org .= "  ".xmltagwrite('schemaversion', 'full', '1.2');
-	$org .= xmltagwrite('metadata', 'close');
-
-	$defaultorgname = 'default_org';
-
-	$attributes[0][0] = 'default';
-	$attributes[1][0] = $defaultorgname;
-	$org .= xmltagwrite('organizations', 'open', $attributes);
-
-	$attributes[0][0] = 'identifier';
-	$attributes[1][0] = $defaultorgname;
-	$org .= "  ".xmltagwrite('organization', 'open', $attributes);
-
-	$org .= "    ".xmltagwrite('title', 'full', $LPname);
-
-	//items list
-	$i = 0;
-	$previous_item_id = '00';
-	while ($circle1_files[0][$i])
-	{
-		//check whether we are in the border of two chapters
-		//if (!$desc=strpos($circle1_files[2][$i],'scription')) {  //this is is needed if the descriptions are exported to file
-
-		$sql = "SELECT * FROM $tbl_learnpath_item WHERE (id=".$circle1_files[2][$i].")";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		$row = mysql_fetch_array($result);
-		$parent_item_id = $row['parent_item_id'];
-
-		if ($parent_item_id != $previous_item_id)
-		{
-			//we create the item tag for the chapter (without indifierref)
-			$sql2 = "SELECT * FROM $tbl_learnpath_chapter WHERE (id=".$parent_item_id.")";
-			$result2 = Database::query($sql2, __FILE__, __LINE__);
-			$row2 = mysql_fetch_array($result2);
-			$chapter_name = $row2['chapter_name'];
-
-			$attributes = '';
-			$attributes[0][] = 'identifier';
-			$attributes[1][] = 'chapter_'.$row2['id'];
-			$attributes[0][] = 'isvisible';
-			$attributes[1][] = '1';
-			if ($previous_item_id != '00')
-			{
-				$org .= "    ".xmltagwrite('item', 'close');
-			}
-
-			$org .= "    ".xmltagwrite('item', 'open', $attributes);
-			$org .= "      ".xmltagwrite('title', 'full', $chapter_name);
-
-			if ($row2['chapter_description'] != '')
-			{
-				//chapter description
-				$attributes = '';
-				$attributes[0][] = 'identifier';
-				$attributes[1][] = 'chapter_'.$row2['id'].'_desc';
-				$attributes[0][] = 'isvisible';
-				$attributes[1][] = '1';
-				$org .= "    ".xmltagwrite('item', 'open', $attributes);
-				$org .= "      ".xmltagwrite('title', 'full', ' '.$row2['chapter_description']);
-				$org .= "    ".xmltagwrite('item', 'close');
-			}
-		}
-		$previous_item_id = $parent_item_id;
-		//}
-
-		$attributes = ''; //item output
-		$attributes[0][] = 'identifier';
-		$attributes[1][] = 'item_'.$circle1_files[2][$i];
-		$attributes[0][] = 'identifierref';
-		$attributes[1][] = 'item_ref_'.$circle1_files[2][$i];
-		$attributes[0][] = 'isvisible';
-		$attributes[1][] = '1';
-		$org .= "    ".xmltagwrite('item', 'open', $attributes);
-		$org .= "      ".xmltagwrite('title', 'full', $circle1_files[1][$i]);
-
-		if ($row['prereq_id'] != '')
-		{ //item prerequisites
-			$attributes = '';
-			$attributes[0][] = 'type';
-			$attributes[1][] = 'aicc_script';
-			$org .= "      ".xmltagwrite('adlcp:prerequisites', 'open', $attributes, "no_linebreak");
-			if ($row['prereq_type'] == 'i')
-			{
-				$org .= 'item_'.$row['prereq_id'];
-			}
-			if ($row['prereq_type'] == 'c')
-			{
-				$org .= 'chapter_'.$row['prereq_id'];
-			}
-			$org .= xmltagwrite('adlcp:prerequisites', 'close', $attributes);
-		}
-
-		if ($row['description'] != '')
-		{
-			//item description
-			$attributes = '';
-			$attributes[0][] = 'identifier';
-			$attributes[1][] = 'item_'.$circle1_files[2][$i].'_desc';
-			$attributes[0][] = 'isvisible';
-			$attributes[1][] = '1';
-			$org .= "    ".xmltagwrite('item', 'open', $attributes);
-			$org .= "      ".xmltagwrite('title', 'full', ' '.$row['description']);
-			$org .= "    ".xmltagwrite('item', 'close');
-		}
-
-		$mds = new mdstore(TRUE); // RH: export metadata; if no table, create it
-		if (($mdt = $mds->mds_get($row['item_type'].'.'.$row['item_id'])))
-			if (($mdo = api_strpos($mdt, '<metadata>')) && ($mdc = api_strpos($mdt, '</metadata>')))
-				$org .= "    ".api_substr($mdt, $mdo, $mdc - $mdo +11)."\n";
-
-		$org .= "    ".xmltagwrite('item', 'close');
-		$i ++;
-	}
-
-	if ($circle1_files)
-	{
-		$org .= "    ".xmltagwrite('item', 'close');
-	} //not needed in case of a blank path
-	$org .= "  ".xmltagwrite('organization', 'close');
-	$org .= xmltagwrite('organizations', 'close');
-	$org .= xmltagwrite('resources', 'open');
-
-	//resources list
-	$i = 0;
-	while ($circle1_files[0][$i])
-	{
-		$attributes = '';
-		$attributes[0][] = 'identifier';
-		$attributes[1][] = 'item_ref_'.$circle1_files[2][$i];
-		$attributes[0][] = 'type';
-		$attributes[1][] = 'webcontent';
-		$attributes[0][] = 'adlcp:scormtype';
-		$attributes[1][] = 'sco';
-		$attributes[0][] = 'href';
-		$attributes[1][] = $circle1_files[0][$i];
-		$org .= "  ".xmltagwrite('resource', 'open', $attributes);
-
-		$org .= "    ".xmltagwrite('metadata', 'open');
-		$org .= "      ".xmltagwrite('schema', 'full', 'ADL SCORM');
-		$org .= "      ".xmltagwrite('schemaversion', 'full', '1.2');
-		$org .= "    ".xmltagwrite('metadata', 'close');
-
-		$attributes = '';
-		$attributes[0][] = 'href';
-		$attributes[1][] = $circle1_files[0][$i];
-		$org .= "    ".xmltagwrite('file', 'open', $attributes);
-
-		$org .= "  ".xmltagwrite('resource', 'close');
-		$i ++;
-	}
-
-	$org .= xmltagwrite('resources', 'close');
-	$org .= xmltagwrite('manifest', 'close');
-	$manifest = $header.$org;
-
-	exporttofile('imsmanifest.xml', 'Manifest file', '0', $manifest);
-}
-
-/**
-	* Gets the tags of the file given as parameter
-	*
-	* if $filename is not found, GetSRCTags(filename) will return FALSE
-	* @param	string	file path
-	* @return	mixed		array of strings on success, false on failure
-	* @author unknown
+	$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
+	$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+	$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+
+	include_once ('../metadata/md_funcs.php'); // RH: export metadata
+
+	//1.1 header
+	/*
+		$header='<?xml version="1.0" encoding="UTF-8"?><manifest identifier="'.$LPnamesafe.'" xmlns="http://www.imsglobal.org/xsd/imscp_v1p1" xmlns:imsmd="http://www.imsglobal.org/xsd/imsmd_v1p2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2.xsd" version="IMS CP 1.1.3">'."\n";
+	*/
+
+	//1.2
+	//charset should be dependent on content
+	//$mycharset = 'ISO-8859-1';
+	$mycharset = $charset;
+	$header = '<?xml version="1.0" encoding="'.$mycharset.'"?>'."\n<manifest identifier='".$LPnamesafe."' version='1.1'\n xmlns='http://www.imsproject.org/xsd/imscp_rootv1p1p2'\n xmlns:adlcp='http://www.adlnet.org/xsd/adlcp_rootv1p2'\n xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n xsi:schemaLocation='http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd\n http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd\n http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd'>\n";
+
+	$org .= xmltagwrite('metadata', 'open');
+	$org .= "  ".xmltagwrite('schema', 'full', 'ADL SCORM');
+	$org .= "  ".xmltagwrite('schemaversion', 'full', '1.2');
+	$org .= xmltagwrite('metadata', 'close');
+
+	$defaultorgname = 'default_org';
+
+	$attributes[0][0] = 'default';
+	$attributes[1][0] = $defaultorgname;
+	$org .= xmltagwrite('organizations', 'open', $attributes);
+
+	$attributes[0][0] = 'identifier';
+	$attributes[1][0] = $defaultorgname;
+	$org .= "  ".xmltagwrite('organization', 'open', $attributes);
+
+	$org .= "    ".xmltagwrite('title', 'full', $LPname);
+
+	//items list
+	$i = 0;
+	$previous_item_id = '00';
+	while ($circle1_files[0][$i])
+	{
+		//check whether we are in the border of two chapters
+		//if (!$desc=strpos($circle1_files[2][$i],'scription')) {  //this is is needed if the descriptions are exported to file
+
+		$sql = "SELECT * FROM $tbl_learnpath_item WHERE (id=".$circle1_files[2][$i].")";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		$row = mysql_fetch_array($result);
+		$parent_item_id = $row['parent_item_id'];
+
+		if ($parent_item_id != $previous_item_id)
+		{
+			//we create the item tag for the chapter (without indifierref)
+			$sql2 = "SELECT * FROM $tbl_learnpath_chapter WHERE (id=".$parent_item_id.")";
+			$result2 = Database::query($sql2, __FILE__, __LINE__);
+			$row2 = mysql_fetch_array($result2);
+			$chapter_name = $row2['chapter_name'];
+
+			$attributes = '';
+			$attributes[0][] = 'identifier';
+			$attributes[1][] = 'chapter_'.$row2['id'];
+			$attributes[0][] = 'isvisible';
+			$attributes[1][] = '1';
+			if ($previous_item_id != '00')
+			{
+				$org .= "    ".xmltagwrite('item', 'close');
+			}
+
+			$org .= "    ".xmltagwrite('item', 'open', $attributes);
+			$org .= "      ".xmltagwrite('title', 'full', $chapter_name);
+
+			if ($row2['chapter_description'] != '')
+			{
+				//chapter description
+				$attributes = '';
+				$attributes[0][] = 'identifier';
+				$attributes[1][] = 'chapter_'.$row2['id'].'_desc';
+				$attributes[0][] = 'isvisible';
+				$attributes[1][] = '1';
+				$org .= "    ".xmltagwrite('item', 'open', $attributes);
+				$org .= "      ".xmltagwrite('title', 'full', ' '.$row2['chapter_description']);
+				$org .= "    ".xmltagwrite('item', 'close');
+			}
+		}
+		$previous_item_id = $parent_item_id;
+		//}
+
+		$attributes = ''; //item output
+		$attributes[0][] = 'identifier';
+		$attributes[1][] = 'item_'.$circle1_files[2][$i];
+		$attributes[0][] = 'identifierref';
+		$attributes[1][] = 'item_ref_'.$circle1_files[2][$i];
+		$attributes[0][] = 'isvisible';
+		$attributes[1][] = '1';
+		$org .= "    ".xmltagwrite('item', 'open', $attributes);
+		$org .= "      ".xmltagwrite('title', 'full', $circle1_files[1][$i]);
+
+		if ($row['prereq_id'] != '')
+		{ //item prerequisites
+			$attributes = '';
+			$attributes[0][] = 'type';
+			$attributes[1][] = 'aicc_script';
+			$org .= "      ".xmltagwrite('adlcp:prerequisites', 'open', $attributes, "no_linebreak");
+			if ($row['prereq_type'] == 'i')
+			{
+				$org .= 'item_'.$row['prereq_id'];
+			}
+			if ($row['prereq_type'] == 'c')
+			{
+				$org .= 'chapter_'.$row['prereq_id'];
+			}
+			$org .= xmltagwrite('adlcp:prerequisites', 'close', $attributes);
+		}
+
+		if ($row['description'] != '')
+		{
+			//item description
+			$attributes = '';
+			$attributes[0][] = 'identifier';
+			$attributes[1][] = 'item_'.$circle1_files[2][$i].'_desc';
+			$attributes[0][] = 'isvisible';
+			$attributes[1][] = '1';
+			$org .= "    ".xmltagwrite('item', 'open', $attributes);
+			$org .= "      ".xmltagwrite('title', 'full', ' '.$row['description']);
+			$org .= "    ".xmltagwrite('item', 'close');
+		}
+
+		$mds = new mdstore(TRUE); // RH: export metadata; if no table, create it
+		if (($mdt = $mds->mds_get($row['item_type'].'.'.$row['item_id'])))
+			if (($mdo = api_strpos($mdt, '<metadata>')) && ($mdc = api_strpos($mdt, '</metadata>')))
+				$org .= "    ".api_substr($mdt, $mdo, $mdc - $mdo +11)."\n";
+
+		$org .= "    ".xmltagwrite('item', 'close');
+		$i ++;
+	}
+
+	if ($circle1_files)
+	{
+		$org .= "    ".xmltagwrite('item', 'close');
+	} //not needed in case of a blank path
+	$org .= "  ".xmltagwrite('organization', 'close');
+	$org .= xmltagwrite('organizations', 'close');
+	$org .= xmltagwrite('resources', 'open');
+
+	//resources list
+	$i = 0;
+	while ($circle1_files[0][$i])
+	{
+		$attributes = '';
+		$attributes[0][] = 'identifier';
+		$attributes[1][] = 'item_ref_'.$circle1_files[2][$i];
+		$attributes[0][] = 'type';
+		$attributes[1][] = 'webcontent';
+		$attributes[0][] = 'adlcp:scormtype';
+		$attributes[1][] = 'sco';
+		$attributes[0][] = 'href';
+		$attributes[1][] = $circle1_files[0][$i];
+		$org .= "  ".xmltagwrite('resource', 'open', $attributes);
+
+		$org .= "    ".xmltagwrite('metadata', 'open');
+		$org .= "      ".xmltagwrite('schema', 'full', 'ADL SCORM');
+		$org .= "      ".xmltagwrite('schemaversion', 'full', '1.2');
+		$org .= "    ".xmltagwrite('metadata', 'close');
+
+		$attributes = '';
+		$attributes[0][] = 'href';
+		$attributes[1][] = $circle1_files[0][$i];
+		$org .= "    ".xmltagwrite('file', 'open', $attributes);
+
+		$org .= "  ".xmltagwrite('resource', 'close');
+		$i ++;
+	}
+
+	$org .= xmltagwrite('resources', 'close');
+	$org .= xmltagwrite('manifest', 'close');
+	$manifest = $header.$org;
+
+	exporttofile('imsmanifest.xml', 'Manifest file', '0', $manifest);
+}
+
+/**
+	* Gets the tags of the file given as parameter
+	*
+	* if $filename is not found, GetSRCTags(filename) will return FALSE
+	* @param	string	file path
+	* @return	mixed		array of strings on success, false on failure
+	* @author unknown
 	* @author included by imandak80
-	*/
-function GetSRCTags($fileName)
-{
-	if (!($fp = fopen($fileName, "r")))
-	{
-		//if file can't be opened, return false
-		return false;
-	}
-	//read file contents
-	$contents = fread($fp, filesize($fileName));
-	fclose($fp);
-
-	$matches = array ();
-	$srcList = array ();
-	//get all src tags contents in this file. Use multi-line search.
-	preg_match_all('/src(\s)*=(\s)*[\'"]([^\'"]*)[\'"]/mi', $contents, $matches); //get the img src as contained between " or '
-
-	foreach ($matches[3] as $match)
-	{
-		if (!in_array($match, $srcList))
-		{
-			$srcList[] = $match;
-		}
-	}
-	if (count($srcList) == 0)
-	{
-		return false;
-	}
-	return $srcList;
-}
-
-/**
- * Copy file and create directories in the path if needed.
- *
- * @param	string	$source Source path
+	*/
+function GetSRCTags($fileName)
+{
+	if (!($fp = fopen($fileName, "r")))
+	{
+		//if file can't be opened, return false
+		return false;
+	}
+	//read file contents
+	$contents = fread($fp, filesize($fileName));
+	fclose($fp);
+
+	$matches = array ();
+	$srcList = array ();
+	//get all src tags contents in this file. Use multi-line search.
+	preg_match_all('/src(\s)*=(\s)*[\'"]([^\'"]*)[\'"]/mi', $contents, $matches); //get the img src as contained between " or '
+
+	foreach ($matches[3] as $match)
+	{
+		if (!in_array($match, $srcList))
+		{
+			$srcList[] = $match;
+		}
+	}
+	if (count($srcList) == 0)
+	{
+		return false;
+	}
+	return $srcList;
+}
+
+/**
+ * Copy file and create directories in the path if needed.
+ *
+ * @param	string	$source Source path
  * @param	string	$dest Destination path
- * @return boolean 	true on success, false on failure
- */
-function CopyNCreate($source, $dest)
-{
-	if (strcmp($source, $dest) == 0)
-		return false;
-
-	$dir = "";
-	$tdest = explode('/', $dest);
-	for ($i = 0; $i < sizeof($tdest) - 1; $i ++)
-	{
-		$dir = $dir.$tdest[$i]."/";
-		if (!is_dir($dir))
-			if (!mkdir($dir))
-				return false;
-	}
-
-	if (!copy($source, $dest))
-		return false;
-
-	return true;
-}
-
-function rcopy($source, $dest)
-{
-	//error_log($source." -> ".$dest,0);
-	if (!file_exists($source))
-	{
-		//error_log($source." does not exist",0);
-		return false;
-	}
-
-	if (is_dir($source))
-	{
-		//error_log($source." is a dir",0);
-		//this is a directory
-		//remove trailing '/'
-		if (strrpos($source, '/') == sizeof($source) - 1)
-		{
-			$source = substr($source, 0, size_of($source) - 1);
-		}
-		if (strrpos($dest, '/') == sizeof($dest) - 1)
-		{
-			$dest = substr($dest, 0, size_of($dest) - 1);
-		}
-
-		if (!is_dir($dest))
-		{
-			$res = @ mkdir($dest);
-			if ($res === true)
-			{
-				return true;
-			}
-			else
-			{
-				//remove latest part of path and try creating that
-				if (rcopy(substr($source, 0, strrpos($source, '/')), substr($dest, 0, strrpos($dest, '/'))))
-				{
-					return @ mkdir($dest);
-				}
-				else
-				{
-					return false;
-				}
-			}
-		}
-		return true;
-	}
-	else
-	{
-		//this is presumably a file
-		//error_log($source." is a file",0);
-		if (!@ copy($source, $dest))
-		{
-			//error_log("Could not simple-copy $source",0);
-			$res = rcopy(dirname($source), dirname($dest));
-			if ($res === true)
-			{
-				//error_log("Welcome dir created",0);
-				return @ copy($source, $dest);
-			}
-			else
-			{
-				return false;
-				//error_log("Error creating path",0);
-			}
-		}
-		else
-		{
-			//error_log("Could well simple-copy $source",0);
-			return true;
-		}
-	}
-}
-?>
+ * @return boolean 	true on success, false on failure
+ */
+function CopyNCreate($source, $dest)
+{
+	if (strcmp($source, $dest) == 0)
+		return false;
+
+	$dir = "";
+	$tdest = explode('/', $dest);
+	for ($i = 0; $i < sizeof($tdest) - 1; $i ++)
+	{
+		$dir = $dir.$tdest[$i]."/";
+		if (!is_dir($dir))
+			if (!mkdir($dir))
+				return false;
+	}
+
+	if (!copy($source, $dest))
+		return false;
+
+	return true;
+}
+
+function rcopy($source, $dest)
+{
+	//error_log($source." -> ".$dest,0);
+	if (!file_exists($source))
+	{
+		//error_log($source." does not exist",0);
+		return false;
+	}
+
+	if (is_dir($source))
+	{
+		//error_log($source." is a dir",0);
+		//this is a directory
+		//remove trailing '/'
+		if (strrpos($source, '/') == sizeof($source) - 1)
+		{
+			$source = substr($source, 0, size_of($source) - 1);
+		}
+		if (strrpos($dest, '/') == sizeof($dest) - 1)
+		{
+			$dest = substr($dest, 0, size_of($dest) - 1);
+		}
+
+		if (!is_dir($dest))
+		{
+			$res = @ mkdir($dest);
+			if ($res === true)
+			{
+				return true;
+			}
+			else
+			{
+				//remove latest part of path and try creating that
+				if (rcopy(substr($source, 0, strrpos($source, '/')), substr($dest, 0, strrpos($dest, '/'))))
+				{
+					return @ mkdir($dest);
+				}
+				else
+				{
+					return false;
+				}
+			}
+		}
+		return true;
+	}
+	else
+	{
+		//this is presumably a file
+		//error_log($source." is a file",0);
+		if (!@ copy($source, $dest))
+		{
+			//error_log("Could not simple-copy $source",0);
+			$res = rcopy(dirname($source), dirname($dest));
+			if ($res === true)
+			{
+				//error_log("Welcome dir created",0);
+				return @ copy($source, $dest);
+			}
+			else
+			{
+				return false;
+				//error_log("Error creating path",0);
+			}
+		}
+		else
+		{
+			//error_log("Could well simple-copy $source",0);
+			return true;
+		}
+	}
+}
+?>

+ 158 - 158
main/newscorm/lp_add.php

@@ -1,170 +1,170 @@
-<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
-==============================================================================
-*/
-
-/**
+<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
+/*
 ==============================================================================
-* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
-*
-* @author Patrick Cool
-* @author Denes Nagy
-* @author Roan Embrechts, refactoring and code cleaning
-* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
-* @package dokeos.learnpath
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
 ==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
 */
-$this_section=SECTION_COURSES;
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+
+/**
+==============================================================================
+* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
+*
+* @author Patrick Cool
+* @author Denes Nagy
+* @author Roan Embrechts, refactoring and code cleaning
+* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
+* @package dokeos.learnpath
+==============================================================================
+*/
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
 */
-//the main_api.lib.php, database.lib.php and display.lib.php
-//libraries are included by default
-
-include('learnpath_functions.inc.php');
-//include('../resourcelinker/resourcelinker.inc.php');
-include('resourcelinker.inc.php');
-//rewrite the language file, sadly overwritten by resourcelinker.inc.php
+$this_section=SECTION_COURSES;
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+//the main_api.lib.php, database.lib.php and display.lib.php
+//libraries are included by default
+
+include('learnpath_functions.inc.php');
+//include('../resourcelinker/resourcelinker.inc.php');
+include('resourcelinker.inc.php');
+//rewrite the language file, sadly overwritten by resourcelinker.inc.php
 // name of the language file that needs to be included
-$language_file = 'learnpath';
-
-/*
------------------------------------------------------------
-	Header and action code
------------------------------------------------------------
+$language_file = 'learnpath';
+
+/*
+-----------------------------------------------------------
+	Header and action code
+-----------------------------------------------------------
+*/
+$currentstyle = api_get_setting('stylesheets');
+//$htmlHeadXtra[] = '<link rel="stylesheet" type="text/css" href="'.api_get_path(WEB_CODE_PATH).'css/'.$currentstyle.'/learnpath.css"/>';
+//$htmlHeadXtra[] = '<link rel="stylesheet" type="text/css" href="learnpath.css" />'; //will be a merged with original learnpath.css
+$htmlHeadXtra[] = '<link rel="stylesheet" type="text/css" href="dtree.css" />'; //will be moved
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
 */
-$currentstyle = api_get_setting('stylesheets');
-//$htmlHeadXtra[] = '<link rel="stylesheet" type="text/css" href="'.api_get_path(WEB_CODE_PATH).'css/'.$currentstyle.'/learnpath.css"/>';
-//$htmlHeadXtra[] = '<link rel="stylesheet" type="text/css" href="learnpath.css" />'; //will be a merged with original learnpath.css
-$htmlHeadXtra[] = '<link rel="stylesheet" type="text/css" href="dtree.css" />'; //will be moved
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
+$is_allowed_to_edit = api_is_allowed_to_edit();
+
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
+
+$isStudentView  = (int) $_REQUEST['isStudentView'];
+$learnpath_id   = (int) $_REQUEST['lp_id'];
+$submit			= $_POST['submit_button'];
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
 */
-$is_allowed_to_edit = api_is_allowed_to_edit();
-
-$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
-
-$isStudentView  = (int) $_REQUEST['isStudentView'];
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-$submit			= $_POST['submit_button'];
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-// using the resource linker as a tool for adding resources to the learning path
-if ($action=="add" and $type=="learnpathitem")
-{
-	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
-}
-if ( (! $is_allowed_to_edit) or ($isStudentView) )
-{
-	error_log('New LP - User not authorized in lp_add.php');
-	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
-}
-//from here on, we are admin because of the previous condition, so don't check anymore
-
+// using the resource linker as a tool for adding resources to the learning path
+if ($action=="add" and $type=="learnpathitem")
+{
+	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
+}
+if ( (! $is_allowed_to_edit) or ($isStudentView) )
+{
+	error_log('New LP - User not authorized in lp_add.php');
+	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
+}
+//from here on, we are admin because of the previous condition, so don't check anymore
+
 $sql_query = "SELECT * FROM $tbl_lp WHERE id = $learnpath_id";
-$result=Database::query($sql_query);
+$result=Database::query($sql_query);
 $therow=Database::fetch_array($result);
-
-/*
------------------------------------------------------------
-	Course admin section
-	- all the functions not available for students - always available in this case (page only shown to admin)
------------------------------------------------------------
+
+/*
+-----------------------------------------------------------
+	Course admin section
+	- all the functions not available for students - always available in this case (page only shown to admin)
+-----------------------------------------------------------
 */
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
-$interbreadcrumb[]= array ("url"=>"#", "name"=> get_lang("_add_learnpath"));
-
-Display::display_header(null,'Path');
-
-echo '<div class="actions">';
-echo '<a href="lp_controller.php?cidReq='.$_course['sysCode'].'">'.Display::return_icon('scorm.gif',get_lang('ReturnToLearningPaths')).' '.get_lang('ReturnToLearningPaths').'</a>';
-echo '</div>';
-
-Display::display_normal_message(get_lang('AddLpIntro'),false);
-
-if ($_POST AND empty($_REQUEST['learnpath_name']))
-{
-	Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'), false);
-}
-
-echo '<form method="post">';
-
-// form title
-echo '<div class="row"><div class="form_header">'.get_lang('AddLpToStart').'</div></div>';
-
-// title field
-echo '<div class="row">';
-echo '<div class="label">';
-echo '<label for="idTitle"><span class="form_required">*</span> '.get_lang('LPName').'</label>';
-echo '</div>';
-echo '<div class="formw">';
-echo '<input id="idTitle" name="learnpath_name" type="text" size="50" />';
-echo '</div>';
-echo '</div>';
-
-// submit button
-echo '<div class="row">';
-echo '<div class="label">';
-echo '</div>';
-echo '<div class="formw">';
-echo '<button  class="save" style="width:150px;" type="submit"/>'.get_lang('CreateLearningPath').'</button>';
-echo '</div>';
-echo '</div>';
-echo '<input name="post_time" type="hidden" value="' . time() . '" />';
-echo '</form>';
-
-echo '<div class="row">';
-echo '<div class="label"></div>';
-echo '<div class="formw"><span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small></div>';
-echo '</div>';
-
-// footer
-Display::display_footer();
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
+$interbreadcrumb[]= array ("url"=>"#", "name"=> get_lang("_add_learnpath"));
+
+Display::display_header(null,'Path');
+
+echo '<div class="actions">';
+echo '<a href="lp_controller.php?cidReq='.$_course['sysCode'].'">'.Display::return_icon('scorm.gif',get_lang('ReturnToLearningPaths')).' '.get_lang('ReturnToLearningPaths').'</a>';
+echo '</div>';
+
+Display::display_normal_message(get_lang('AddLpIntro'),false);
+
+if ($_POST AND empty($_REQUEST['learnpath_name']))
+{
+	Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'), false);
+}
+
+echo '<form method="post">';
+
+// form title
+echo '<div class="row"><div class="form_header">'.get_lang('AddLpToStart').'</div></div>';
+
+// title field
+echo '<div class="row">';
+echo '<div class="label">';
+echo '<label for="idTitle"><span class="form_required">*</span> '.get_lang('LPName').'</label>';
+echo '</div>';
+echo '<div class="formw">';
+echo '<input id="idTitle" name="learnpath_name" type="text" size="50" />';
+echo '</div>';
+echo '</div>';
+
+// submit button
+echo '<div class="row">';
+echo '<div class="label">';
+echo '</div>';
+echo '<div class="formw">';
+echo '<button  class="save" style="width:150px;" type="submit"/>'.get_lang('CreateLearningPath').'</button>';
+echo '</div>';
+echo '</div>';
+echo '<input name="post_time" type="hidden" value="' . time() . '" />';
+echo '</form>';
+
+echo '<div class="row">';
+echo '<div class="label"></div>';
+echo '<div class="formw"><span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small></div>';
+echo '</div>';
+
+// footer
+Display::display_footer();
 ?>

+ 263 - 263
main/newscorm/lp_admin_view.php

@@ -1,293 +1,293 @@
-<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
-==============================================================================
-*/
-
-
-/**
+<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
+/*
 ==============================================================================
-* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
-*
-* @author Patrick Cool
-* @author Denes Nagy
-* @author Roan Embrechts, refactoring and code cleaning
-* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
-* @package dokeos.learnpath
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
 ==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
 */
-$this_section=SECTION_COURSES;
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+
+
+/**
+==============================================================================
+* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
+*
+* @author Patrick Cool
+* @author Denes Nagy
+* @author Roan Embrechts, refactoring and code cleaning
+* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
+* @package dokeos.learnpath
+==============================================================================
 */
-//the main_api.lib.php, database.lib.php and display.lib.php
-//libraries are included by default
-
-include('learnpath_functions.inc.php');
-//include('../resourcelinker/resourcelinker.inc.php');
-include('resourcelinker.inc.php');
-//rewrite the language file, sadly overwritten by resourcelinker.inc.php
-$language_file = "learnpath";
-
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+$this_section=SECTION_COURSES;
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
 */
-$is_allowed_to_edit = api_is_allowed_to_edit();
-
-$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
-
-$isStudentView  = (int) $_REQUEST['isStudentView'];
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-$submit			= $_POST['submit_button'];
-/*
-$chapter_id     = $_GET['chapter_id'];
-$title          = $_POST['title'];
-$description   = $_POST['description'];
-$Submititem     = $_POST['Submititem'];
-$action         = $_REQUEST['action'];
-$id             = (int) $_REQUEST['id'];
-$type           = $_REQUEST['type'];
-$direction      = $_REQUEST['direction'];
-$moduleid       = $_REQUEST['moduleid'];
-$prereq         = $_REQUEST['prereq'];
-$type           = $_REQUEST['type'];
-*/
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-// using the resource linker as a tool for adding resources to the learning path
-if ($action=="add" and $type=="learnpathitem")
-{
-	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
-}
-if ( (! $is_allowed_to_edit) or ($isStudentView) )
-{
-	error_log('New LP - User not authorized in lp_admin_view.php');
-	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
-}
-//from here on, we are admin because of the previous condition, so don't check anymore
-
+//the main_api.lib.php, database.lib.php and display.lib.php
+//libraries are included by default
+
+include('learnpath_functions.inc.php');
+//include('../resourcelinker/resourcelinker.inc.php');
+include('resourcelinker.inc.php');
+//rewrite the language file, sadly overwritten by resourcelinker.inc.php
+$language_file = "learnpath";
+
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
+*/
+$is_allowed_to_edit = api_is_allowed_to_edit();
+
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
+
+$isStudentView  = (int) $_REQUEST['isStudentView'];
+$learnpath_id   = (int) $_REQUEST['lp_id'];
+$submit			= $_POST['submit_button'];
+/*
+$chapter_id     = $_GET['chapter_id'];
+$title          = $_POST['title'];
+$description   = $_POST['description'];
+$Submititem     = $_POST['Submititem'];
+$action         = $_REQUEST['action'];
+$id             = (int) $_REQUEST['id'];
+$type           = $_REQUEST['type'];
+$direction      = $_REQUEST['direction'];
+$moduleid       = $_REQUEST['moduleid'];
+$prereq         = $_REQUEST['prereq'];
+$type           = $_REQUEST['type'];
+*/
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+// using the resource linker as a tool for adding resources to the learning path
+if ($action=="add" and $type=="learnpathitem")
+{
+	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
+}
+if ( (! $is_allowed_to_edit) or ($isStudentView) )
+{
+	error_log('New LP - User not authorized in lp_admin_view.php');
+	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
+}
+//from here on, we are admin because of the previous condition, so don't check anymore
+
 $sql_query = "SELECT * FROM $tbl_lp WHERE id = $learnpath_id";
-$result=Database::query($sql_query);
+$result=Database::query($sql_query);
 $therow=Database::fetch_array($result);
-
-//$admin_output = '';
-/*
------------------------------------------------------------
-	Course admin section
-	- all the functions not available for students - always available in this case (page only shown to admin)
------------------------------------------------------------
+
+//$admin_output = '';
+/*
+-----------------------------------------------------------
+	Course admin section
+	- all the functions not available for students - always available in this case (page only shown to admin)
+-----------------------------------------------------------
 */
-/*==================================================
-			SHOWING THE ADMIN TOOLS
- ==================================================*/
-
-
-
-/*==================================================
-	prerequisites setting end
+/*==================================================
+			SHOWING THE ADMIN TOOLS
  ==================================================*/
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+
+
+
+/*==================================================
+	prerequisites setting end
+ ==================================================*/
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
-
-$interbreadcrumb[]= array ("url"=>api_get_self()."?action=admin_view&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
-
-//Theme calls
-$show_learn_path=true;
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
+
+$interbreadcrumb[]= array ("url"=>api_get_self()."?action=admin_view&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
+
+//Theme calls
+$show_learn_path=true;
 $lp_theme_css=$_SESSION['oLP']->get_theme();
-Display::display_header(null,'Path');
-//api_display_tool_title($therow['name']);
-
-$suredel = trim(get_lang('AreYouSureToDelete'));
-//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
-?>
-<script type='text/javascript'>
-/* <![CDATA[ */
-function stripslashes(str) {
-	str=str.replace(/\\'/g,'\'');
-	str=str.replace(/\\"/g,'"');
-	str=str.replace(/\\\\/g,'\\');
-	str=str.replace(/\\0/g,'\0');
-	return str;
-}
-function confirmation(name)
-{
+Display::display_header(null,'Path');
+//api_display_tool_title($therow['name']);
+
+$suredel = trim(get_lang('AreYouSureToDelete'));
+//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
+?>
+<script type='text/javascript'>
+/* <![CDATA[ */
+function stripslashes(str) {
+	str=str.replace(/\\'/g,'\'');
+	str=str.replace(/\\"/g,'"');
+	str=str.replace(/\\\\/g,'\\');
+	str=str.replace(/\\0/g,'\0');
+	return str;
+}
+function confirmation(name)
+{
 	name=stripslashes(name);
-	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
-	{
-		return true;
-	}
-	else
-	{
-		return false;
+	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
+	{
+		return true;
+	}
+	else
+	{
+		return false;
 	}
-}
-</script>
-<?php
-
-/*
------------------------------------------------------------
-	DISPLAY SECTION
------------------------------------------------------------
-*/
-
-switch($_GET['action'])
-{
-	case 'edit_item':
-
-		if(isset($is_success) && $is_success === true)
-		{
-			Display::display_confirmation_message(get_lang("_learnpath_item_edited"));
-		}
-		else
-		{
-			echo $_SESSION['oLP']->display_edit_item($_GET['id']);
-		}
-
-		break;
-
-	case 'delete_item':
-
-		if(isset($is_success) && $is_success === true)
-		{
-			Display::display_confirmation_message(get_lang("_learnpath_item_deleted"));
-		}
-
-		break;
-}
-
-// POST action handling (uploading mp3, deleting mp3)
-if (isset($_POST['save_audio']))
-{
-	// deleting the audio fragments
-	foreach ($_POST as $key=>$value) {
-		if (substr($key,0,9) == 'removemp3') {
+}
+</script>
+<?php
+
+/*
+-----------------------------------------------------------
+	DISPLAY SECTION
+-----------------------------------------------------------
+*/
+
+switch($_GET['action'])
+{
+	case 'edit_item':
+
+		if(isset($is_success) && $is_success === true)
+		{
+			Display::display_confirmation_message(get_lang("_learnpath_item_edited"));
+		}
+		else
+		{
+			echo $_SESSION['oLP']->display_edit_item($_GET['id']);
+		}
+
+		break;
+
+	case 'delete_item':
+
+		if(isset($is_success) && $is_success === true)
+		{
+			Display::display_confirmation_message(get_lang("_learnpath_item_deleted"));
+		}
+
+		break;
+}
+
+// POST action handling (uploading mp3, deleting mp3)
+if (isset($_POST['save_audio']))
+{
+	// deleting the audio fragments
+	foreach ($_POST as $key=>$value) {
+		if (substr($key,0,9) == 'removemp3') {
 			$lp_items_to_remove_audio[] = str_ireplace('removemp3','',$key);
-			// removing the audio from the learning path item
-			$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-			$in = implode(',',$lp_items_to_remove_audio);
-		}
-	}
-	if (count($lp_items_to_remove_audio)>0) {
-		$sql 	= "UPDATE $tbl_lp_item SET audio = '' WHERE id IN (".$in.")";
-		$result = Database::query($sql, __FILE__, __LINE__);
+			// removing the audio from the learning path item
+			$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+			$in = implode(',',$lp_items_to_remove_audio);
+		}
 	}
+	if (count($lp_items_to_remove_audio)>0) {
+		$sql 	= "UPDATE $tbl_lp_item SET audio = '' WHERE id IN (".$in.")";
+		$result = Database::query($sql, __FILE__, __LINE__);
+	}
+
+	// uploading the audio files
+	foreach ($_FILES as $key=>$value)
+	{
+		if (substr($key,0,7) == 'mp3file' AND !empty($_FILES[$key]['tmp_name']))
+		{
+			// the id of the learning path item
+			$lp_item_id = str_ireplace('mp3file','',$key);
 
-	// uploading the audio files
-	foreach ($_FILES as $key=>$value)
-	{
-		if (substr($key,0,7) == 'mp3file' AND !empty($_FILES[$key]['tmp_name']))
-		{
-			// the id of the learning path item
-			$lp_item_id = str_ireplace('mp3file','',$key);
-
-			// create the audio folder if it does not exist yet
-			global $_course;
-			$filepath = api_get_path('SYS_COURSE_PATH').$_course['path'].'/document/';
-			if(!is_dir($filepath.'audio'))
-			{
-				$perm = api_get_setting('permissions_for_new_directories');
-				$perm = octdec(!empty($perm)?$perm:'0770');
-				mkdir($filepath.'audio',$perm);
-				$audio_id=add_document($_course,'/audio','folder',0,'audio');
+			// create the audio folder if it does not exist yet
+			global $_course;
+			$filepath = api_get_path('SYS_COURSE_PATH').$_course['path'].'/document/';
+			if(!is_dir($filepath.'audio'))
+			{
+				$perm = api_get_setting('permissions_for_new_directories');
+				$perm = octdec(!empty($perm)?$perm:'0770');
+				mkdir($filepath.'audio',$perm);
+				$audio_id=add_document($_course,'/audio','folder',0,'audio');
 				api_item_property_update($_course, TOOL_DOCUMENT, $audio_id, 'FolderCreated', api_get_user_id());
-			}
+			}
 
 			// check if file already exits into document/audio/
-			$file_name = $_FILES[$key]['name'];
-			$file_name=stripslashes($file_name);
-			//add extension to files without one (if possible)
-			$file_name=add_ext_on_mime($file_name,$_FILES[$key]['type']);
-
-			$clean_name = replace_dangerous_char($file_name);
-			$clean_name = replace_accents($clean_name);
-			//no "dangerous" files
+			$file_name = $_FILES[$key]['name'];
+			$file_name=stripslashes($file_name);
+			//add extension to files without one (if possible)
+			$file_name=add_ext_on_mime($file_name,$_FILES[$key]['type']);
+
+			$clean_name = replace_dangerous_char($file_name);
+			$clean_name = replace_accents($clean_name);
+			//no "dangerous" files
 			$clean_name = disable_dangerous_file($clean_name);
-
-			$check_file_path = api_get_path('SYS_COURSE_PATH').$_course['path'].'/document/audio/'.$clean_name;
+
+			$check_file_path = api_get_path('SYS_COURSE_PATH').$_course['path'].'/document/audio/'.$clean_name;
 
 			// if the file exists we generate a new name
-			if (file_exists($check_file_path)) {
-				$filename_components = explode('.',$clean_name);
-				// gettting the extension of the file
-				$file_extension = $filename_components[count($filename_components)-1];
-				// adding something random to prevent overwriting
-				$filename_components[count($filename_components)-1] = time();
-				// reconstructing the new filename
-				$clean_name = implode($filename_components) .'.'.$file_extension;
-				// using the new name in the $_FILES superglobal
-				$_FILES[$key]['name'] = $clean_name;
-
-			}
-
-			// upload the file in the documents tool
-			include_once(api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php');
+			if (file_exists($check_file_path)) {
+				$filename_components = explode('.',$clean_name);
+				// gettting the extension of the file
+				$file_extension = $filename_components[count($filename_components)-1];
+				// adding something random to prevent overwriting
+				$filename_components[count($filename_components)-1] = time();
+				// reconstructing the new filename
+				$clean_name = implode($filename_components) .'.'.$file_extension;
+				// using the new name in the $_FILES superglobal
+				$_FILES[$key]['name'] = $clean_name;
+
+			}
+
+			// upload the file in the documents tool
+			include_once(api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php');
 			$file_path = handle_uploaded_document($_course, $_FILES[$key],api_get_path('SYS_COURSE_PATH').$_course['path'].'/document','/audio',api_get_user_id(),'','','','','',false);
 
-			// getting the filename only
-			$file_components = explode('/',$file_path);
+			// getting the filename only
+			$file_components = explode('/',$file_path);
 			$file = $file_components[count($file_components)-1];
-
-			// store the mp3 file in the lp_item table
-			$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-			$sql_insert_audio = "UPDATE $tbl_lp_item SET audio = '".Database::escape_string($file)."' WHERE id = '".Database::escape_string($lp_item_id)."'";
+
+			// store the mp3 file in the lp_item table
+			$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+			$sql_insert_audio = "UPDATE $tbl_lp_item SET audio = '".Database::escape_string($file)."' WHERE id = '".Database::escape_string($lp_item_id)."'";
 			Database::query($sql_insert_audio, __FILE__, __LINE__);
 
-		}
-	}
+		}
+	}
+
+	Display::display_confirmation_message(get_lang('ChangesStored'));
+}
 
-	Display::display_confirmation_message(get_lang('ChangesStored'));
-}
-
-echo $_SESSION['oLP']->overview();
-
-/*
-==============================================================================
+echo $_SESSION['oLP']->overview();
+
+/*
+==============================================================================
 		FOOTER
-==============================================================================
+==============================================================================
 */
-Display::display_footer();
-?>
+Display::display_footer();
+?>

+ 22 - 22
main/newscorm/lp_api.php

@@ -1,23 +1,23 @@
-<?php //$id: $
-/**
- * DEPRECATED (temporarily left here)
- * Script that displays the footer frame for lp_view.php
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-require_once('back_compat.inc.php');
-//require_once('lp_comm.common.php'); //xajax functions
-//$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/')."\n";
-//$htmlHeadXtra[] = '<script language="javascript">var myxajax = window.parent.oxajax;</script>';
-include_once('../inc/reduced_header.inc.php');
-?>
-<body>
-<!--div id="clickme" style="border: 1px solid black; width:10px; height:7px;" onclick="myxajax.xajax_get_statuses();"></div-->
-</body>
+<?php //$id: $
+/**
+ * DEPRECATED (temporarily left here)
+ * Script that displays the footer frame for lp_view.php
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+require_once('back_compat.inc.php');
+//require_once('lp_comm.common.php'); //xajax functions
+//$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/')."\n";
+//$htmlHeadXtra[] = '<script language="javascript">var myxajax = window.parent.oxajax;</script>';
+include_once('../inc/reduced_header.inc.php');
+?>
+<body>
+<!--div id="clickme" style="border: 1px solid black; width:10px; height:7px;" onclick="myxajax.xajax_get_statuses();"></div-->
+</body>
 </html>

+ 214 - 214
main/newscorm/lp_build.php

@@ -1,241 +1,241 @@
-<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
-==============================================================================
-*/
-
-
-/**
+<?php // $Id: index.php 16620 2008-10-25 20:03:54Z yannoo $
+/*
 ==============================================================================
-* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
-*
-* @author Patrick Cool
-* @author Denes Nagy
-* @author Roan Embrechts, refactoring and code cleaning
-* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
-* @package dokeos.learnpath
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, rue Notre Dame, 152, B-1140 Evere, Belgium, info@dokeos.com
+==============================================================================
+*/
+
+
+/**
+==============================================================================
+* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
+*
+* @author Patrick Cool
+* @author Denes Nagy
+* @author Roan Embrechts, refactoring and code cleaning
+* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
+* @package dokeos.learnpath
 ==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
 */
-$_SESSION['whereami'] = 'lp/build';
-$this_section=SECTION_COURSES;
-
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
 */
-//the main_api.lib.php, database.lib.php and display.lib.php
-//libraries are included by default
-
-include('learnpath_functions.inc.php');
-//include('../resourcelinker/resourcelinker.inc.php');
-include('resourcelinker.inc.php');
-//rewrite the language file, sadly overwritten by resourcelinker.inc.php
+$_SESSION['whereami'] = 'lp/build';
+$this_section=SECTION_COURSES;
+
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+//the main_api.lib.php, database.lib.php and display.lib.php
+//libraries are included by default
+
+include('learnpath_functions.inc.php');
+//include('../resourcelinker/resourcelinker.inc.php');
+include('resourcelinker.inc.php');
+//rewrite the language file, sadly overwritten by resourcelinker.inc.php
 // name of the language file that needs to be included
-$language_file = "learnpath";
-
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
+$language_file = "learnpath";
+
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
 */
-$is_allowed_to_edit = api_is_allowed_to_edit();
-
-$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
-
-$isStudentView  = (int) $_REQUEST['isStudentView'];
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-$submit			= $_POST['submit_button'];
-/*
-$chapter_id     = $_GET['chapter_id'];
-$title          = $_POST['title'];
-$description   = $_POST['description'];
-$Submititem     = $_POST['Submititem'];
-$action         = $_REQUEST['action'];
-$id             = (int) $_REQUEST['id'];
-$type           = $_REQUEST['type'];
-$direction      = $_REQUEST['direction'];
-$moduleid       = $_REQUEST['moduleid'];
-$prereq         = $_REQUEST['prereq'];
-$type           = $_REQUEST['type'];
-*/
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-// using the resource linker as a tool for adding resources to the learning path
-if ($action=="add" and $type=="learnpathitem")
-{
-	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
-}
-if ( (! $is_allowed_to_edit) or ($isStudentView) )
-{
-	error_log('New LP - User not authorized in lp_build.php');
-	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
-}
-//from here on, we are admin because of the previous condition, so don't check anymore
-
-/* learnpath is just created, go get the last id */
-$is_new = false;
-
-if($learnpath_id == 0)
-{
-	$is_new = true;
-
-	$sql = "
-		SELECT id
-		FROM " . $tbl_lp . "
-		ORDER BY id DESC
-		LIMIT 0, 1";
-	$result = Database::query($sql);
-	$row = Database::fetch_array($result);
-
-	$learnpath_id = $row['id'];
-}
-
-$sql_query = "SELECT * FROM $tbl_lp WHERE id = $learnpath_id";
-
-
-$result=Database::query($sql_query);
+$is_allowed_to_edit = api_is_allowed_to_edit();
+
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
+
+$isStudentView  = (int) $_REQUEST['isStudentView'];
+$learnpath_id   = (int) $_REQUEST['lp_id'];
+$submit			= $_POST['submit_button'];
+/*
+$chapter_id     = $_GET['chapter_id'];
+$title          = $_POST['title'];
+$description   = $_POST['description'];
+$Submititem     = $_POST['Submititem'];
+$action         = $_REQUEST['action'];
+$id             = (int) $_REQUEST['id'];
+$type           = $_REQUEST['type'];
+$direction      = $_REQUEST['direction'];
+$moduleid       = $_REQUEST['moduleid'];
+$prereq         = $_REQUEST['prereq'];
+$type           = $_REQUEST['type'];
+*/
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+// using the resource linker as a tool for adding resources to the learning path
+if ($action=="add" and $type=="learnpathitem")
+{
+	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
+}
+if ( (! $is_allowed_to_edit) or ($isStudentView) )
+{
+	error_log('New LP - User not authorized in lp_build.php');
+	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
+}
+//from here on, we are admin because of the previous condition, so don't check anymore
+
+/* learnpath is just created, go get the last id */
+$is_new = false;
+
+if($learnpath_id == 0)
+{
+	$is_new = true;
+
+	$sql = "
+		SELECT id
+		FROM " . $tbl_lp . "
+		ORDER BY id DESC
+		LIMIT 0, 1";
+	$result = Database::query($sql);
+	$row = Database::fetch_array($result);
+
+	$learnpath_id = $row['id'];
+}
+
+$sql_query = "SELECT * FROM $tbl_lp WHERE id = $learnpath_id";
+
+
+$result=Database::query($sql_query);
 $therow=Database::fetch_array($result);
-
-//$admin_output = '';
-/*
------------------------------------------------------------
-	Course admin section
-	- all the functions not available for students - always available in this case (page only shown to admin)
------------------------------------------------------------
+
+//$admin_output = '';
+/*
+-----------------------------------------------------------
+	Course admin section
+	- all the functions not available for students - always available in this case (page only shown to admin)
+-----------------------------------------------------------
 */
-/*==================================================
-			SHOWING THE ADMIN TOOLS
- ==================================================*/
-
-
-
-/*==================================================
-	prerequisites setting end
+/*==================================================
+			SHOWING THE ADMIN TOOLS
  ==================================================*/
-if (!empty($_GET['gradebook']) && $_GET['gradebook']=='view' ) {
-	$_SESSION['gradebook']=Security::remove_XSS($_GET['gradebook']);
-	$gradebook=	$_SESSION['gradebook'];
-} elseif (empty($_GET['gradebook'])) {
-	unset($_SESSION['gradebook']);
-	$gradebook=	'';
+
+
+
+/*==================================================
+	prerequisites setting end
+ ==================================================*/
+if (!empty($_GET['gradebook']) && $_GET['gradebook']=='view' ) {
+	$_SESSION['gradebook']=Security::remove_XSS($_GET['gradebook']);
+	$gradebook=	$_SESSION['gradebook'];
+} elseif (empty($_GET['gradebook'])) {
+	unset($_SESSION['gradebook']);
+	$gradebook=	'';
 }
-
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[] = array (
-		'url' => '../gradebook/' . $_SESSION['gradebook_dest'],
-		'name' => get_lang('Gradebook')
-	);
-}
-$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
-$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
-
-//Theme calls
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-$show_learn_path=true;
-Display::display_header(null,'Path');
-
-//api_display_tool_title($therow['name']);
-
-$suredel = trim(get_lang('AreYouSureToDelete'));
-//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
-?>
-<script type='text/javascript'>
-/* <![CDATA[ */
-function stripslashes(str) {
-	str=str.replace(/\\'/g,'\'');
-	str=str.replace(/\\"/g,'"');
-	str=str.replace(/\\\\/g,'\\');
-	str=str.replace(/\\0/g,'\0');
-	return str;
-}
-function confirmation(name)
-{
+	$interbreadcrumb[] = array (
+		'url' => '../gradebook/' . $_SESSION['gradebook_dest'],
+		'name' => get_lang('Gradebook')
+	);
+}
+$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
+$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
+
+//Theme calls
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+$show_learn_path=true;
+Display::display_header(null,'Path');
+
+//api_display_tool_title($therow['name']);
+
+$suredel = trim(get_lang('AreYouSureToDelete'));
+//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
+?>
+<script type='text/javascript'>
+/* <![CDATA[ */
+function stripslashes(str) {
+	str=str.replace(/\\'/g,'\'');
+	str=str.replace(/\\"/g,'"');
+	str=str.replace(/\\\\/g,'\\');
+	str=str.replace(/\\0/g,'\0');
+	return str;
+}
+function confirmation(name)
+{
 	name=stripslashes(name);
-	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
-	{
-		return true;
-	}
-	else
-	{
-		return false;
+	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
+	{
+		return true;
+	}
+	else
+	{
+		return false;
 	}
-}
-</script>
-<?php
-
-//echo $admin_output;
-/*
------------------------------------------------------------
-	DISPLAY SECTION
------------------------------------------------------------
-*/
-echo $_SESSION['oLP']->build_action_menu();
-echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
+}
+</script>
+<?php
+
+//echo $admin_output;
+/*
+-----------------------------------------------------------
+	DISPLAY SECTION
+-----------------------------------------------------------
+*/
+echo $_SESSION['oLP']->build_action_menu();
+echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
 	echo '<tr>';
 		echo '<td class="tree">';
 			echo '<div class="lp_tree">';
-				//build the tree with the menu items in it
+				//build the tree with the menu items in it
 				echo $_SESSION['oLP']->build_tree();
 			echo '</div>';
-		echo '</td>';
+		echo '</td>';
 		echo '<td class="workspace">';
-			if(isset($is_success) && $is_success === true) {
-				Display::display_confirmation_message(get_lang('ItemRemoved'));
-			} else {
-				if($is_new) {
-					Display::display_normal_message(get_lang('LearnpathAdded'), false);
+			if(isset($is_success) && $is_success === true) {
+				Display::display_confirmation_message(get_lang('ItemRemoved'));
+			} else {
+				if($is_new) {
+					Display::display_normal_message(get_lang('LearnpathAdded'), false);
 				}
-					// Display::display_normal_message(get_lang('LPCreatedAddChapterStep'), false);
-					$gradebook = Security::remove_XSS($_GET['gradebook']);
-					$learnpathadded = Display::return_icon('gallery/creative.gif','',array('align'=>'right'));
-					$learnpathadded .= '<p><strong>'.get_lang('LearnPathAddedTitle').'</strong><br /><br />';
-					$learnpathadded .= '<a href="lp_controller.php?'.api_get_cidreq().'&amp;action=build&amp;lp_id='.Security::remove_XSS($_GET['lp_id']).'" target="_parent">'.Display::return_icon('learnpath_build.gif', get_lang('Build'),array('style'=> 'vertical-align: middle;')).' '.get_lang('Build')."</a>: ".get_lang('BuildComment').'<br />';
-					$learnpathadded .= '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=admin_view&amp;lp_id=' . $_SESSION['oLP']->lp_id . '" title="'.get_lang("BasicOverview").'">'.Display::return_icon('learnpath_organize.gif', get_lang('BasicOverview'),array('style'=> 'vertical-align: middle;')).' '.get_lang('BasicOverview').'</a>: '.get_lang('BasicOverviewComment').'<br />';
-					$learnpathadded .= '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&action=view&lp_id='.$_SESSION['oLP']->lp_id.'">'.Display::return_icon('learnpath_view.gif', get_lang('Display'),array('style'=> 'vertical-align: middle;')).' '.get_lang('Display').'</a>: '.get_lang('DisplayComment').'<br />';
-					$learnpathadded .= '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=add_item&amp;type=chapter&amp;lp_id=' . $_SESSION['oLP']->lp_id . '" title="'.get_lang("NewChapter").'">'.Display::return_icon('lp_dokeos_chapter_add.gif', get_lang('NewChapter'),array('style'=> 'vertical-align: middle;')).' '.get_lang('NewChapter').'</a>: '.get_lang('NewChapterComment').'<br />';
-					$learnpathadded .= '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=add_item&amp;type=step&amp;lp_id=' . $_SESSION['oLP']->lp_id . '" title="'.get_lang("NewStep").'">'.Display::return_icon('new_test.gif', get_lang('NewStep'),array('style'=> 'vertical-align: middle;')).' '.get_lang('NewStep').'</a>: '.get_lang('NewStepComment').'<br />';
+					// Display::display_normal_message(get_lang('LPCreatedAddChapterStep'), false);
+					$gradebook = Security::remove_XSS($_GET['gradebook']);
+					$learnpathadded = Display::return_icon('gallery/creative.gif','',array('align'=>'right'));
+					$learnpathadded .= '<p><strong>'.get_lang('LearnPathAddedTitle').'</strong><br /><br />';
+					$learnpathadded .= '<a href="lp_controller.php?'.api_get_cidreq().'&amp;action=build&amp;lp_id='.Security::remove_XSS($_GET['lp_id']).'" target="_parent">'.Display::return_icon('learnpath_build.gif', get_lang('Build'),array('style'=> 'vertical-align: middle;')).' '.get_lang('Build')."</a>: ".get_lang('BuildComment').'<br />';
+					$learnpathadded .= '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=admin_view&amp;lp_id=' . $_SESSION['oLP']->lp_id . '" title="'.get_lang("BasicOverview").'">'.Display::return_icon('learnpath_organize.gif', get_lang('BasicOverview'),array('style'=> 'vertical-align: middle;')).' '.get_lang('BasicOverview').'</a>: '.get_lang('BasicOverviewComment').'<br />';
+					$learnpathadded .= '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&action=view&lp_id='.$_SESSION['oLP']->lp_id.'">'.Display::return_icon('learnpath_view.gif', get_lang('Display'),array('style'=> 'vertical-align: middle;')).' '.get_lang('Display').'</a>: '.get_lang('DisplayComment').'<br />';
+					$learnpathadded .= '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=add_item&amp;type=chapter&amp;lp_id=' . $_SESSION['oLP']->lp_id . '" title="'.get_lang("NewChapter").'">'.Display::return_icon('lp_dokeos_chapter_add.gif', get_lang('NewChapter'),array('style'=> 'vertical-align: middle;')).' '.get_lang('NewChapter').'</a>: '.get_lang('NewChapterComment').'<br />';
+					$learnpathadded .= '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=add_item&amp;type=step&amp;lp_id=' . $_SESSION['oLP']->lp_id . '" title="'.get_lang("NewStep").'">'.Display::return_icon('new_test.gif', get_lang('NewStep'),array('style'=> 'vertical-align: middle;')).' '.get_lang('NewStep').'</a>: '.get_lang('NewStepComment').'<br />';
 					$learnpathadded .= '<br /><br /><br /><br /></p>';
-					Display::display_normal_message($learnpathadded, false);
+					Display::display_normal_message($learnpathadded, false);
 			}
 		echo '</td>';
 	echo '</tr>';
-echo '</table>';
-
-/*
-==============================================================================
+echo '</table>';
+
+/*
+==============================================================================
 		FOOTER
-==============================================================================
+==============================================================================
 */
-Display::display_footer();
+Display::display_footer();
 ?>

+ 24 - 24
main/newscorm/lp_comm.common.php

@@ -1,25 +1,25 @@
-<?php //$id: $
-/**
- * This script contains the server part of the xajax interaction process. The client part is located
- * in lp_api.php or other api's.
- * This is a first attempt at using xajax and AJAX in general, so the code might be a bit unsettling.
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-require_once('back_compat.inc.php');
-require_once('learnpath.class.php');
-
-require('../inc/lib/xajax/xajax.inc.php');
-$xajax = new xajax(api_get_path(WEB_CODE_PATH).'newscorm/lp_comm.server.php');
-$xajax->registerFunction("save_item");
-$xajax->registerFunction("save_objectives");
-$xajax->registerFunction("switch_item_details");
-$xajax->registerFunction("backup_item_details");
-$xajax->registerFunction("start_timer");
+<?php //$id: $
+/**
+ * This script contains the server part of the xajax interaction process. The client part is located
+ * in lp_api.php or other api's.
+ * This is a first attempt at using xajax and AJAX in general, so the code might be a bit unsettling.
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+require_once('back_compat.inc.php');
+require_once('learnpath.class.php');
+
+require('../inc/lib/xajax/xajax.inc.php');
+$xajax = new xajax(api_get_path(WEB_CODE_PATH).'newscorm/lp_comm.server.php');
+$xajax->registerFunction("save_item");
+$xajax->registerFunction("save_objectives");
+$xajax->registerFunction("switch_item_details");
+$xajax->registerFunction("backup_item_details");
+$xajax->registerFunction("start_timer");
 ?>

+ 441 - 441
main/newscorm/lp_comm.server.php

@@ -1,455 +1,455 @@
-<?php //$id: $
-/**
- * This script contains the server part of the xajax interaction process. The client part is located
- * in lp_api.php or other api's.
- * This is a first attempt at using xajax and AJAX in general, so the code might be a bit unsettling.
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
+<?php //$id: $
+/**
+ * This script contains the server part of the xajax interaction process. The client part is located
+ * in lp_api.php or other api's.
+ * This is a first attempt at using xajax and AJAX in general, so the code might be a bit unsettling.
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
 // name of the language file that needs to be included
-$language_file[] = 'learnpath';
-require_once('back_compat.inc.php');
-/**
- * Backup an item's values into the javascript API as "old" values (so we still have them at hand)
- * @param	integer	Learnpath ID
- * @param	integer	User ID
- * @param	integer View ID
- * @param	integer	Item ID
- * @param	double	Current score
- * @param	double	Maximum score
- * @param	double	Minimum score
- * @param	string	Lesson status
- * @param	string	Session time
- * @param	string	Suspend data
- * @param	string	Lesson location
- */
-function backup_item_details($lp_id,$user_id,$view_id,$item_id,$score=-1,$max=-1,$min=-1,$status='',$time='',$suspend='',$location='')
-{
-	$objResponse = new xajaxResponse();
-	$objResponse->addScript(
-			"old_score=".$score.";" .
-			"old_max=".$max.";" .
-			"old_min=".$min.";" .
-			"old_lesson_status='".$status."';" .
-			"old_session_time='".$time."';" .
-			"lms_old_item_id='".$item_id."';" .
-			"old_suspend_data='".$suspend."';" .
-			"old_lesson_location='".$location."';");
-	//$objResponse->addAlert('data for item '.$item_id.', user '.$user_id.' backed up');
-	return $objResponse;
-}
-/**
- * Writes an item's new values into the database and returns the operation result
- * @param	integer	Learnpath ID
- * @param	integer	User ID
- * @param	integer View ID
- * @param	integer	Item ID
- * @param	double	Current score
- * @param	double	Maximum score
- * @param	double	Minimum score
- * @param	string	Lesson status
- * @param	string	Session time
- * @param	string	Suspend data
- * @param	string	Lesson location
- * @param	string	Core exit SCORM string
- */
-function save_item($lp_id,$user_id,$view_id,$item_id,$score=-1,$max=-1,$min=-1,$status='',$time=0,$suspend='',$location='',$interactions=array(),$core_exit='none')
-{
-	global $_configuration;
-	$debug=0;
-	if($debug>0){error_log('In xajax_save_item('.$lp_id.','.$user_id.','.$view_id.','.$item_id.','.$score.','.$max.','.$min.',"'.$status.'",'.$time.',"'.$suspend.'","'.$location.'","'.(count($interactions)>0?$interactions[0]:'').'","'.$core_exit.'")',0);}
-	$objResponse = new xajaxResponse();
-	require_once('learnpath.class.php');
-	require_once('scorm.class.php');
-	require_once('aicc.class.php');
-	require_once('learnpathItem.class.php');
-	require_once('scormItem.class.php');
-	require_once('aiccItem.class.php');
-	$mylp = '';
-	if(isset($_SESSION['lpobject']))
-	{
-		if($debug>1){error_log('////$_SESSION[lpobject] is set',0);}
-		$oLP =& unserialize($_SESSION['lpobject']);
-		if(!is_object($oLP)){
-			if($debug>2){error_log(print_r($oLP,true),0);}
-			if($debug>2){error_log('////Building new lp',0);}
-			unset($oLP);
-			$code = api_get_course_id();
-			$mylp = & new learnpath($code,$lp_id,$user_id);
-		}else{
-			if($debug>2){error_log('////Reusing session lp',0);}
-			$mylp = & $oLP;
-		}
-	}
-	//$objResponse->addAlert(api_get_path(REL_CODE_PATH).'newscorm/learnpathItem.class.php');
+$language_file[] = 'learnpath';
+require_once('back_compat.inc.php');
+/**
+ * Backup an item's values into the javascript API as "old" values (so we still have them at hand)
+ * @param	integer	Learnpath ID
+ * @param	integer	User ID
+ * @param	integer View ID
+ * @param	integer	Item ID
+ * @param	double	Current score
+ * @param	double	Maximum score
+ * @param	double	Minimum score
+ * @param	string	Lesson status
+ * @param	string	Session time
+ * @param	string	Suspend data
+ * @param	string	Lesson location
+ */
+function backup_item_details($lp_id,$user_id,$view_id,$item_id,$score=-1,$max=-1,$min=-1,$status='',$time='',$suspend='',$location='')
+{
+	$objResponse = new xajaxResponse();
+	$objResponse->addScript(
+			"old_score=".$score.";" .
+			"old_max=".$max.";" .
+			"old_min=".$min.";" .
+			"old_lesson_status='".$status."';" .
+			"old_session_time='".$time."';" .
+			"lms_old_item_id='".$item_id."';" .
+			"old_suspend_data='".$suspend."';" .
+			"old_lesson_location='".$location."';");
+	//$objResponse->addAlert('data for item '.$item_id.', user '.$user_id.' backed up');
+	return $objResponse;
+}
+/**
+ * Writes an item's new values into the database and returns the operation result
+ * @param	integer	Learnpath ID
+ * @param	integer	User ID
+ * @param	integer View ID
+ * @param	integer	Item ID
+ * @param	double	Current score
+ * @param	double	Maximum score
+ * @param	double	Minimum score
+ * @param	string	Lesson status
+ * @param	string	Session time
+ * @param	string	Suspend data
+ * @param	string	Lesson location
+ * @param	string	Core exit SCORM string
+ */
+function save_item($lp_id,$user_id,$view_id,$item_id,$score=-1,$max=-1,$min=-1,$status='',$time=0,$suspend='',$location='',$interactions=array(),$core_exit='none')
+{
+	global $_configuration;
+	$debug=0;
+	if($debug>0){error_log('In xajax_save_item('.$lp_id.','.$user_id.','.$view_id.','.$item_id.','.$score.','.$max.','.$min.',"'.$status.'",'.$time.',"'.$suspend.'","'.$location.'","'.(count($interactions)>0?$interactions[0]:'').'","'.$core_exit.'")',0);}
+	$objResponse = new xajaxResponse();
+	require_once('learnpath.class.php');
+	require_once('scorm.class.php');
+	require_once('aicc.class.php');
+	require_once('learnpathItem.class.php');
+	require_once('scormItem.class.php');
+	require_once('aiccItem.class.php');
+	$mylp = '';
+	if(isset($_SESSION['lpobject']))
+	{
+		if($debug>1){error_log('////$_SESSION[lpobject] is set',0);}
+		$oLP =& unserialize($_SESSION['lpobject']);
+		if(!is_object($oLP)){
+			if($debug>2){error_log(print_r($oLP,true),0);}
+			if($debug>2){error_log('////Building new lp',0);}
+			unset($oLP);
+			$code = api_get_course_id();
+			$mylp = & new learnpath($code,$lp_id,$user_id);
+		}else{
+			if($debug>2){error_log('////Reusing session lp',0);}
+			$mylp = & $oLP;
+		}
+	}
+	//$objResponse->addAlert(api_get_path(REL_CODE_PATH).'newscorm/learnpathItem.class.php');
 
 
-	$prereq_check = $mylp->prerequisites_match($item_id);
-	if($prereq_check === true) //launch the prerequisites check and set error if needed
-	{
+	$prereq_check = $mylp->prerequisites_match($item_id);
+	if($prereq_check === true) //launch the prerequisites check and set error if needed
+	{
 
-		$mylpi =& $mylp->items[$item_id];
-		//$mylpi->set_lp_view($view_id);
-		if($max!=-1)
-		{
-			$mylpi->max_score=$max;
-		}
-		if($min!=-1)
-		{
-			$mylpi->min_score=$min;
-		}
-		if($score!=-1)
-		{
-			$mylpi->set_score($score);
-		}
-		if($status!='')
-		{
-			if($debug>1){error_log('Calling set_status('.$status.') from xajax',0);}
-			$mylpi->set_status($status);
-			if($debug>1){error_log('Done calling set_status from xajax',0);}
-		}
-		if($time!='')
-		{
-			//if big integer, then it's a timestamp, otherwise it's normal scorm time
-			if($time == intval(strval($time)) && $time>1000000){
-				$real_time = time() - $time;
-				//$real_time += $mylpi->get_total_time();
-				$mylpi->set_time($real_time,'int');
-			}else{
-				$mylpi->set_time($time);
-			}
-		}
-		if($suspend!='')
-		{
-			$mylpi->current_data = $suspend;//escapetxt($suspend);
-		}
-		if($location!='')
-		{
-			$mylpi->set_lesson_location($location);
-		}
-		//deal with interactions provided in arrays in the following format
-		//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
-		if(is_array($interactions) && count($interactions)>0){
-			foreach($interactions as $index=>$interaction){
-				$mylpi->add_interaction($index,$interactions[$index]);
-			}
-		}
-		$mylpi->set_core_exit($core_exit);
-		$mylp->save_item($item_id,false);
-	}else{
-		return $objResponse;
-	}
+		$mylpi =& $mylp->items[$item_id];
+		//$mylpi->set_lp_view($view_id);
+		if($max!=-1)
+		{
+			$mylpi->max_score=$max;
+		}
+		if($min!=-1)
+		{
+			$mylpi->min_score=$min;
+		}
+		if($score!=-1)
+		{
+			$mylpi->set_score($score);
+		}
+		if($status!='')
+		{
+			if($debug>1){error_log('Calling set_status('.$status.') from xajax',0);}
+			$mylpi->set_status($status);
+			if($debug>1){error_log('Done calling set_status from xajax',0);}
+		}
+		if($time!='')
+		{
+			//if big integer, then it's a timestamp, otherwise it's normal scorm time
+			if($time == intval(strval($time)) && $time>1000000){
+				$real_time = time() - $time;
+				//$real_time += $mylpi->get_total_time();
+				$mylpi->set_time($real_time,'int');
+			}else{
+				$mylpi->set_time($time);
+			}
+		}
+		if($suspend!='')
+		{
+			$mylpi->current_data = $suspend;//escapetxt($suspend);
+		}
+		if($location!='')
+		{
+			$mylpi->set_lesson_location($location);
+		}
+		//deal with interactions provided in arrays in the following format
+		//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
+		if(is_array($interactions) && count($interactions)>0){
+			foreach($interactions as $index=>$interaction){
+				$mylpi->add_interaction($index,$interactions[$index]);
+			}
+		}
+		$mylpi->set_core_exit($core_exit);
+		$mylp->save_item($item_id,false);
+	}else{
+		return $objResponse;
+	}
 
-	$mystatus = $mylpi->get_status(false);
-	$mytotal = $mylp->get_total_items_count_without_chapters();
-	$mycomplete = $mylp->get_complete_items_count();
-	$myprogress_mode = $mylp->get_progress_bar_mode();
-	$myprogress_mode = ($myprogress_mode==''?'%':$myprogress_mode);
-	//$mylpi->write_to_db();
-	$_SESSION['lpobject'] = serialize($mylp);
-	if($mylpi->get_type()!='sco')
+	$mystatus = $mylpi->get_status(false);
+	$mytotal = $mylp->get_total_items_count_without_chapters();
+	$mycomplete = $mylp->get_complete_items_count();
+	$myprogress_mode = $mylp->get_progress_bar_mode();
+	$myprogress_mode = ($myprogress_mode==''?'%':$myprogress_mode);
+	//$mylpi->write_to_db();
+	$_SESSION['lpobject'] = serialize($mylp);
+	if($mylpi->get_type()!='sco')
 	{ //if this object's JS status has not been updated by the SCORM API, update now
-		$objResponse->addScript("lesson_status='".$mystatus."';");
-	}
-	$objResponse->addScript("update_toc('".$mystatus."','".$item_id."');");
-	$update_list = $mylp->get_update_queue();
-	foreach($update_list as $my_upd_id => $my_upd_status)
-	{
-		if($my_upd_id != $item_id){ //only update the status from other items (i.e. parents and brothers), do not update current as we just did it already
-			$objResponse->addScript("update_toc('".$my_upd_status."','".$my_upd_id."');");
+		$objResponse->addScript("lesson_status='".$mystatus."';");
+	}
+	$objResponse->addScript("update_toc('".$mystatus."','".$item_id."');");
+	$update_list = $mylp->get_update_queue();
+	foreach($update_list as $my_upd_id => $my_upd_status)
+	{
+		if($my_upd_id != $item_id){ //only update the status from other items (i.e. parents and brothers), do not update current as we just did it already
+			$objResponse->addScript("update_toc('".$my_upd_status."','".$my_upd_id."');");
 		}
-	}
-	$objResponse->addScript("update_progress_bar('$mycomplete','$mytotal','$myprogress_mode');");
-
-	if($debug>0){
-		$objResponse->addScript("logit_lms('Saved data for item ".$item_id.", user ".$user_id." (status=".$mystatus.")',2)");
-		if($debug>1){error_log('End of xajax_save_item()',0);}
-	}
+	}
+	$objResponse->addScript("update_progress_bar('$mycomplete','$mytotal','$myprogress_mode');");
 
-	if($_configuration['tracking_enabled'] && !isset($_SESSION['login_as']))
-	{ // if $_SESSION['login_as'] is set, then the user is an admin logged as the user
+	if($debug>0){
+		$objResponse->addScript("logit_lms('Saved data for item ".$item_id.", user ".$user_id." (status=".$mystatus.")',2)");
+		if($debug>1){error_log('End of xajax_save_item()',0);}
+	}
 
-		$tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+	if($_configuration['tracking_enabled'] && !isset($_SESSION['login_as']))
+	{ // if $_SESSION['login_as'] is set, then the user is an admin logged as the user
 
-		$sql_last_connection="SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='".api_get_user_id()."' ORDER BY login_date DESC LIMIT 0,1";
+		$tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
 
-		$q_last_connection=Database::query($sql_last_connection);
-		if(Database::num_rows($q_last_connection) > 0)
-		{
-			$row = Database::fetch_array($q_last_connection);
-			$i_id_last_connection=$row['login_id'];
-			$s_sql_update_logout_date="UPDATE $tbl_track_login SET logout_date=NOW() WHERE login_id='$i_id_last_connection'";
-			Database::query($s_sql_update_logout_date);
-		}
+		$sql_last_connection="SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='".api_get_user_id()."' ORDER BY login_date DESC LIMIT 0,1";
 
-	}
+		$q_last_connection=Database::query($sql_last_connection);
+		if(Database::num_rows($q_last_connection) > 0)
+		{
+			$row = Database::fetch_array($q_last_connection);
+			$i_id_last_connection=$row['login_id'];
+			$s_sql_update_logout_date="UPDATE $tbl_track_login SET logout_date=NOW() WHERE login_id='$i_id_last_connection'";
+			Database::query($s_sql_update_logout_date);
+		}
 
-	return $objResponse;
-}
-/**
- * Writes an item's new values into the database and returns the operation result
- * @param	integer	Learnpath ID
- * @param	integer	User ID
- * @param	integer View ID
- * @param	integer	Item ID
- * @param	array	Objectives array
- */
-function save_objectives($lp_id,$user_id,$view_id,$item_id,$objectives=array())
-{
-	global $_configuration;
-	$debug=0;
-	if($debug>0){error_log('In xajax_save_objectives('.$lp_id.','.$user_id.','.$view_id.','.$item_id.',"'.(count($objectives)>0?count($objectives):'').'")',0);}
-	$objResponse = new xajaxResponse();
-	require_once('learnpath.class.php');
-	require_once('scorm.class.php');
-	require_once('aicc.class.php');
-	require_once('learnpathItem.class.php');
-	require_once('scormItem.class.php');
-	require_once('aiccItem.class.php');
-	$mylp = '';
-	if(isset($_SESSION['lpobject']))
-	{
-		if($debug>1){error_log('////$_SESSION[lpobject] is set',0);}
-		$oLP =& unserialize($_SESSION['lpobject']);
-		if(!is_object($oLP)){
-			if($debug>2){error_log(print_r($oLP,true),0);}
-			if($debug>2){error_log('////Building new lp',0);}
-			unset($oLP);
-			$code = api_get_course_id();
-			$mylp = & new learnpath($code,$lp_id,$user_id);
-		}else{
-			if($debug>2){error_log('////Reusing session lp',0);}
-			$mylp = & $oLP;
-		}
-	}
-	$mylpi =& $mylp->items[$item_id];
-	//error_log(__FILE__.' '.__LINE__.' '.print_r($objectives,true),0);
-	if(is_array($objectives) && count($objectives)>0){
-		foreach($objectives as $index=>$objective){
-			//error_log(__FILE__.' '.__LINE__.' '.$objectives[$index][0],0);
-			$mylpi->add_objective($index,$objectives[$index]);
-		}
-        $mylpi->write_objectives_to_db();
-	}
-	return $objResponse;
-}
-/**
- * Get one item's details
- * @param	integer	LP ID
- * @param	integer	user ID
- * @param	integer	View ID
- * @param	integer	Current item ID
- * @param	integer New item ID
- */
-function switch_item_details($lp_id,$user_id,$view_id,$current_item,$next_item)
-{
-	global $charset;
-
-	$debug=0;
-	if($debug>0){error_log('In xajax_switch_item_details('.$lp_id.','.$user_id.','.$view_id.','.$current_item.','.$next_item.')',0);}
-	$objResponse = new xajaxResponse();
-	/*$item_id may be one of:
-	 * -'next'
-	 * -'previous'
-	 * -'first'
-	 * -'last'
-	 * - a real item ID
-	 */
-	require_once('learnpath.class.php');
-	require_once('scorm.class.php');
-	require_once('aicc.class.php');
-	require_once('learnpathItem.class.php');
-	require_once('scormItem.class.php');
-	require_once('aiccItem.class.php');
-	$mylp = '';
-	if(isset($_SESSION['lpobject']))
-	{
-		if($debug>1){error_log('////$_SESSION[lpobject] is set',0);}
-		$oLP =& unserialize($_SESSION['lpobject']);
-		if(!is_object($oLP)){
-			if($debug>1){error_log(print_r($oLP,true),0);}
-			if($debug>2){error_log('////Building new lp',0);}
-			unset($oLP);
-			$code = api_get_course_id();
-			$mylp = & new learnpath($code,$lp_id,$user_id);
-		}else{
-			if($debug>1){error_log('////Reusing session lp',0);}
-			$mylp = & $oLP;
-		}
-	}
-	$new_item_id = 0;
-	switch($next_item){
-		case 'next':
-			$mylp->set_current_item($current_item);
-			$mylp->next();
-			$new_item_id = $mylp->get_current_item_id();
-			if($debug>1){error_log('In {next} - next item is '.$new_item_id.'(current: '.$current_item.')',0);}
-			break;
-		case 'previous':
-			$mylp->set_current_item($current_item);
-			$mylp->previous();
+	}
+
+	return $objResponse;
+}
+/**
+ * Writes an item's new values into the database and returns the operation result
+ * @param	integer	Learnpath ID
+ * @param	integer	User ID
+ * @param	integer View ID
+ * @param	integer	Item ID
+ * @param	array	Objectives array
+ */
+function save_objectives($lp_id,$user_id,$view_id,$item_id,$objectives=array())
+{
+	global $_configuration;
+	$debug=0;
+	if($debug>0){error_log('In xajax_save_objectives('.$lp_id.','.$user_id.','.$view_id.','.$item_id.',"'.(count($objectives)>0?count($objectives):'').'")',0);}
+	$objResponse = new xajaxResponse();
+	require_once('learnpath.class.php');
+	require_once('scorm.class.php');
+	require_once('aicc.class.php');
+	require_once('learnpathItem.class.php');
+	require_once('scormItem.class.php');
+	require_once('aiccItem.class.php');
+	$mylp = '';
+	if(isset($_SESSION['lpobject']))
+	{
+		if($debug>1){error_log('////$_SESSION[lpobject] is set',0);}
+		$oLP =& unserialize($_SESSION['lpobject']);
+		if(!is_object($oLP)){
+			if($debug>2){error_log(print_r($oLP,true),0);}
+			if($debug>2){error_log('////Building new lp',0);}
+			unset($oLP);
+			$code = api_get_course_id();
+			$mylp = & new learnpath($code,$lp_id,$user_id);
+		}else{
+			if($debug>2){error_log('////Reusing session lp',0);}
+			$mylp = & $oLP;
+		}
+	}
+	$mylpi =& $mylp->items[$item_id];
+	//error_log(__FILE__.' '.__LINE__.' '.print_r($objectives,true),0);
+	if(is_array($objectives) && count($objectives)>0){
+		foreach($objectives as $index=>$objective){
+			//error_log(__FILE__.' '.__LINE__.' '.$objectives[$index][0],0);
+			$mylpi->add_objective($index,$objectives[$index]);
+		}
+        $mylpi->write_objectives_to_db();
+	}
+	return $objResponse;
+}
+/**
+ * Get one item's details
+ * @param	integer	LP ID
+ * @param	integer	user ID
+ * @param	integer	View ID
+ * @param	integer	Current item ID
+ * @param	integer New item ID
+ */
+function switch_item_details($lp_id,$user_id,$view_id,$current_item,$next_item)
+{
+	global $charset;
+
+	$debug=0;
+	if($debug>0){error_log('In xajax_switch_item_details('.$lp_id.','.$user_id.','.$view_id.','.$current_item.','.$next_item.')',0);}
+	$objResponse = new xajaxResponse();
+	/*$item_id may be one of:
+	 * -'next'
+	 * -'previous'
+	 * -'first'
+	 * -'last'
+	 * - a real item ID
+	 */
+	require_once('learnpath.class.php');
+	require_once('scorm.class.php');
+	require_once('aicc.class.php');
+	require_once('learnpathItem.class.php');
+	require_once('scormItem.class.php');
+	require_once('aiccItem.class.php');
+	$mylp = '';
+	if(isset($_SESSION['lpobject']))
+	{
+		if($debug>1){error_log('////$_SESSION[lpobject] is set',0);}
+		$oLP =& unserialize($_SESSION['lpobject']);
+		if(!is_object($oLP)){
+			if($debug>1){error_log(print_r($oLP,true),0);}
+			if($debug>2){error_log('////Building new lp',0);}
+			unset($oLP);
+			$code = api_get_course_id();
+			$mylp = & new learnpath($code,$lp_id,$user_id);
+		}else{
+			if($debug>1){error_log('////Reusing session lp',0);}
+			$mylp = & $oLP;
+		}
+	}
+	$new_item_id = 0;
+	switch($next_item){
+		case 'next':
+			$mylp->set_current_item($current_item);
+			$mylp->next();
 			$new_item_id = $mylp->get_current_item_id();
-			if($debug>1){error_log('In {previous} - next item is '.$new_item_id.'(current: '.$current_item.')',0);}
-			break;
-		case 'first':
-			$mylp->set_current_item($current_item);
-			$mylp->first();
-			$new_item_id = $mylp->get_current_item_id();
-			if($debug>1){error_log('In {first} - next item is '.$new_item_id.'(current: '.$current_item.')',0);}
-			break;
-		case 'last':
-			break;
-		default:
-			//should be filtered to check it's not hacked
-			if($next_item == $current_item){
-				//if we're opening the same item again
-				$mylp->items[$current_item]->restart();
-			}
-			$new_item_id = $next_item;
-			$mylp->set_current_item($new_item_id);
-			if($debug>1){error_log('In {default} - next item is '.$new_item_id.'(current: '.$current_item.')',0);}
-			break;
-	}
-	$mylp->start_current_item(true);
-	if($mylp->force_commit){
-		$mylp->save_current();
-	}
-	//$objResponse->addAlert(api_get_path(REL_CODE_PATH).'newscorm/learnpathItem.class.php');
-	if(is_object($mylp->items[$new_item_id])){
-		$mylpi = & $mylp->items[$new_item_id];
-	}else{
-		if($debug>1){error_log('In switch_item_details - generating new item object',0);}
-		$mylpi =& new learnpathItem($new_item_id,$user_id);
-		$mylpi->set_lp_view($view_id);
-	}
-	/*
-	 * now get what's needed by the SCORM API:
-	 * -score
-	 * -max
-	 * -min
-	 * -lesson_status
-	 * -session_time
-	 * -suspend_data
-	 */
-	$myscore = $mylpi->get_score();
-	$mymax = $mylpi->get_max();
-	$mymin = $mylpi->get_min();
-	$mylesson_status = $mylpi->get_status();
-	$mylesson_location = $mylpi->get_lesson_location();
-	$mytotal_time = $mylpi->get_scorm_time('js');
-	$mymastery_score = $mylpi->get_mastery_score();
-	$mymax_time_allowed = $mylpi->get_max_time_allowed();
-	$mylaunch_data = $mylpi->get_launch_data();
-	/*
-	if($mylpi->get_type() == 'asset'){
-		//temporary measure to save completion of an asset. Later on, Dokeos should trigger something on unload, maybe... (even though that would mean the last item cannot be completed)
-		$mylesson_status = 'completed';
-		$mylpi->set_status('completed');
-		$mylpi->save();
-	}
-	*/
-	$mysession_time = $mylpi->get_total_time();
-	$mysuspend_data = $mylpi->get_suspend_data();
-	$mylesson_location = $mylpi->get_lesson_location();
-	$objResponse->addScript(
-			"score=".$myscore.";" .
-			"max=".$mymax.";" .
-			"min=".$mymin.";" .
-			"lesson_status='".$mylesson_status."';" .
-			"lesson_location='".$mylesson_location."';" .
-			"session_time='".$mysession_time."';" .
-			"suspend_data='".$mysuspend_data."';" .
-			"lesson_location='".$mylesson_location."';" .
-			"total_time = '".$mytotal_time."';" .
-			"mastery_score = '".$mymastery_score."';" .
-			"max_time_allowed = '".$mymax_time_allowed."';" .
-			"launch_data = '".$mylaunch_data."';" .
-			"interactions = new Array();" .
-			"item_objectives = new Array();" .
-			"G_lastError = 0;" .
-			"G_LastErrorMessage = 'No error';");
-	/*
-	 * and re-initialise the rest
-	 * -saved_lesson_status = 'not attempted'
-	 * -lms_lp_id
-	 * -lms_item_id
-	 * -lms_old_item_id
-	 * -lms_new_item_id
-	 * -lms_been_synchronized
-	 * -lms_initialized
-	 * -lms_total_lessons
-	 * -lms_complete_lessons
-	 * -lms_progress_bar_mode
-	 * -lms_view_id
-	 * -lms_user_id
-	 */
-	$mytotal = $mylp->get_total_items_count_without_chapters();
-	$mycomplete = $mylp->get_complete_items_count();
-	$myprogress_mode = $mylp->get_progress_bar_mode();
-	$myprogress_mode = ($myprogress_mode==''?'%':$myprogress_mode);
-	$mynext = $mylp->get_next_item_id();
-	$myprevious = $mylp->get_previous_item_id();
-	$myitemtype = $mylpi->get_type();
-	$mylesson_mode = $mylpi->get_lesson_mode();
-	$mycredit = $mylpi->get_credit();
-	$mylaunch_data = $mylpi->get_launch_data();
-	$myinteractions_count = $mylpi->get_interactions_count();
-	$myobjectives_count = $mylpi->get_objectives_count();
-	$mycore_exit = $mylpi->get_core_exit();
-	$objResponse->addScript(
-			"saved_lesson_status='not attempted';" .
-			"lms_lp_id=".$lp_id.";" .
-			"lms_item_id=".$new_item_id.";" .
-			"lms_old_item_id=0;" .
-			"lms_been_synchronized=0;" .
-			"lms_initialized=0;" .
-			"lms_total_lessons=".$mytotal.";" .
-			"lms_complete_lessons=".$mycomplete.";" .
-			"lms_progress_bar_mod='".$myprogress_mode."';" .
-			"lms_view_id=".$view_id.";" .
-			"lms_user_id=".$user_id.";" .
-			"next_item=".$new_item_id.";" . //this one is very important to replace possible literal strings
-			"lms_next_item=".$mynext.";" .
-			"lms_previous_item=".$myprevious.";" .
-			"lms_item_type = '".$myitemtype."';" .
-			"lms_item_credit = '".$mycredit."';" .
-			"lms_item_lesson_mode = '".$mylesson_mode."';" .
-			"lms_item_launch_data = '".$mylaunch_data."';" .
-			"lms_item_interactions_count = '".$myinteractions_count."';" .
-			"lms_item_objectives_count = '".$myinteractions_count."';" .
-			"lms_item_core_exit = '".$mycore_exit."';" .
-			"asset_timer = 0;"
-			);
-	$objResponse->addScript("update_toc('unhighlight','".$current_item."');");
-	$objResponse->addScript("update_toc('highlight','".$new_item_id."');");
-	$objResponse->addScript("update_toc('$mylesson_status','".$new_item_id."');");
-	$objResponse->addScript("update_progress_bar('$mycomplete','$mytotal','$myprogress_mode');");
-
-	$mylp->set_error_msg('');
-	$mylp->prerequisites_match(); //check the prerequisites are all complete
-	if($debug>1){error_log('Prereq_match() returned '.api_htmlentities($mylp->error, ENT_QUOTES, $charset),0);}
-	$objResponse->addScript("update_message_frame('".str_replace("'","\'",api_htmlentities($mylp->error, ENT_QUOTES, $charset))."');");
-	$_SESSION['scorm_item_id'] = $new_item_id;//Save the new item ID for the exercise tool to use
-	$_SESSION['lpobject'] = serialize($mylp);
-	return $objResponse;
-}
-/**
- * Start a timer and hand it back to the JS by assigning the current time (of start) to
- * var asset_timer
- */
-function start_timer()
-{
-	$objResponse = new xajaxResponse();
-	$time = time();
-	$objResponse->addScript("asset_timer='$time';asset_timer_total=0;");
-	return $objResponse;
-}
-
-require('lp_comm.common.php');
-$xajax->processRequests();
-?>
+			if($debug>1){error_log('In {next} - next item is '.$new_item_id.'(current: '.$current_item.')',0);}
+			break;
+		case 'previous':
+			$mylp->set_current_item($current_item);
+			$mylp->previous();
+			$new_item_id = $mylp->get_current_item_id();
+			if($debug>1){error_log('In {previous} - next item is '.$new_item_id.'(current: '.$current_item.')',0);}
+			break;
+		case 'first':
+			$mylp->set_current_item($current_item);
+			$mylp->first();
+			$new_item_id = $mylp->get_current_item_id();
+			if($debug>1){error_log('In {first} - next item is '.$new_item_id.'(current: '.$current_item.')',0);}
+			break;
+		case 'last':
+			break;
+		default:
+			//should be filtered to check it's not hacked
+			if($next_item == $current_item){
+				//if we're opening the same item again
+				$mylp->items[$current_item]->restart();
+			}
+			$new_item_id = $next_item;
+			$mylp->set_current_item($new_item_id);
+			if($debug>1){error_log('In {default} - next item is '.$new_item_id.'(current: '.$current_item.')',0);}
+			break;
+	}
+	$mylp->start_current_item(true);
+	if($mylp->force_commit){
+		$mylp->save_current();
+	}
+	//$objResponse->addAlert(api_get_path(REL_CODE_PATH).'newscorm/learnpathItem.class.php');
+	if(is_object($mylp->items[$new_item_id])){
+		$mylpi = & $mylp->items[$new_item_id];
+	}else{
+		if($debug>1){error_log('In switch_item_details - generating new item object',0);}
+		$mylpi =& new learnpathItem($new_item_id,$user_id);
+		$mylpi->set_lp_view($view_id);
+	}
+	/*
+	 * now get what's needed by the SCORM API:
+	 * -score
+	 * -max
+	 * -min
+	 * -lesson_status
+	 * -session_time
+	 * -suspend_data
+	 */
+	$myscore = $mylpi->get_score();
+	$mymax = $mylpi->get_max();
+	$mymin = $mylpi->get_min();
+	$mylesson_status = $mylpi->get_status();
+	$mylesson_location = $mylpi->get_lesson_location();
+	$mytotal_time = $mylpi->get_scorm_time('js');
+	$mymastery_score = $mylpi->get_mastery_score();
+	$mymax_time_allowed = $mylpi->get_max_time_allowed();
+	$mylaunch_data = $mylpi->get_launch_data();
+	/*
+	if($mylpi->get_type() == 'asset'){
+		//temporary measure to save completion of an asset. Later on, Dokeos should trigger something on unload, maybe... (even though that would mean the last item cannot be completed)
+		$mylesson_status = 'completed';
+		$mylpi->set_status('completed');
+		$mylpi->save();
+	}
+	*/
+	$mysession_time = $mylpi->get_total_time();
+	$mysuspend_data = $mylpi->get_suspend_data();
+	$mylesson_location = $mylpi->get_lesson_location();
+	$objResponse->addScript(
+			"score=".$myscore.";" .
+			"max=".$mymax.";" .
+			"min=".$mymin.";" .
+			"lesson_status='".$mylesson_status."';" .
+			"lesson_location='".$mylesson_location."';" .
+			"session_time='".$mysession_time."';" .
+			"suspend_data='".$mysuspend_data."';" .
+			"lesson_location='".$mylesson_location."';" .
+			"total_time = '".$mytotal_time."';" .
+			"mastery_score = '".$mymastery_score."';" .
+			"max_time_allowed = '".$mymax_time_allowed."';" .
+			"launch_data = '".$mylaunch_data."';" .
+			"interactions = new Array();" .
+			"item_objectives = new Array();" .
+			"G_lastError = 0;" .
+			"G_LastErrorMessage = 'No error';");
+	/*
+	 * and re-initialise the rest
+	 * -saved_lesson_status = 'not attempted'
+	 * -lms_lp_id
+	 * -lms_item_id
+	 * -lms_old_item_id
+	 * -lms_new_item_id
+	 * -lms_been_synchronized
+	 * -lms_initialized
+	 * -lms_total_lessons
+	 * -lms_complete_lessons
+	 * -lms_progress_bar_mode
+	 * -lms_view_id
+	 * -lms_user_id
+	 */
+	$mytotal = $mylp->get_total_items_count_without_chapters();
+	$mycomplete = $mylp->get_complete_items_count();
+	$myprogress_mode = $mylp->get_progress_bar_mode();
+	$myprogress_mode = ($myprogress_mode==''?'%':$myprogress_mode);
+	$mynext = $mylp->get_next_item_id();
+	$myprevious = $mylp->get_previous_item_id();
+	$myitemtype = $mylpi->get_type();
+	$mylesson_mode = $mylpi->get_lesson_mode();
+	$mycredit = $mylpi->get_credit();
+	$mylaunch_data = $mylpi->get_launch_data();
+	$myinteractions_count = $mylpi->get_interactions_count();
+	$myobjectives_count = $mylpi->get_objectives_count();
+	$mycore_exit = $mylpi->get_core_exit();
+	$objResponse->addScript(
+			"saved_lesson_status='not attempted';" .
+			"lms_lp_id=".$lp_id.";" .
+			"lms_item_id=".$new_item_id.";" .
+			"lms_old_item_id=0;" .
+			"lms_been_synchronized=0;" .
+			"lms_initialized=0;" .
+			"lms_total_lessons=".$mytotal.";" .
+			"lms_complete_lessons=".$mycomplete.";" .
+			"lms_progress_bar_mod='".$myprogress_mode."';" .
+			"lms_view_id=".$view_id.";" .
+			"lms_user_id=".$user_id.";" .
+			"next_item=".$new_item_id.";" . //this one is very important to replace possible literal strings
+			"lms_next_item=".$mynext.";" .
+			"lms_previous_item=".$myprevious.";" .
+			"lms_item_type = '".$myitemtype."';" .
+			"lms_item_credit = '".$mycredit."';" .
+			"lms_item_lesson_mode = '".$mylesson_mode."';" .
+			"lms_item_launch_data = '".$mylaunch_data."';" .
+			"lms_item_interactions_count = '".$myinteractions_count."';" .
+			"lms_item_objectives_count = '".$myinteractions_count."';" .
+			"lms_item_core_exit = '".$mycore_exit."';" .
+			"asset_timer = 0;"
+			);
+	$objResponse->addScript("update_toc('unhighlight','".$current_item."');");
+	$objResponse->addScript("update_toc('highlight','".$new_item_id."');");
+	$objResponse->addScript("update_toc('$mylesson_status','".$new_item_id."');");
+	$objResponse->addScript("update_progress_bar('$mycomplete','$mytotal','$myprogress_mode');");
+
+	$mylp->set_error_msg('');
+	$mylp->prerequisites_match(); //check the prerequisites are all complete
+	if($debug>1){error_log('Prereq_match() returned '.api_htmlentities($mylp->error, ENT_QUOTES, $charset),0);}
+	$objResponse->addScript("update_message_frame('".str_replace("'","\'",api_htmlentities($mylp->error, ENT_QUOTES, $charset))."');");
+	$_SESSION['scorm_item_id'] = $new_item_id;//Save the new item ID for the exercise tool to use
+	$_SESSION['lpobject'] = serialize($mylp);
+	return $objResponse;
+}
+/**
+ * Start a timer and hand it back to the JS by assigning the current time (of start) to
+ * var asset_timer
+ */
+function start_timer()
+{
+	$objResponse = new xajaxResponse();
+	$time = time();
+	$objResponse->addScript("asset_timer='$time';asset_timer_total=0;");
+	return $objResponse;
+}
+
+require('lp_comm.common.php');
+$xajax->processRequests();
+?>

+ 85 - 85
main/newscorm/lp_content.php

@@ -1,96 +1,96 @@
-<?php //$id: $
-/**
- * Script that displays an error message when no content could be loaded
+<?php //$id: $
+/**
+ * Script that displays an error message when no content could be loaded
  * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Nothing very interesting
- */
-$debug = 0;
-if($debug>0){error_log('New lp - In lp_content.php',0);}
-if(empty($lp_controller_touched)){
-	if($debug>0){error_log('New lp - In lp_content.php - Redirecting to lp_controller',0);}
-	header('location: lp_controller.php?action=content&lp_id='.Security::remove_XSS($_REQUEST['lp_id']).'&item_id='.Security::remove_XSS($_REQUEST['item_id']));
-}
-$_SESSION['oLP']->error = '';
-$lp_type = $_SESSION['oLP']->get_type();
-$lp_item_id = $_SESSION['oLP']->get_current_item_id();
-
-/**
- * Get a link to the corresponding document
- */
-$src = '';
-if($debug>0){error_log('New lp - In lp_content.php - Looking for file url',0);}
-
-$list = $_SESSION['oLP']->get_toc();
-
-$dokeos_chapter = false;
-
-foreach($list as $toc) {
-	if ($toc['id']==$lp_item_id && ($toc['type']=='dokeos_chapter' || $toc['type']=='dokeos_module' || $toc['type']=='dir')) {
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Nothing very interesting
+ */
+$debug = 0;
+if($debug>0){error_log('New lp - In lp_content.php',0);}
+if(empty($lp_controller_touched)){
+	if($debug>0){error_log('New lp - In lp_content.php - Redirecting to lp_controller',0);}
+	header('location: lp_controller.php?action=content&lp_id='.Security::remove_XSS($_REQUEST['lp_id']).'&item_id='.Security::remove_XSS($_REQUEST['item_id']));
+}
+$_SESSION['oLP']->error = '';
+$lp_type = $_SESSION['oLP']->get_type();
+$lp_item_id = $_SESSION['oLP']->get_current_item_id();
+
+/**
+ * Get a link to the corresponding document
+ */
+$src = '';
+if($debug>0){error_log('New lp - In lp_content.php - Looking for file url',0);}
+
+$list = $_SESSION['oLP']->get_toc();
+
+$dokeos_chapter = false;
+
+foreach($list as $toc) {
+	if ($toc['id']==$lp_item_id && ($toc['type']=='dokeos_chapter' || $toc['type']=='dokeos_module' || $toc['type']=='dir')) {
 		$dokeos_chapter = true;
 	}
-}
-
+}
+
 if ($dokeos_chapter) {
-	$src='blank.php';
-} else {
-	switch($lp_type){
-		case 1:
-			$_SESSION['oLP']->stop_previous_item();
-			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
-			if($prereq_check === true){
-				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
-				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
-			}else{
-				$src = 'blank.php?error=prerequisites';
+	$src='blank.php';
+} else {
+	switch($lp_type){
+		case 1:
+			$_SESSION['oLP']->stop_previous_item();
+			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
+			if($prereq_check === true){
+				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
+				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
+			}else{
+				$src = 'blank.php?error=prerequisites';
 			}
-			break;
+			break;
 		case 2:
-				$_SESSION['oLP']->stop_previous_item();
-				$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
-				if($prereq_check === true){
-					$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
-					$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
-				}else{
-					$src = 'blank.php?error=prerequisites';
+				$_SESSION['oLP']->stop_previous_item();
+				$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
+				if($prereq_check === true){
+					$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
+					$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
+				}else{
+					$src = 'blank.php?error=prerequisites';
 				}
-				break;
+				break;
 		case 3:
-			//save old if asset
-			$_SESSION['oLP']->stop_previous_item(); //save status manually if asset
-			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
-			if($prereq_check === true){
-				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
-				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
-			}else{
-				$src = 'blank.php';
-			}
-			break;
-		case 4:
+			//save old if asset
+			$_SESSION['oLP']->stop_previous_item(); //save status manually if asset
+			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
+			if($prereq_check === true){
+				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
+				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
+			}else{
+				$src = 'blank.php';
+			}
 			break;
-	}
-}
-if($debug>0){error_log('New lp - In lp_content.php - File url is '.$src,0);}
-$_SESSION['oLP']->set_previous_item($lp_item_id);
-
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+		case 4:
+			break;
+	}
+}
+if($debug>0){error_log('New lp - In lp_content.php - File url is '.$src,0);}
+$_SESSION['oLP']->set_previous_item($lp_item_id);
+
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-// Define the 'doc.inc.php' as language file
-$nameTools = $_SESSION['oLP']->get_name();
-$interbreadcrumb[]= array ("url"=>"./lp_list.php", "name"=> get_lang('Doc'));
-//update global setting to avoid displaying right menu
-$save_setting = api_get_setting("show_navigation_menu");
-global $_setting;
-$_setting['show_navigation_menu'] = false;
-if($debug>0){error_log('New LP - In lp_content.php - Loading '.$src,0);}
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+// Define the 'doc.inc.php' as language file
+$nameTools = $_SESSION['oLP']->get_name();
+$interbreadcrumb[]= array ("url"=>"./lp_list.php", "name"=> get_lang('Doc'));
+//update global setting to avoid displaying right menu
+$save_setting = api_get_setting("show_navigation_menu");
+global $_setting;
+$_setting['show_navigation_menu'] = false;
+if($debug>0){error_log('New LP - In lp_content.php - Loading '.$src,0);}
 header("Location: ".urldecode($src));

+ 724 - 724
main/newscorm/lp_controller.php

@@ -1,842 +1,842 @@
-<?php //$id: $
-/**
- * Controller script. Prepares the common background variables to give to the scripts corresponding to
- * the requested action
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Initialisations
- */
-$debug = 0;
-if($debug>0) error_log('New LP -+- Entered lp_controller.php -+-',0);
-// name of the language file that needs to be included
-if (isset($_GET['action']))
+<?php //$id: $
+/**
+ * Controller script. Prepares the common background variables to give to the scripts corresponding to
+ * the requested action
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Initialisations
+ */
+$debug = 0;
+if($debug>0) error_log('New LP -+- Entered lp_controller.php -+-',0);
+// name of the language file that needs to be included
+if (isset($_GET['action']))
 {
-	if($_GET['action'] == 'export')
-	{ //only needed on export
-		$language_file[] = 'hotspot';
-		$language_file[] = 'exercice';
-	}
-}
-$language_file[] = 'course_home';
-$language_file[] = 'scormdocument';
-$language_file[] = 'scorm';
-$language_file[] = 'learnpath';
-$language_file[] = 'resourcelinker';
-$language_file[] = 'registration';
-
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-//include class definitions before session_start() to ensure availability when touching
-//session vars containing learning paths
-require_once('learnpath.class.php');
-if($debug>0) error_log('New LP - Included learnpath',0);
-require_once('learnpathItem.class.php');
-if($debug>0) error_log('New LP - Included learnpathItem',0);
-require_once('scorm.class.php');
-if($debug>0) error_log('New LP - Included scorm',0);
-require_once('scormItem.class.php');
-if($debug>0) error_log('New LP - Included scormItem',0);
-require_once('aicc.class.php');
-if($debug>0) error_log('New LP - Included aicc',0);
-require_once('aiccItem.class.php');
-if($debug>0) error_log('New LP - Included aiccItem',0);
-
-require_once('back_compat.inc.php');
-if($debug>0) error_log('New LP - Included back_compat',0);
-
-if ($is_allowed_in_course == false){
-	api_not_allowed(true);
-}
-
+	if($_GET['action'] == 'export')
+	{ //only needed on export
+		$language_file[] = 'hotspot';
+		$language_file[] = 'exercice';
+	}
+}
+$language_file[] = 'course_home';
+$language_file[] = 'scormdocument';
+$language_file[] = 'scorm';
+$language_file[] = 'learnpath';
+$language_file[] = 'resourcelinker';
+$language_file[] = 'registration';
+
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+//include class definitions before session_start() to ensure availability when touching
+//session vars containing learning paths
+require_once('learnpath.class.php');
+if($debug>0) error_log('New LP - Included learnpath',0);
+require_once('learnpathItem.class.php');
+if($debug>0) error_log('New LP - Included learnpathItem',0);
+require_once('scorm.class.php');
+if($debug>0) error_log('New LP - Included scorm',0);
+require_once('scormItem.class.php');
+if($debug>0) error_log('New LP - Included scormItem',0);
+require_once('aicc.class.php');
+if($debug>0) error_log('New LP - Included aicc',0);
+require_once('aiccItem.class.php');
+if($debug>0) error_log('New LP - Included aiccItem',0);
+
+require_once('back_compat.inc.php');
+if($debug>0) error_log('New LP - Included back_compat',0);
+
+if ($is_allowed_in_course == false){
+	api_not_allowed(true);
+}
+
 require_once api_get_path(LIBRARY_PATH).'fckeditor/fckeditor.php';
-$lpfound = false;
-
-$myrefresh = 0;
-$myrefresh_id = 0;
-if(!empty($_SESSION['refresh']) && $_SESSION['refresh']==1){
-	//check if we should do a refresh of the oLP object (for example after editing the LP)
-	//if refresh is set, we regenerate the oLP object from the database (kind of flush)
-	api_session_unregister('refresh');
-	$myrefresh = 1;
-	if($debug>0) error_log('New LP - Refresh asked',0);
-}
-if($debug>0) error_log('New LP - Passed refresh check',0);
-
-if(!empty($_REQUEST['dialog_box'])){
-	$dialog_box = stripslashes(urldecode($_REQUEST['dialog_box']));
-}
-
-$lp_controller_touched = 1;
-$lp_found = false;
-
-if(isset($_SESSION['lpobject']))
-{
-	if($debug>0) error_log('New LP - SESSION[lpobject] is defined',0);
-	$oLP = unserialize($_SESSION['lpobject']);
-	if(is_object($oLP)){
-		if($debug>0) error_log('New LP - oLP is object',0);
-		if($myrefresh == 1 OR (empty($oLP->cc)) OR $oLP->cc != api_get_course_id()){
-			if($debug>0) error_log('New LP - Course has changed, discard lp object',0);
-			if($myrefresh == 1){$myrefresh_id = $oLP->get_id();}
-			$oLP = null;
-			api_session_unregister('oLP');
-			api_session_unregister('lpobject');
-		}else{
-			$_SESSION['oLP'] = $oLP;
+$lpfound = false;
+
+$myrefresh = 0;
+$myrefresh_id = 0;
+if(!empty($_SESSION['refresh']) && $_SESSION['refresh']==1){
+	//check if we should do a refresh of the oLP object (for example after editing the LP)
+	//if refresh is set, we regenerate the oLP object from the database (kind of flush)
+	api_session_unregister('refresh');
+	$myrefresh = 1;
+	if($debug>0) error_log('New LP - Refresh asked',0);
+}
+if($debug>0) error_log('New LP - Passed refresh check',0);
+
+if(!empty($_REQUEST['dialog_box'])){
+	$dialog_box = stripslashes(urldecode($_REQUEST['dialog_box']));
+}
+
+$lp_controller_touched = 1;
+$lp_found = false;
+
+if(isset($_SESSION['lpobject']))
+{
+	if($debug>0) error_log('New LP - SESSION[lpobject] is defined',0);
+	$oLP = unserialize($_SESSION['lpobject']);
+	if(is_object($oLP)){
+		if($debug>0) error_log('New LP - oLP is object',0);
+		if($myrefresh == 1 OR (empty($oLP->cc)) OR $oLP->cc != api_get_course_id()){
+			if($debug>0) error_log('New LP - Course has changed, discard lp object',0);
+			if($myrefresh == 1){$myrefresh_id = $oLP->get_id();}
+			$oLP = null;
+			api_session_unregister('oLP');
+			api_session_unregister('lpobject');
+		}else{
+			$_SESSION['oLP'] = $oLP;
 			$lp_found = true;
-		}
-	}
-}
-
-if($debug>0) error_log('New LP - Passed data remains check',0);
-
-if($lp_found == false || (!empty($_REQUEST['lp_id']) && $_SESSION['oLP']->get_id() != $_REQUEST['lp_id'])) {
+		}
+	}
+}
+
+if($debug>0) error_log('New LP - Passed data remains check',0);
+
+if($lp_found == false || (!empty($_REQUEST['lp_id']) && $_SESSION['oLP']->get_id() != $_REQUEST['lp_id'])) {
 	if($debug>0) error_log('New LP - oLP is not object, has changed or refresh been asked, getting new',0);
-	//regenerate a new lp object? Not always as some pages don't need the object (like upload?)
-	if(!empty($_REQUEST['lp_id']) || !empty($myrefresh_id)){
-		if($debug>0) error_log('New LP - lp_id is defined',0);
-		//select the lp in the database and check which type it is (scorm/dokeos/aicc) to generate the
-		//right object
-		$lp_table = Database::get_course_table(TABLE_LP_MAIN);
-		if(!empty($_REQUEST['lp_id'])){
-			$lp_id = $_REQUEST['lp_id'];
-		} else {
-			$lp_id = $myrefresh_id;
-		}
-		if (is_numeric($lp_id)) {
-			$lp_id = Database::escape_string($lp_id);
+	//regenerate a new lp object? Not always as some pages don't need the object (like upload?)
+	if(!empty($_REQUEST['lp_id']) || !empty($myrefresh_id)){
+		if($debug>0) error_log('New LP - lp_id is defined',0);
+		//select the lp in the database and check which type it is (scorm/dokeos/aicc) to generate the
+		//right object
+		$lp_table = Database::get_course_table(TABLE_LP_MAIN);
+		if(!empty($_REQUEST['lp_id'])){
+			$lp_id = $_REQUEST['lp_id'];
+		} else {
+			$lp_id = $myrefresh_id;
+		}
+		if (is_numeric($lp_id)) {
+			$lp_id = Database::escape_string($lp_id);
 			$sel = "SELECT * FROM $lp_table WHERE id = $lp_id";
 
-			if($debug>0) error_log('New LP - querying '.$sel,0);
-			$res = Database::query($sel);
-			if(Database::num_rows($res)) {
-				$row = Database::fetch_array($res);
-				$type = $row['lp_type'];
+			if($debug>0) error_log('New LP - querying '.$sel,0);
+			$res = Database::query($sel);
+			if(Database::num_rows($res)) {
+				$row = Database::fetch_array($res);
+				$type = $row['lp_type'];
 				if($debug>0) error_log('New LP - found row - type '.$type. ' - Calling constructor with '.api_get_course_id().' - '.$lp_id.' - '.api_get_user_id(),0);
-				switch($type){
-					case 1:
+				switch($type){
+					case 1:
 				if($debug>0) error_log('New LP - found row - type dokeos - Calling constructor with '.api_get_course_id().' - '.$lp_id.' - '.api_get_user_id(),0);
-						$oLP = new learnpath(api_get_course_id(),$lp_id,api_get_user_id());
-						if($oLP !== false){ $lp_found = true; }else{eror_log($oLP->error,0);}
-						break;
-					case 2:
+						$oLP = new learnpath(api_get_course_id(),$lp_id,api_get_user_id());
+						if($oLP !== false){ $lp_found = true; }else{eror_log($oLP->error,0);}
+						break;
+					case 2:
 				if($debug>0) error_log('New LP - found row - type scorm - Calling constructor with '.api_get_course_id().' - '.$lp_id.' - '.api_get_user_id(),0);
-						$oLP = new scorm(api_get_course_id(),$lp_id,api_get_user_id());
-						if($oLP !== false){ $lp_found = true; }else{eror_log($oLP->error,0);}
-						break;
-					case 3:
+						$oLP = new scorm(api_get_course_id(),$lp_id,api_get_user_id());
+						if($oLP !== false){ $lp_found = true; }else{eror_log($oLP->error,0);}
+						break;
+					case 3:
 				if($debug>0) error_log('New LP - found row - type aicc - Calling constructor with '.api_get_course_id().' - '.$lp_id.' - '.api_get_user_id(),0);
-						$oLP = new aicc(api_get_course_id(),$lp_id,api_get_user_id());
-						if($oLP !== false){ $lp_found = true; }else{eror_log($oLP->error,0);}
+						$oLP = new aicc(api_get_course_id(),$lp_id,api_get_user_id());
+						if($oLP !== false){ $lp_found = true; }else{eror_log($oLP->error,0);}
 						break;
-					default:
+					default:
 				if($debug>0) error_log('New LP - found row - type other - Calling constructor with '.api_get_course_id().' - '.$lp_id.' - '.api_get_user_id(),0);
-						$oLP = new learnpath(api_get_course_id(),$lp_id,api_get_user_id());
-						if($oLP !== false){ $lp_found = true; }else{eror_log($oLP->error,0);}
-						break;
-				}
-			}
-		} else {
-			if($debug>0) error_log('New LP - Request[lp_id] is not numeric',0);
-		}
-
-
-	} else {
-		if($debug>0) error_log('New LP - Request[lp_id] and refresh_id were empty',0);
-	}
-	if($lp_found) {
-		$_SESSION['oLP'] = $oLP;
-	}
-}
-if($debug>0) error_log('New LP - Passed oLP creation check',0);
-
-
-/**
- * Actions switching
- */
-$_SESSION['oLP']->update_queue = array(); //reinitialises array used by javascript to update items in the TOC
-$_SESSION['oLP']->message = ''; //should use ->clear_message() method but doesn't work
-
-if(isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'true')
-{
-	if($_REQUEST['action'] != 'list' AND $_REQUEST['action'] != 'view')
-	{
-		if(!empty($_REQUEST['lp_id']))
-		{
-			$_REQUEST['action'] = 'view';
-		}
-		else
-		{
-			$_REQUEST['action'] = 'list';
-		}
-	}
-}
-
-$action = (!empty($_REQUEST['action'])?$_REQUEST['action']:'');
-switch($action)
-{
-	case 'add_item':
-
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-
-		if($debug > 0) error_log('New LP - add item action triggered', 0);
+						$oLP = new learnpath(api_get_course_id(),$lp_id,api_get_user_id());
+						if($oLP !== false){ $lp_found = true; }else{eror_log($oLP->error,0);}
+						break;
+				}
+			}
+		} else {
+			if($debug>0) error_log('New LP - Request[lp_id] is not numeric',0);
+		}
+
+
+	} else {
+		if($debug>0) error_log('New LP - Request[lp_id] and refresh_id were empty',0);
+	}
+	if($lp_found) {
+		$_SESSION['oLP'] = $oLP;
+	}
+}
+if($debug>0) error_log('New LP - Passed oLP creation check',0);
+
+
+/**
+ * Actions switching
+ */
+$_SESSION['oLP']->update_queue = array(); //reinitialises array used by javascript to update items in the TOC
+$_SESSION['oLP']->message = ''; //should use ->clear_message() method but doesn't work
+
+if(isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'true')
+{
+	if($_REQUEST['action'] != 'list' AND $_REQUEST['action'] != 'view')
+	{
+		if(!empty($_REQUEST['lp_id']))
+		{
+			$_REQUEST['action'] = 'view';
+		}
+		else
+		{
+			$_REQUEST['action'] = 'list';
+		}
+	}
+}
+
+$action = (!empty($_REQUEST['action'])?$_REQUEST['action']:'');
+switch($action)
+{
+	case 'add_item':
+
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+
+		if($debug > 0) error_log('New LP - add item action triggered', 0);
 
 		if(!$lp_found){
-			//check if the learnpath ID was defined, otherwise send back to list
+			//check if the learnpath ID was defined, otherwise send back to list
 			error_log('New LP - No learnpath given for add item', 0);
 			require('lp_list.php');
-		} else {
-			$_SESSION['refresh'] = 1;
+		} else {
+			$_SESSION['refresh'] = 1;
 
-			if(isset($_POST['submit_button']) && !empty($_POST['title'])) {
-				//if a title was sumbitted
+			if(isset($_POST['submit_button']) && !empty($_POST['title'])) {
+				//if a title was sumbitted
 
-				if(isset($_SESSION['post_time']) && $_SESSION['post_time'] == $_POST['post_time']) {
+				if(isset($_SESSION['post_time']) && $_SESSION['post_time'] == $_POST['post_time']) {
 					//check post_time to ensure ??? (counter-hacking measure?)
 					require('lp_add_item.php');
 				} else {
 
-					$_SESSION['post_time'] = $_POST['post_time'];
+					$_SESSION['post_time'] = $_POST['post_time'];
 
 					if($_POST['type'] == TOOL_DOCUMENT) {
-						if(isset($_POST['path']) && $_GET['edit'] != 'true') {
+						if(isset($_POST['path']) && $_GET['edit'] != 'true') {
 							$document_id = $_POST['path'];
 						} else {
-							$document_id = $_SESSION['oLP']->create_document($_course);
+							$document_id = $_SESSION['oLP']->create_document($_course);
 
 						}
-						$new_item_id = $_SESSION['oLP']->add_item($_POST['parent'], $_POST['previous'], $_POST['type'], $document_id, $_POST['title'], $_POST['description'], $_POST['prerequisites']);
+						$new_item_id = $_SESSION['oLP']->add_item($_POST['parent'], $_POST['previous'], $_POST['type'], $document_id, $_POST['title'], $_POST['description'], $_POST['prerequisites']);
 					} else {
-						//for all other item types than documents, load the item using the item type and path rather than its ID
-						$new_item_id = $_SESSION['oLP']->add_item($_POST['parent'], $_POST['previous'], $_POST['type'], $_POST['path'], $_POST['title'], $_POST['description'], $_POST['prerequisites'],$_POST['maxTimeAllowed']);
-					}
+						//for all other item types than documents, load the item using the item type and path rather than its ID
+						$new_item_id = $_SESSION['oLP']->add_item($_POST['parent'], $_POST['previous'], $_POST['type'], $_POST['path'], $_POST['title'], $_POST['description'], $_POST['prerequisites'],$_POST['maxTimeAllowed']);
+					}
 
 					//display
-					require('lp_add_item.php');
-				}
+					require('lp_add_item.php');
+				}
 			} else {
-				require('lp_add_item.php');
-			}
-		}
+				require('lp_add_item.php');
+			}
+		}
 
-		break;
+		break;
 
-	case 'add_lp':
+	case 'add_lp':
 
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
 
-		if($debug > 0) error_log('New LP - add_lp action triggered', 0);
+		if($debug > 0) error_log('New LP - add_lp action triggered', 0);
 
-		$_REQUEST['learnpath_name'] = trim($_REQUEST['learnpath_name']);
+		$_REQUEST['learnpath_name'] = trim($_REQUEST['learnpath_name']);
 
-		if(!empty($_REQUEST['learnpath_name']))
-		{
-			$_SESSION['refresh'] = 1;
+		if(!empty($_REQUEST['learnpath_name']))
+		{
+			$_SESSION['refresh'] = 1;
 
-			if(isset($_SESSION['post_time']) && $_SESSION['post_time'] == $_REQUEST['post_time'])
-			{
-				require('lp_add.php');
-			}
-			else
-			{
-				$_SESSION['post_time'] = $_REQUEST['post_time'];
+			if(isset($_SESSION['post_time']) && $_SESSION['post_time'] == $_REQUEST['post_time'])
+			{
+				require('lp_add.php');
+			}
+			else
+			{
+				$_SESSION['post_time'] = $_REQUEST['post_time'];
 
-				//Kevin Van Den Haute: changed $_REQUEST['learnpath_description'] by '' because it's not used
-				//old->$new_lp_id = learnpath::add_lp(api_get_course_id(), $_REQUEST['learnpath_name'], $_REQUEST['learnpath_description'], 'dokeos', 'manual', '');
-				$new_lp_id = learnpath::add_lp(api_get_course_id(), Security::remove_XSS($_REQUEST['learnpath_name']), '', 'dokeos', 'manual', '');
-				//learnpath::toggle_visibility($new_lp_id,'v');
-				//Kevin Van Den Haute: only go further if learnpath::add_lp has returned an id
-				if(is_numeric($new_lp_id))
-				{
-					//TODO maybe create a first module directly to avoid bugging the user with useless queries
-					$_SESSION['oLP'] = new learnpath(api_get_course_id(),$new_lp_id,api_get_user_id());
+				//Kevin Van Den Haute: changed $_REQUEST['learnpath_description'] by '' because it's not used
+				//old->$new_lp_id = learnpath::add_lp(api_get_course_id(), $_REQUEST['learnpath_name'], $_REQUEST['learnpath_description'], 'dokeos', 'manual', '');
+				$new_lp_id = learnpath::add_lp(api_get_course_id(), Security::remove_XSS($_REQUEST['learnpath_name']), '', 'dokeos', 'manual', '');
+				//learnpath::toggle_visibility($new_lp_id,'v');
+				//Kevin Van Den Haute: only go further if learnpath::add_lp has returned an id
+				if(is_numeric($new_lp_id))
+				{
+					//TODO maybe create a first module directly to avoid bugging the user with useless queries
+					$_SESSION['oLP'] = new learnpath(api_get_course_id(),$new_lp_id,api_get_user_id());
 
-					//$_SESSION['oLP']->add_item(0,-1,'dokeos_chapter',$_REQUEST['path'],'Default');
+					//$_SESSION['oLP']->add_item(0,-1,'dokeos_chapter',$_REQUEST['path'],'Default');
 
-					require('lp_build.php');
-				}
-			}
-		}
-		else
-			require('lp_add.php');
+					require('lp_build.php');
+				}
+			}
+		}
+		else
+			require('lp_add.php');
 
-		break;
+		break;
 
-	case 'admin_view':
+	case 'admin_view':
 
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
 
-		if($debug>0) error_log('New LP - admin_view action triggered',0);
+		if($debug>0) error_log('New LP - admin_view action triggered',0);
 
-		if(!$lp_found){ error_log('New LP - No learnpath given for admin_view', 0); require('lp_list.php'); }
-		else
-		{
-			$_SESSION['refresh'] = 1;
+		if(!$lp_found){ error_log('New LP - No learnpath given for admin_view', 0); require('lp_list.php'); }
+		else
+		{
+			$_SESSION['refresh'] = 1;
 
-			require('lp_admin_view.php');
-		}
+			require('lp_admin_view.php');
+		}
 
-		break;
+		break;
 
-	case 'build':
+	case 'build':
 
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
 
-		if($debug > 0) error_log('New LP - build action triggered', 0);
+		if($debug > 0) error_log('New LP - build action triggered', 0);
 
-		if(!$lp_found){ error_log('New LP - No learnpath given for build', 0); require('lp_list.php'); }
-		else
-		{
-			$_SESSION['refresh'] = 1;
+		if(!$lp_found){ error_log('New LP - No learnpath given for build', 0); require('lp_list.php'); }
+		else
+		{
+			$_SESSION['refresh'] = 1;
 
-			require('lp_build.php');
-		}
+			require('lp_build.php');
+		}
 
-		break;
+		break;
 
-	case 'delete_item':
+	case 'delete_item':
 
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
 
-		if($debug > 0) error_log('New LP - delete item action triggered', 0);
+		if($debug > 0) error_log('New LP - delete item action triggered', 0);
 
-		if(!$lp_found){ error_log('New LP - No learnpath given for delete item', 0); require('lp_list.php'); }
-		else
-		{
-			$_SESSION['refresh'] = 1;
+		if(!$lp_found){ error_log('New LP - No learnpath given for delete item', 0); require('lp_list.php'); }
+		else
+		{
+			$_SESSION['refresh'] = 1;
 
-			if(is_numeric($_GET['id']))
-			{
-				$_SESSION['oLP']->delete_item($_GET['id']);
+			if(is_numeric($_GET['id']))
+			{
+				$_SESSION['oLP']->delete_item($_GET['id']);
 
-				$is_success = true;
-			}
+				$is_success = true;
+			}
 
-			if(isset($_GET['view']) && $_GET['view'] == 'build')
-			{
-				require('lp_build.php');
-			}
-			else
-			{
-				require('lp_admin_view.php');
-			}
-		}
+			if(isset($_GET['view']) && $_GET['view'] == 'build')
+			{
+				require('lp_build.php');
+			}
+			else
+			{
+				require('lp_admin_view.php');
+			}
+		}
 
-		break;
+		break;
 
-	case 'edit_item':
+	case 'edit_item':
 
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
 
-		if($debug > 0) error_log('New LP - edit item action triggered', 0);
+		if($debug > 0) error_log('New LP - edit item action triggered', 0);
 
-		if(!$lp_found){ error_log('New LP - No learnpath given for edit item', 0); require('lp_list.php'); }
-		else
-		{
-			$_SESSION['refresh'] = 1;
+		if(!$lp_found){ error_log('New LP - No learnpath given for edit item', 0); require('lp_list.php'); }
+		else
+		{
+			$_SESSION['refresh'] = 1;
 
 			if(isset($_POST['submit_button']) && !empty($_POST['title'])) {
-				//$_SESSION['oLP']->edit_item($_GET['id'], $_POST['parent'], $_POST['previous'], $_POST['title'], $_POST['description'], $_POST['prerequisites']);
-				//todo mp3 edit
-				$audio = array();
-				if (isset($_FILES['mp3'])) $audio = $_FILES['mp3'];
-				$_SESSION['oLP']->edit_item($_GET['id'], $_POST['parent'], $_POST['previous'], $_POST['title'], $_POST['description'], $_POST['prerequisites'],$audio, $_POST['maxTimeAllowed']);
-
-				if(isset($_POST['content_lp'])) {
-					$_SESSION['oLP']->edit_document($_course);
+				//$_SESSION['oLP']->edit_item($_GET['id'], $_POST['parent'], $_POST['previous'], $_POST['title'], $_POST['description'], $_POST['prerequisites']);
+				//todo mp3 edit
+				$audio = array();
+				if (isset($_FILES['mp3'])) $audio = $_FILES['mp3'];
+				$_SESSION['oLP']->edit_item($_GET['id'], $_POST['parent'], $_POST['previous'], $_POST['title'], $_POST['description'], $_POST['prerequisites'],$audio, $_POST['maxTimeAllowed']);
+
+				if(isset($_POST['content_lp'])) {
+					$_SESSION['oLP']->edit_document($_course);
 				}
-				$is_success = true;
-			}
-
-			if(isset($_GET['view']) && $_GET['view'] == 'build')
-			{
-				require('lp_edit_item.php');
-			}
-			else
+				$is_success = true;
+			}
+
+			if(isset($_GET['view']) && $_GET['view'] == 'build')
 			{
-				require('lp_admin_view.php');
-			}
-		}
+				require('lp_edit_item.php');
+			}
+			else
+			{
+				require('lp_admin_view.php');
+			}
+		}
 
-		break;
+		break;
 
-	case 'edit_item_prereq':
+	case 'edit_item_prereq':
 
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
 
-		if($debug > 0) error_log('New LP - edit item prereq action triggered', 0);
+		if($debug > 0) error_log('New LP - edit item prereq action triggered', 0);
 
-		if(!$lp_found){ error_log('New LP - No learnpath given for edit item prereq', 0); require('lp_list.php'); }
-		else
-		{
-			if(isset($_POST['submit_button']))
-			{
-				$_SESSION['refresh'] = 1;
+		if(!$lp_found){ error_log('New LP - No learnpath given for edit item prereq', 0); require('lp_list.php'); }
+		else
+		{
+			if(isset($_POST['submit_button']))
+			{
+				$_SESSION['refresh'] = 1;
 
-				$_SESSION['oLP']->edit_item_prereq($_GET['id'], $_POST['prerequisites'], $_POST['min_' . $_POST['prerequisites']], $_POST['max_' . $_POST['prerequisites']]);
-			}
+				$_SESSION['oLP']->edit_item_prereq($_GET['id'], $_POST['prerequisites'], $_POST['min_' . $_POST['prerequisites']], $_POST['max_' . $_POST['prerequisites']]);
+			}
 
-			require('lp_edit_item_prereq.php');
-		}
+			require('lp_edit_item_prereq.php');
+		}
 
-		break;
+		break;
 
-	case 'move_item':
+	case 'move_item':
 
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
 
-		if($debug > 0) error_log('New LP - move item action triggered', 0);
+		if($debug > 0) error_log('New LP - move item action triggered', 0);
 
-		if(!$lp_found){ error_log('New LP - No learnpath given for move item', 0); require('lp_list.php'); }
-		else
-		{
-			$_SESSION['refresh'] = 1;
+		if(!$lp_found){ error_log('New LP - No learnpath given for move item', 0); require('lp_list.php'); }
+		else
+		{
+			$_SESSION['refresh'] = 1;
 
-			if(isset($_POST['submit_button']))
-			{
-				$_SESSION['oLP']->edit_item($_GET['id'], $_POST['parent'], $_POST['previous'], Security::remove_XSS($_POST['title']), $_POST['description']);
+			if(isset($_POST['submit_button']))
+			{
+				$_SESSION['oLP']->edit_item($_GET['id'], $_POST['parent'], $_POST['previous'], Security::remove_XSS($_POST['title']), $_POST['description']);
 
-				$is_success = true;
-			}
+				$is_success = true;
+			}
 
-			if(isset($_GET['view']) && $_GET['view'] == 'build')
-			{
-				require('lp_move_item.php');
-			}
-			else
-			{
-				$_SESSION['oLP']->move_item($_GET['id'], $_GET['direction']);
+			if(isset($_GET['view']) && $_GET['view'] == 'build')
+			{
+				require('lp_move_item.php');
+			}
+			else
+			{
+				$_SESSION['oLP']->move_item($_GET['id'], $_GET['direction']);
 
-				require('lp_admin_view.php');
-			}
-		}
+				require('lp_admin_view.php');
+			}
+		}
 
-		break;
+		break;
 
 	case 'view_item':
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
 		}
 		if($debug>0) error_log('New LP - view_item action triggered', 0);
 		if(!$lp_found){
 			error_log('New LP - No learnpath given for view item', 0); require('lp_list.php');
-		} else	{
+		} else	{
 			$_SESSION['refresh'] = 1;
-			require('lp_view_item.php');
-		}
-
-		break;
-
-	case 'upload':
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - upload action triggered',0);
-		$cwdir = getcwd();
-		require('lp_upload.php');
-		//reinit current working directory as many functions in upload change it
-		chdir($cwdir);
-		require('lp_list.php');
-		break;
-	case 'export':
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - export action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for export',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->scorm_export();
-			exit();
+			require('lp_view_item.php');
+		}
+
+		break;
+
+	case 'upload':
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - upload action triggered',0);
+		$cwdir = getcwd();
+		require('lp_upload.php');
+		//reinit current working directory as many functions in upload change it
+		chdir($cwdir);
+		require('lp_list.php');
+		break;
+	case 'export':
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - export action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for export',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->scorm_export();
+			exit();
 			//require('lp_list.php');
-		}
-		break;
-	case 'delete':
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - delete action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for delete',0); require('lp_list.php'); }
-		else{
-			$_SESSION['refresh'] = 1;
-			//remove lp from homepage if it is there
-			//$_SESSION['oLP']->toggle_visibility((int)$_GET['lp_id'],'i');
-			$_SESSION['oLP']->delete(null,(int)$_GET['lp_id'],'remove');
-			api_session_unregister('oLP');
-			require('lp_list.php');
-		}
-		break;
-	case 'toggle_visible': //change lp visibility (inside lp tool)
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - visibility action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for visibility',0); require('lp_list.php'); }
-		else{
-			learnpath::toggle_visibility($_REQUEST['lp_id'],$_REQUEST['new_status']);
-			require('lp_list.php');
-		}
-		break;
-	case 'toggle_publish': //change lp published status (visibility on homepage)
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - publish action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for publish',0); require('lp_list.php'); }
-		else{
-			learnpath::toggle_publish($_REQUEST['lp_id'],$_REQUEST['new_status']);
-			require('lp_list.php');
-		}
-		break;
-	case 'move_lp_up': //change lp published status (visibility on homepage)
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - publish action triggered',0);
-		if(!$lp_found)
+		}
+		break;
+	case 'delete':
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - delete action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for delete',0); require('lp_list.php'); }
+		else{
+			$_SESSION['refresh'] = 1;
+			//remove lp from homepage if it is there
+			//$_SESSION['oLP']->toggle_visibility((int)$_GET['lp_id'],'i');
+			$_SESSION['oLP']->delete(null,(int)$_GET['lp_id'],'remove');
+			api_session_unregister('oLP');
+			require('lp_list.php');
+		}
+		break;
+	case 'toggle_visible': //change lp visibility (inside lp tool)
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - visibility action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for visibility',0); require('lp_list.php'); }
+		else{
+			learnpath::toggle_visibility($_REQUEST['lp_id'],$_REQUEST['new_status']);
+			require('lp_list.php');
+		}
+		break;
+	case 'toggle_publish': //change lp published status (visibility on homepage)
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - publish action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for publish',0); require('lp_list.php'); }
+		else{
+			learnpath::toggle_publish($_REQUEST['lp_id'],$_REQUEST['new_status']);
+			require('lp_list.php');
+		}
+		break;
+	case 'move_lp_up': //change lp published status (visibility on homepage)
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - publish action triggered',0);
+		if(!$lp_found)
 		{
 			error_log('New LP - No learnpath given for publish',0);
 			require('lp_list.php');
-		}
-		else
-		{
-			learnpath::move_up($_REQUEST['lp_id']);
-			require('lp_list.php');
-		}
-		break;
-	case 'move_lp_down': //change lp published status (visibility on homepage)
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - publish action triggered',0);
+		}
+		else
+		{
+			learnpath::move_up($_REQUEST['lp_id']);
+			require('lp_list.php');
+		}
+		break;
+	case 'move_lp_down': //change lp published status (visibility on homepage)
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - publish action triggered',0);
 		if(!$lp_found){
 			error_log('New LP - No learnpath given for publish',0);
 			require('lp_list.php');
-		}
-		else
-		{
-			learnpath::move_down($_REQUEST['lp_id']);
-			require('lp_list.php');
-		}
-		break;
-	case 'edit':
-		if(!api_is_allowed_to_edit())
-		{
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - edit action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for edit',0); require('lp_list.php'); }
-		else{
-			$_SESSION['refresh'] = 1;
-			require('lp_edit.php');
-		}
-		break;
-	case 'update_lp':
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - update_lp action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for edit',0); require('lp_list.php'); }
-		else{
-			$_SESSION['refresh'] = 1;
-			$lp_name=Security::remove_XSS($_REQUEST['lp_name']);
-			$_SESSION['oLP']->set_name($lp_name);
+		}
+		else
+		{
+			learnpath::move_down($_REQUEST['lp_id']);
+			require('lp_list.php');
+		}
+		break;
+	case 'edit':
+		if(!api_is_allowed_to_edit())
+		{
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - edit action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for edit',0); require('lp_list.php'); }
+		else{
+			$_SESSION['refresh'] = 1;
+			require('lp_edit.php');
+		}
+		break;
+	case 'update_lp':
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - update_lp action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for edit',0); require('lp_list.php'); }
+		else{
+			$_SESSION['refresh'] = 1;
+			$lp_name=Security::remove_XSS($_REQUEST['lp_name']);
+			$_SESSION['oLP']->set_name($lp_name);
 			$author=$_REQUEST['lp_author'];
 			//fixing the author name (no body or html tags)
-		$auth_init = stripos($author,'<p>');
-		if ( $auth_init === false ) {
-		    $auth_init = stripos($author,'<body>');
-		    $auth_end = $auth_init + stripos(substr($author,$auth_init+6),'</body>') + 7;
-		    $len = $auth_end - $auth_init +6;
-            } else {
-		    $auth_end  =  strripos($author,'</p>');
-		    $len = $auth_end - $auth_init + 4;
-            }
-
-			$author_fixed=substr($author,$auth_init, $len);
+		$auth_init = stripos($author,'<p>');
+		if ( $auth_init === false ) {
+		    $auth_init = stripos($author,'<body>');
+		    $auth_end = $auth_init + stripos(substr($author,$auth_init+6),'</body>') + 7;
+		    $len = $auth_end - $auth_init +6;
+            } else {
+		    $auth_end  =  strripos($author,'</p>');
+		    $len = $auth_end - $auth_init + 4;
+            }
+
+			$author_fixed=substr($author,$auth_init, $len);
 			//$author_fixed = $author;
 
-			$_SESSION['oLP']->set_author($author_fixed);
-			$_SESSION['oLP']->set_encoding($_REQUEST['lp_encoding']);
-			$_SESSION['oLP']->set_maker($_REQUEST['lp_maker']);
+			$_SESSION['oLP']->set_author($author_fixed);
+			$_SESSION['oLP']->set_encoding($_REQUEST['lp_encoding']);
+			$_SESSION['oLP']->set_maker($_REQUEST['lp_maker']);
 			$_SESSION['oLP']->set_proximity($_REQUEST['lp_proximity']);
-			$_SESSION['oLP']->set_theme($_REQUEST['lp_theme']);
-			if ($_REQUEST['remove_picture'])
+			$_SESSION['oLP']->set_theme($_REQUEST['lp_theme']);
+			if ($_REQUEST['remove_picture'])
 			{
 				$_SESSION['oLP']->delete_lp_image();
 			}
 
-			if ($_FILES['lp_preview_image']['size']>0)
-				$_SESSION['oLP']->upload_image($_FILES['lp_preview_image']);
-
-			if (api_get_setting('search_enabled') === 'true')
-			{
-				require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
-				$specific_fields = get_specific_field_list();
-				foreach ($specific_fields as $specific_field) {
-					$_SESSION['oLP']->set_terms_by_prefix($_REQUEST[$specific_field['code']], $specific_field['code']);
-					$new_values = explode(',', trim($_REQUEST[$specific_field['code']]));
-					if ( !empty($new_values) ) {
-						array_walk($new_values, 'trim');
-						delete_all_specific_field_value(api_get_course_id(), $specific_field['id'], TOOL_LEARNPATH, $_SESSION['oLP']->lp_id);
-
-						foreach ($new_values as $value)
-						{
-							if ( !empty($value) ) {
-								add_specific_field_value($specific_field['id'], api_get_course_id(), TOOL_LEARNPATH, $_SESSION['oLP']->lp_id, $value);
-							}
-						}
-					}
-				}
-			}
-
-			require('lp_list.php');
-		}
-		break;
-	case 'add_sub_item': //add an item inside a chapter
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - add sub item action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for add sub item',0); require('lp_list.php'); }
-		else{
-			$_SESSION['refresh'] = 1;
-			if(!empty($_REQUEST['parent_item_id'])){
-				$_SESSION['from_learnpath']='yes';
-				$_SESSION['origintoolurl'] = 'lp_controller.php?action=admin_view&lp_id='.Security::remove_XSS($_REQUEST['lp_id']);
-				require('resourcelinker.php');
-				//$_SESSION['oLP']->add_sub_item($_REQUEST['parent_item_id'],$_REQUEST['previous'],$_REQUEST['type'],$_REQUEST['path'],$_REQUEST['title']);
-			}else{
-				require('lp_admin_view.php');
-			}
-		}
-		break;
-	case 'deleteitem':
-	case 'delete_item':
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - delete item action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for delete item',0); require('lp_list.php'); }
-		else{
-			$_SESSION['refresh'] = 1;
-			if(!empty($_REQUEST['id'])){
-				$_SESSION['oLP']->delete_item($_REQUEST['id']);
-			}
-			require('lp_admin_view.php');
-		}
-		break;
-	case 'edititemprereq':
-	case 'edit_item_prereq':
-		if(!api_is_allowed_to_edit()){
-			api_not_allowed(true);
-		}
-		if($debug>0) error_log('New LP - edit item prereq action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for edit item prereq',0); require('lp_list.php'); }
-		else{
-			if(!empty($_REQUEST['id']) && !empty($_REQUEST['submit_item'])){
-				$_SESSION['refresh'] = 1;
-				$_SESSION['oLP']->edit_item_prereq($_REQUEST['id'],$_REQUEST['prereq']);
-			}
-			require('lp_admin_view.php');
-		}
-		break;
-	case 'restart':
-		if($debug>0) error_log('New LP - restart action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for restart',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->restart();
-			require('lp_view.php');
-		}
-		break;
-	case 'last':
-		if($debug>0) error_log('New LP - last action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for last',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->last();
-			require('lp_view.php');
-		}
-		break;
-	case 'first':
-		if($debug>0) error_log('New LP - first action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for first',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->first();
-			require('lp_view.php');
-		}
-		break;
-	case 'next':
-		if($debug>0) error_log('New LP - next action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for next',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->next();
-			require('lp_view.php');
-		}
-		break;
-	case 'previous':
-		if($debug>0) error_log('New LP - previous action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for previous',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->previous();
-			require('lp_view.php');
-		}
-		break;
-	case 'content':
-		if($debug>0) error_log('New LP - content action triggered',0);
-		if($debug>0) error_log('New LP - Item id is '.$_GET['item_id'],0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for content',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->save_last();
+			if ($_FILES['lp_preview_image']['size']>0)
+				$_SESSION['oLP']->upload_image($_FILES['lp_preview_image']);
+
+			if (api_get_setting('search_enabled') === 'true')
+			{
+				require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
+				$specific_fields = get_specific_field_list();
+				foreach ($specific_fields as $specific_field) {
+					$_SESSION['oLP']->set_terms_by_prefix($_REQUEST[$specific_field['code']], $specific_field['code']);
+					$new_values = explode(',', trim($_REQUEST[$specific_field['code']]));
+					if ( !empty($new_values) ) {
+						array_walk($new_values, 'trim');
+						delete_all_specific_field_value(api_get_course_id(), $specific_field['id'], TOOL_LEARNPATH, $_SESSION['oLP']->lp_id);
+
+						foreach ($new_values as $value)
+						{
+							if ( !empty($value) ) {
+								add_specific_field_value($specific_field['id'], api_get_course_id(), TOOL_LEARNPATH, $_SESSION['oLP']->lp_id, $value);
+							}
+						}
+					}
+				}
+			}
+
+			require('lp_list.php');
+		}
+		break;
+	case 'add_sub_item': //add an item inside a chapter
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - add sub item action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for add sub item',0); require('lp_list.php'); }
+		else{
+			$_SESSION['refresh'] = 1;
+			if(!empty($_REQUEST['parent_item_id'])){
+				$_SESSION['from_learnpath']='yes';
+				$_SESSION['origintoolurl'] = 'lp_controller.php?action=admin_view&lp_id='.Security::remove_XSS($_REQUEST['lp_id']);
+				require('resourcelinker.php');
+				//$_SESSION['oLP']->add_sub_item($_REQUEST['parent_item_id'],$_REQUEST['previous'],$_REQUEST['type'],$_REQUEST['path'],$_REQUEST['title']);
+			}else{
+				require('lp_admin_view.php');
+			}
+		}
+		break;
+	case 'deleteitem':
+	case 'delete_item':
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - delete item action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for delete item',0); require('lp_list.php'); }
+		else{
+			$_SESSION['refresh'] = 1;
+			if(!empty($_REQUEST['id'])){
+				$_SESSION['oLP']->delete_item($_REQUEST['id']);
+			}
+			require('lp_admin_view.php');
+		}
+		break;
+	case 'edititemprereq':
+	case 'edit_item_prereq':
+		if(!api_is_allowed_to_edit()){
+			api_not_allowed(true);
+		}
+		if($debug>0) error_log('New LP - edit item prereq action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for edit item prereq',0); require('lp_list.php'); }
+		else{
+			if(!empty($_REQUEST['id']) && !empty($_REQUEST['submit_item'])){
+				$_SESSION['refresh'] = 1;
+				$_SESSION['oLP']->edit_item_prereq($_REQUEST['id'],$_REQUEST['prereq']);
+			}
+			require('lp_admin_view.php');
+		}
+		break;
+	case 'restart':
+		if($debug>0) error_log('New LP - restart action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for restart',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->restart();
+			require('lp_view.php');
+		}
+		break;
+	case 'last':
+		if($debug>0) error_log('New LP - last action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for last',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->last();
+			require('lp_view.php');
+		}
+		break;
+	case 'first':
+		if($debug>0) error_log('New LP - first action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for first',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->first();
+			require('lp_view.php');
+		}
+		break;
+	case 'next':
+		if($debug>0) error_log('New LP - next action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for next',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->next();
+			require('lp_view.php');
+		}
+		break;
+	case 'previous':
+		if($debug>0) error_log('New LP - previous action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for previous',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->previous();
+			require('lp_view.php');
+		}
+		break;
+	case 'content':
+		if($debug>0) error_log('New LP - content action triggered',0);
+		if($debug>0) error_log('New LP - Item id is '.$_GET['item_id'],0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for content',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->save_last();
 			$_SESSION['oLP']->set_current_item($_GET['item_id']);
-			$_SESSION['oLP']->start_current_item();
+			$_SESSION['oLP']->start_current_item();
 			require('lp_content.php');
-		}
-		break;
-	case 'view':
-		if($debug > 0)
-			error_log('New LP - view action triggered', 0);
-		if(!$lp_found)
-		{
-			error_log('New LP - No learnpath given for view', 0);
-			require('lp_list.php');
-		}
-		else
+		}
+		break;
+	case 'view':
+		if($debug > 0)
+			error_log('New LP - view action triggered', 0);
+		if(!$lp_found)
+		{
+			error_log('New LP - No learnpath given for view', 0);
+			require('lp_list.php');
+		}
+		else
 		{
-			if($debug > 0){error_log('New LP - Trying to set current item to ' . $_REQUEST['item_id'], 0);}
-			if ( !empty($_REQUEST['item_id']) )
-            {
-                $_SESSION['oLP']->set_current_item($_REQUEST['item_id']);
+			if($debug > 0){error_log('New LP - Trying to set current item to ' . $_REQUEST['item_id'], 0);}
+			if ( !empty($_REQUEST['item_id']) )
+            {
+                $_SESSION['oLP']->set_current_item($_REQUEST['item_id']);
             }
-			require('lp_view.php');
-		}
-		break;
-	case 'save':
-		if($debug>0) error_log('New LP - save action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for save',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->save_item();
-			require('lp_save.php');
-		}
-		break;
-	case 'stats':
-		if($debug>0) error_log('New LP - stats action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for stats',0); require('lp_list.php'); }
-		else{
-			$_SESSION['oLP']->save_current();
-			$_SESSION['oLP']->save_last();
-			//declare variables to be used in lp_stats.php
-			$lp_id = $_SESSION['oLP']->get_id();
-			$list = $_SESSION['oLP']->get_flat_ordered_items_list($lp_id);
-			$user_id = api_get_user_id();
-			$stats_charset = $_SESSION['oLP']->encoding;
-			require('lp_stats.php');
-		}
-		break;
-	case 'list':
-		if($debug>0) error_log('New LP - list action triggered',0);
-		if($lp_found){
-			$_SESSION['refresh'] = 1;
-			$_SESSION['oLP']->save_last();
-		}
-		require('lp_list.php');
-		break;
-	case 'mode':
-		//switch between fullscreen and embedded mode
-		if($debug>0) error_log('New LP - mode change triggered',0);
-		$mode = $_REQUEST['mode'];
-		if($mode == 'fullscreen'){
-			$_SESSION['oLP']->mode = 'fullscreen';
-		}else{
+			require('lp_view.php');
+		}
+		break;
+	case 'save':
+		if($debug>0) error_log('New LP - save action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for save',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->save_item();
+			require('lp_save.php');
+		}
+		break;
+	case 'stats':
+		if($debug>0) error_log('New LP - stats action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for stats',0); require('lp_list.php'); }
+		else{
+			$_SESSION['oLP']->save_current();
+			$_SESSION['oLP']->save_last();
+			//declare variables to be used in lp_stats.php
+			$lp_id = $_SESSION['oLP']->get_id();
+			$list = $_SESSION['oLP']->get_flat_ordered_items_list($lp_id);
+			$user_id = api_get_user_id();
+			$stats_charset = $_SESSION['oLP']->encoding;
+			require('lp_stats.php');
+		}
+		break;
+	case 'list':
+		if($debug>0) error_log('New LP - list action triggered',0);
+		if($lp_found){
+			$_SESSION['refresh'] = 1;
+			$_SESSION['oLP']->save_last();
+		}
+		require('lp_list.php');
+		break;
+	case 'mode':
+		//switch between fullscreen and embedded mode
+		if($debug>0) error_log('New LP - mode change triggered',0);
+		$mode = $_REQUEST['mode'];
+		if($mode == 'fullscreen'){
+			$_SESSION['oLP']->mode = 'fullscreen';
+		}else{
 			$_SESSION['oLP']->mode = 'embedded';
-		}
-		require('lp_view.php');
-		break;
-	case 'switch_view_mode':
-		if($debug>0) error_log('New LP - switch_view_mode action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for switch',0); require('lp_list.php'); }
-		$_SESSION['refresh'] = 1;
+		}
+		require('lp_view.php');
+		break;
+	case 'switch_view_mode':
+		if($debug>0) error_log('New LP - switch_view_mode action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for switch',0); require('lp_list.php'); }
+		$_SESSION['refresh'] = 1;
 		$_SESSION['oLP']->update_default_view_mode();
-		require('lp_list.php');
-		break;
-	case 'switch_force_commit':
-		if($debug>0) error_log('New LP - switch_force_commit action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for switch',0); require('lp_list.php'); }
-		$_SESSION['refresh'] = 1;
-		$_SESSION['oLP']->update_default_scorm_commit();
-		require('lp_list.php');
-		break;
-	case 'switch_reinit':
-		if($debug>0) error_log('New LP - switch_reinit action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for switch',0); require('lp_list.php'); }
-		$_SESSION['refresh'] = 1;
-		$_SESSION['oLP']->update_reinit();
-		require('lp_list.php');
-		break;
-	case 'switch_scorm_debug':
-		if($debug>0) error_log('New LP - switch_scorm_debug action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for switch',0); require('lp_list.php'); }
-		$_SESSION['refresh'] = 1;
-		$_SESSION['oLP']->update_scorm_debug();
-		require('lp_list.php');
-		break;
-	case 'intro_cmdAdd':
-		if($debug>0) error_log('New LP - intro_cmdAdd action triggered',0);
-		//add introduction section page
-		break;
-	case 'js_api_refresh':
-		if($debug>0) error_log('New LP - js_api_refresh action triggered',0);
-		if(!$lp_found){ error_log('New LP - No learnpath given for js_api_refresh',0); require('lp_message.php'); }
-		if(isset($_REQUEST['item_id'])){
-			$htmlHeadXtra[] = $_SESSION['oLP']->get_js_info($_REQUEST['item_id']);
-		}
-		require('lp_message.php');
-		break;
-	case 'return_to_course_homepage':
-        if(!$lp_found){ error_log('New LP - No learnpath given for stats',0); require('lp_list.php'); }
-        else{
-            $_SESSION['oLP']->save_current();
-            $_SESSION['oLP']->save_last();
-            //declare variables to be used in lp_stats.php
-            $lp_id = $_SESSION['oLP']->get_id();
-            $list = $_SESSION['oLP']->get_flat_ordered_items_list($lp_id);
-            $user_id = api_get_user_id();
-            $stats_charset = $_SESSION['oLP']->encoding;
-            //header('location: ../course_home/course_home.php?'.api_get_cidreq()); // This is not the preferable way to go to the homepage.
-            header('location: '.api_get_path(WEB_COURSE_PATH).api_get_course_path().'/index.php');
-        }
+		require('lp_list.php');
+		break;
+	case 'switch_force_commit':
+		if($debug>0) error_log('New LP - switch_force_commit action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for switch',0); require('lp_list.php'); }
+		$_SESSION['refresh'] = 1;
+		$_SESSION['oLP']->update_default_scorm_commit();
+		require('lp_list.php');
+		break;
+	case 'switch_reinit':
+		if($debug>0) error_log('New LP - switch_reinit action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for switch',0); require('lp_list.php'); }
+		$_SESSION['refresh'] = 1;
+		$_SESSION['oLP']->update_reinit();
+		require('lp_list.php');
+		break;
+	case 'switch_scorm_debug':
+		if($debug>0) error_log('New LP - switch_scorm_debug action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for switch',0); require('lp_list.php'); }
+		$_SESSION['refresh'] = 1;
+		$_SESSION['oLP']->update_scorm_debug();
+		require('lp_list.php');
+		break;
+	case 'intro_cmdAdd':
+		if($debug>0) error_log('New LP - intro_cmdAdd action triggered',0);
+		//add introduction section page
+		break;
+	case 'js_api_refresh':
+		if($debug>0) error_log('New LP - js_api_refresh action triggered',0);
+		if(!$lp_found){ error_log('New LP - No learnpath given for js_api_refresh',0); require('lp_message.php'); }
+		if(isset($_REQUEST['item_id'])){
+			$htmlHeadXtra[] = $_SESSION['oLP']->get_js_info($_REQUEST['item_id']);
+		}
+		require('lp_message.php');
+		break;
+	case 'return_to_course_homepage':
+        if(!$lp_found){ error_log('New LP - No learnpath given for stats',0); require('lp_list.php'); }
+        else{
+            $_SESSION['oLP']->save_current();
+            $_SESSION['oLP']->save_last();
+            //declare variables to be used in lp_stats.php
+            $lp_id = $_SESSION['oLP']->get_id();
+            $list = $_SESSION['oLP']->get_flat_ordered_items_list($lp_id);
+            $user_id = api_get_user_id();
+            $stats_charset = $_SESSION['oLP']->encoding;
+            //header('location: ../course_home/course_home.php?'.api_get_cidreq()); // This is not the preferable way to go to the homepage.
+            header('location: '.api_get_path(WEB_COURSE_PATH).api_get_course_path().'/index.php');
+        }
+        break;
+    case 'search':
+        /* Include the search script, it's smart enough to know when we are
+         * searching or not
+         */
+        require 'lp_list_search.php';
         break;
-    case 'search':
-        /* Include the search script, it's smart enough to know when we are
-         * searching or not
-         */
-        require 'lp_list_search.php';
-        break;
-	default:
-		if($debug>0) error_log('New LP - default action triggered',0);
-		//$_SESSION['refresh'] = 1;
-		require('lp_list.php');
-		break;
-}
-if(!empty($_SESSION['oLP'])){
-	$_SESSION['lpobject'] = serialize($_SESSION['oLP']);
-	if($debug>0) error_log('New LP - lpobject is serialized in session',0);
-}
-?>
+	default:
+		if($debug>0) error_log('New LP - default action triggered',0);
+		//$_SESSION['refresh'] = 1;
+		require('lp_list.php');
+		break;
+}
+if(!empty($_SESSION['oLP'])){
+	$_SESSION['lpobject'] = serialize($_SESSION['oLP']);
+	if($debug>0) error_log('New LP - lpobject is serialized in session',0);
+}
+?>

+ 159 - 159
main/newscorm/lp_edit.php

@@ -1,174 +1,174 @@
-<?php //$id: $
-/**
- * Script allowing simple edition of learnpath information (title, description, etc)
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
-*/
-
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
-
-global $charset;
-
-$show_description_field = false; //for now
-$nameTools = get_lang("Doc");
-event_access_tool(TOOL_LEARNPATH);
-if (! $is_allowed_in_course) api_not_allowed();
-
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+<?php //$id: $
+/**
+ * Script allowing simple edition of learnpath information (title, description, etc)
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+*/
+
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
+
+global $charset;
+
+$show_description_field = false; //for now
+$nameTools = get_lang("Doc");
+event_access_tool(TOOL_LEARNPATH);
+if (! $is_allowed_in_course) api_not_allowed();
+
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
-$interbreadcrumb[]= array ("url"=>api_get_self()."?action=admin_view&lp_id=$learnpath_id", "name" => $_SESSION['oLP']->get_name());
-
-Display::display_header(null,'Path');
-
-// actions link
-echo '<div class="actions">';
-$gradebook = Security::remove_XSS($_GET['gradebook']);
-echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=build&amp;lp_id=' . Security::remove_XSS($_GET['lp_id']) . '" title="'.get_lang("Build").'">'.Display::return_icon('learnpath_build.gif', get_lang('Build')).' '.get_lang('Build').'</a>';
-echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=admin_view&amp;lp_id=' . Security::remove_XSS($_GET['lp_id']) . '" title="'.get_lang("BasicOverview").'">'.Display::return_icon('learnpath_organize.gif', get_lang('BasicOverview')).' '.get_lang('BasicOverview').'</a>';
-echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=view&lp_id='.Security::remove_XSS($_GET['lp_id']).'">'.Display::return_icon('learnpath_view.gif', get_lang("Display")).' '.get_lang('Display').'</a> '.Display::return_icon('i.gif');
-echo '<a href="../newscorm/lp_controller.php?cidReq='.$_course['sysCode'].'">'.Display::return_icon('scorm.gif',get_lang('ReturnToLearningPaths')).' '.get_lang('ReturnToLearningPaths').'</a>';
-echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action='.Security::remove_XSS($_GET['action']).'&amp;lp_id='.Security::remove_XSS($_GET['lp_id']).'&amp;updateaudio=true">'.Display::return_icon('audio.gif', get_lang('UpdateAllAudioFragments')).' '.get_lang('UpdateAllAudioFragments').'</a>';
-echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=add_item&amp;type=chapter&amp;lp_id=' . Security::remove_XSS($_GET['lp_id']) . '" title="'.get_lang("NewChapter").'"><img alt="'.get_lang("NewChapter").'" src="../img/lp_dokeos_chapter_add.gif" title="'.get_lang("NewChapter").'" />'.get_lang("NewChapter").'</a>';
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
+$interbreadcrumb[]= array ("url"=>api_get_self()."?action=admin_view&lp_id=$learnpath_id", "name" => $_SESSION['oLP']->get_name());
+
+Display::display_header(null,'Path');
+
+// actions link
+echo '<div class="actions">';
+$gradebook = Security::remove_XSS($_GET['gradebook']);
+echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=build&amp;lp_id=' . Security::remove_XSS($_GET['lp_id']) . '" title="'.get_lang("Build").'">'.Display::return_icon('learnpath_build.gif', get_lang('Build')).' '.get_lang('Build').'</a>';
+echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=admin_view&amp;lp_id=' . Security::remove_XSS($_GET['lp_id']) . '" title="'.get_lang("BasicOverview").'">'.Display::return_icon('learnpath_organize.gif', get_lang('BasicOverview')).' '.get_lang('BasicOverview').'</a>';
+echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=view&lp_id='.Security::remove_XSS($_GET['lp_id']).'">'.Display::return_icon('learnpath_view.gif', get_lang("Display")).' '.get_lang('Display').'</a> '.Display::return_icon('i.gif');
+echo '<a href="../newscorm/lp_controller.php?cidReq='.$_course['sysCode'].'">'.Display::return_icon('scorm.gif',get_lang('ReturnToLearningPaths')).' '.get_lang('ReturnToLearningPaths').'</a>';
+echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action='.Security::remove_XSS($_GET['action']).'&amp;lp_id='.Security::remove_XSS($_GET['lp_id']).'&amp;updateaudio=true">'.Display::return_icon('audio.gif', get_lang('UpdateAllAudioFragments')).' '.get_lang('UpdateAllAudioFragments').'</a>';
+echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=add_item&amp;type=chapter&amp;lp_id=' . Security::remove_XSS($_GET['lp_id']) . '" title="'.get_lang("NewChapter").'"><img alt="'.get_lang("NewChapter").'" src="../img/lp_dokeos_chapter_add.gif" title="'.get_lang("NewChapter").'" />'.get_lang("NewChapter").'</a>';
 echo '<a href="lp_controller.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&amp;gradebook='.$gradebook.'&amp;action=add_item&amp;type=step&amp;lp_id=' . Security::remove_XSS($_GET['lp_id']) . '" title="'.get_lang("NewStep").'"><img alt="'.get_lang("NewStep").'" src="../img/new_test.gif" title="'.get_lang("NewStep").'" />'.get_lang("NewStep").'</a>';
-
-echo '</div>';
-
-$defaults=array();
-$form = new FormValidator('form1', 'post', 'lp_controller.php');
-
-// form title
-$form->addElement('header',null, get_lang('EditLPSettings'));
-
-//Title
-$form->addElement('text', 'lp_name', api_ucfirst(get_lang('_title')),array('size'=>43));
-$form->applyFilter('lp_name', 'html_filter');
-$form->addRule('lp_name', get_lang('ThisFieldIsRequired'), 'required');
-
-//Encoding
-$encoding_select = &$form->addElement('select', 'lp_encoding', get_lang('Charset'));
-$encodings = array('UTF-8','ISO-8859-1','ISO-8859-15','cp1251','cp1252','KOI8-R','BIG5','GB2312','Shift_JIS','EUC-JP');
-foreach($encodings as $encoding){
-	if (api_equal_encodings($encoding, $_SESSION['oLP']->encoding)) {
-  		$s_selected_encoding = $encoding;
-  	}
-  	$encoding_select->addOption($encoding,$encoding);
-}
-
-
-//Origin
-$origin_select = &$form->addElement('select', 'lp_maker', get_lang('Origin'));
-$lp_orig = $_SESSION['oLP']->get_maker();
-
-include('content_makers.inc.php');
-foreach($content_origins as $origin){
-	if($lp_orig == $origin){
-		$s_selected_origin = $origin;
-	}
-	$origin_select->addOption($origin,$origin);
-}
-
-
-//Content proximity
-$content_proximity_select = &$form->addElement('select', 'lp_proximity', get_lang('ContentProximity'));
-$lp_prox = $_SESSION['oLP']->get_proximity();
-if($lp_prox != 'local'){
-	$s_selected_proximity = 'remote';
-}else{
-	$s_selected_proximity = 'local';
-}
-$content_proximity_select->addOption(get_lang('Local'), 'local');
-$content_proximity_select->addOption(get_lang('Remote'), 'remote');
-
-
-if (api_get_setting('allow_course_theme') == 'true')
+
+echo '</div>';
+
+$defaults=array();
+$form = new FormValidator('form1', 'post', 'lp_controller.php');
+
+// form title
+$form->addElement('header',null, get_lang('EditLPSettings'));
+
+//Title
+$form->addElement('text', 'lp_name', api_ucfirst(get_lang('_title')),array('size'=>43));
+$form->applyFilter('lp_name', 'html_filter');
+$form->addRule('lp_name', get_lang('ThisFieldIsRequired'), 'required');
+
+//Encoding
+$encoding_select = &$form->addElement('select', 'lp_encoding', get_lang('Charset'));
+$encodings = array('UTF-8','ISO-8859-1','ISO-8859-15','cp1251','cp1252','KOI8-R','BIG5','GB2312','Shift_JIS','EUC-JP');
+foreach($encodings as $encoding){
+	if (api_equal_encodings($encoding, $_SESSION['oLP']->encoding)) {
+  		$s_selected_encoding = $encoding;
+  	}
+  	$encoding_select->addOption($encoding,$encoding);
+}
+
+
+//Origin
+$origin_select = &$form->addElement('select', 'lp_maker', get_lang('Origin'));
+$lp_orig = $_SESSION['oLP']->get_maker();
+
+include('content_makers.inc.php');
+foreach($content_origins as $origin){
+	if($lp_orig == $origin){
+		$s_selected_origin = $origin;
+	}
+	$origin_select->addOption($origin,$origin);
+}
+
+
+//Content proximity
+$content_proximity_select = &$form->addElement('select', 'lp_proximity', get_lang('ContentProximity'));
+$lp_prox = $_SESSION['oLP']->get_proximity();
+if($lp_prox != 'local'){
+	$s_selected_proximity = 'remote';
+}else{
+	$s_selected_proximity = 'local';
+}
+$content_proximity_select->addOption(get_lang('Local'), 'local');
+$content_proximity_select->addOption(get_lang('Remote'), 'remote');
+
+
+if (api_get_setting('allow_course_theme') == 'true')
 {
-	$mycourselptheme=api_get_course_setting('allow_learning_path_theme');
+	$mycourselptheme=api_get_course_setting('allow_learning_path_theme');
 	if (!empty($mycourselptheme) && $mycourselptheme!=-1 && $mycourselptheme== 1)
 	{
 		//LP theme picker
-		$theme_select = &$form->addElement('select_theme', 'lp_theme', get_lang('Theme'));
-		$form->applyFilter('lp_theme', 'trim');
+		$theme_select = &$form->addElement('select_theme', 'lp_theme', get_lang('Theme'));
+		$form->applyFilter('lp_theme', 'trim');
 
-		$s_theme = $_SESSION['oLP']->get_theme();
+		$s_theme = $_SESSION['oLP']->get_theme();
 		$theme_select ->setSelected($s_theme); //default
 	}
-}
-
-//Author
+}
+
+//Author
 $form->addElement('html_editor', 'lp_author', get_lang('Author'), array('size'=>80), array('ToolbarSet' => 'LearningPathAuthor', 'Width' => '100%', 'Height' => '150px') );
-$form->applyFilter('lp_author', 'html_filter');
-
+$form->applyFilter('lp_author', 'html_filter');
+
 // LP image
-$form->add_progress_bar();
-if( strlen($_SESSION['oLP']->get_preview_image() ) > 0)
-{
-	$show_preview_image='<img src='.api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/learning_path/images/'.$_SESSION['oLP']->get_preview_image().'>';
-	$div = '<div class="row">
-	<div class="label">'.get_lang('ImagePreview').'</div>
+$form->add_progress_bar();
+if( strlen($_SESSION['oLP']->get_preview_image() ) > 0)
+{
+	$show_preview_image='<img src='.api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/learning_path/images/'.$_SESSION['oLP']->get_preview_image().'>';
+	$div = '<div class="row">
+	<div class="label">'.get_lang('ImagePreview').'</div>
 	<div class="formw">
-	'.$show_preview_image.'
-	</div>
+	'.$show_preview_image.'
+	</div>
 	</div>';
 	$form->addElement('html', $div .'<br/>');
 	$form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
-}
-
-$form->addElement('file', 'lp_preview_image', ($_SESSION['oLP']->get_preview_image() != '' ? get_lang('UpdateImage') : get_lang('AddImage')));
-
-$form->addElement('static', null, null, get_lang('ImageWillResizeMsg'));
-
-/*
-$form->addRule('lp_preview_image', get_lang('OnlyImagesAllowed'), 'mimetype', array('image/gif', 'image/jpeg', 'image/png'));
-*/
-$form->addRule('lp_preview_image', get_lang('OnlyImagesAllowed'), 'filetype', array ('jpg', 'jpeg', 'png', 'gif'));
-
-// Search terms (only if search is activated)
-if (api_get_setting('search_enabled') === 'true')
-{
-	$specific_fields = get_specific_field_list();
-	foreach ($specific_fields as $specific_field) {
-		$form -> addElement ('text', $specific_field['code'], $specific_field['name']);
-		$filter = array('course_code'=> "'". api_get_course_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $_SESSION['oLP']->lp_id, 'tool_id' => '\''. TOOL_LEARNPATH .'\'');
-		$values = get_specific_field_values_list($filter, array('value'));
-		if ( !empty($values) ) {
-			$arr_str_values = array();
-			foreach ($values as $value) {
-				$arr_str_values[] = $value['value'];
-			}
-			$defaults[$specific_field['code']] = implode(', ', $arr_str_values);
-		}
-	}
-}
-
-//default values
-$content_proximity_select -> setSelected($s_selected_proximity);
-$origin_select -> setSelected($s_selected_origin);
-$encoding_select -> setSelected($s_selected_encoding);
-$defaults['lp_name'] = Security::remove_XSS($_SESSION['oLP']->get_name());
-$defaults['lp_author'] = Security::remove_XSS($_SESSION['oLP']->get_author());
-
-//Submit button
-$form->addElement('style_submit_button', 'Submit',get_lang('SaveLPSettings'),'class="save"');
-//'<img src="'.api_get_path(WEB_IMG_PATH).'accept.png'.'" alt=""/>'
-
-//Hidden fields
-$form->addElement('hidden', 'action', 'update_lp');
-$form->addElement('hidden', 'lp_id', $_SESSION['oLP']->get_id());
-
-$form->setDefaults($defaults);
-echo '<table><tr><td width="550px">';
-	$form -> display();
-echo '</td><td valign="top"><img src="../img/course_setting_layout.png" /></td></tr></table>';
-
-Display::display_footer();
-?>
+}
+
+$form->addElement('file', 'lp_preview_image', ($_SESSION['oLP']->get_preview_image() != '' ? get_lang('UpdateImage') : get_lang('AddImage')));
+
+$form->addElement('static', null, null, get_lang('ImageWillResizeMsg'));
+
+/*
+$form->addRule('lp_preview_image', get_lang('OnlyImagesAllowed'), 'mimetype', array('image/gif', 'image/jpeg', 'image/png'));
+*/
+$form->addRule('lp_preview_image', get_lang('OnlyImagesAllowed'), 'filetype', array ('jpg', 'jpeg', 'png', 'gif'));
+
+// Search terms (only if search is activated)
+if (api_get_setting('search_enabled') === 'true')
+{
+	$specific_fields = get_specific_field_list();
+	foreach ($specific_fields as $specific_field) {
+		$form -> addElement ('text', $specific_field['code'], $specific_field['name']);
+		$filter = array('course_code'=> "'". api_get_course_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $_SESSION['oLP']->lp_id, 'tool_id' => '\''. TOOL_LEARNPATH .'\'');
+		$values = get_specific_field_values_list($filter, array('value'));
+		if ( !empty($values) ) {
+			$arr_str_values = array();
+			foreach ($values as $value) {
+				$arr_str_values[] = $value['value'];
+			}
+			$defaults[$specific_field['code']] = implode(', ', $arr_str_values);
+		}
+	}
+}
+
+//default values
+$content_proximity_select -> setSelected($s_selected_proximity);
+$origin_select -> setSelected($s_selected_origin);
+$encoding_select -> setSelected($s_selected_encoding);
+$defaults['lp_name'] = Security::remove_XSS($_SESSION['oLP']->get_name());
+$defaults['lp_author'] = Security::remove_XSS($_SESSION['oLP']->get_author());
+
+//Submit button
+$form->addElement('style_submit_button', 'Submit',get_lang('SaveLPSettings'),'class="save"');
+//'<img src="'.api_get_path(WEB_IMG_PATH).'accept.png'.'" alt=""/>'
+
+//Hidden fields
+$form->addElement('hidden', 'action', 'update_lp');
+$form->addElement('hidden', 'lp_id', $_SESSION['oLP']->get_id());
+
+$form->setDefaults($defaults);
+echo '<table><tr><td width="550px">';
+	$form -> display();
+echo '</td><td valign="top"><img src="../img/course_setting_layout.png" /></td></tr></table>';
+
+Display::display_footer();
+?>

+ 203 - 203
main/newscorm/lp_edit_item.php

@@ -1,261 +1,261 @@
-<?php
-/*
+<?php
+/*
 ==============================================================================
-	Dokeos - elearning and course management software
+	Dokeos - elearning and course management software
 
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Patrick Cool
-	Copyright (c) Denes Nagy
-	Copyright (c) Yannick Warnier
+	Copyright (c) 2004-2008 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Patrick Cool
+	Copyright (c) Denes Nagy
+	Copyright (c) Yannick Warnier
 
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
+	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.
+	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.
+	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
 ==============================================================================
-*/
-/**
+*/
+/**
 ==============================================================================
-* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
-*
-* @author Patrick Cool
-* @author Denes Nagy
-* @author Roan Embrechts, refactoring and code cleaning
-* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
-* @author Julio Montoya  - Improving the list of templates
-* @package dokeos.learnpath
+* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
+*
+* @author Patrick Cool
+* @author Denes Nagy
+* @author Roan Embrechts, refactoring and code cleaning
+* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
+* @author Julio Montoya  - Improving the list of templates
+* @package dokeos.learnpath
 ==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
 */
-$this_section=SECTION_COURSES;
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
 */
-//the main_api.lib.php, database.lib.php and display.lib.php
-//libraries are included by default
-
-include('learnpath_functions.inc.php');
-//include('../resourcelinker/resourcelinker.inc.php');
-include('resourcelinker.inc.php');
-//rewrite the language file, sadly overwritten by resourcelinker.inc.php
+$this_section=SECTION_COURSES;
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+//the main_api.lib.php, database.lib.php and display.lib.php
+//libraries are included by default
+
+include('learnpath_functions.inc.php');
+//include('../resourcelinker/resourcelinker.inc.php');
+include('resourcelinker.inc.php');
+//rewrite the language file, sadly overwritten by resourcelinker.inc.php
 // name of the language file that needs to be included
-$language_file = "learnpath";
-
-/*
------------------------------------------------------------
-	Header and action code
------------------------------------------------------------
+$language_file = "learnpath";
+
+/*
+-----------------------------------------------------------
+	Header and action code
+-----------------------------------------------------------
 */
-$htmlHeadXtra[] = '
-<script type="text/javascript">
+$htmlHeadXtra[] = '
+<script type="text/javascript">
 
-function FCKeditor_OnComplete( editorInstance )
+function FCKeditor_OnComplete( editorInstance )
 {
 	document.getElementById(\'frmModel\').innerHTML = "<iframe height=890px; width=230px; frameborder=0 src=\''.api_get_path(WEB_LIBRARY_PATH).'fckeditor/editor/fckdialogframe.html \'>";
 }
 
-function InnerDialogLoaded()
+function InnerDialogLoaded()
 {
-	if (document.all)
+	if (document.all)
 	{
-		// if is iexplorer
+		// if is iexplorer
 		var B=new window.frames.content_lp___Frame.FCKToolbarButton(\'Templates\',window.content_lp___Frame.FCKLang.Templates);
-	}
-	else
+	}
+	else
 	{
 		var B=new window.frames[0].FCKToolbarButton(\'Templates\',window.frames[0].FCKLang.Templates);
 	}
-	return B.ClickFrame();
+	return B.ClickFrame();
 };
-
-</script>';
-$htmlHeadXtra[] = $_SESSION['oLP']->create_js();
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
+
+</script>';
+$htmlHeadXtra[] = $_SESSION['oLP']->create_js();
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
 */
-$is_allowed_to_edit = api_is_allowed_to_edit();
-
-$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
-
-$isStudentView  = (int) $_REQUEST['isStudentView'];
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-$submit			= $_POST['submit_button'];
-/*
-$chapter_id     = $_GET['chapter_id'];
-$title          = $_POST['title'];
-$description   = $_POST['description'];
-$Submititem     = $_POST['Submititem'];
-$action         = $_REQUEST['action'];
-$id             = (int) $_REQUEST['id'];
-$type           = $_REQUEST['type'];
-$direction      = $_REQUEST['direction'];
-$moduleid       = $_REQUEST['moduleid'];
-$prereq         = $_REQUEST['prereq'];
-$type           = $_REQUEST['type'];
-*/
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-// using the resource linker as a tool for adding resources to the learning path
-if ($action=="add" and $type=="learnpathitem")
-{
-	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
-}
-if ( (! $is_allowed_to_edit) or ($isStudentView) )
-{
-	error_log('New LP - User not authorized in lp_add_item.php');
-	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
-}
-//from here on, we are admin because of the previous condition, so don't check anymore
-
+$is_allowed_to_edit = api_is_allowed_to_edit();
+
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
+
+$isStudentView  = (int) $_REQUEST['isStudentView'];
+$learnpath_id   = (int) $_REQUEST['lp_id'];
+$submit			= $_POST['submit_button'];
+/*
+$chapter_id     = $_GET['chapter_id'];
+$title          = $_POST['title'];
+$description   = $_POST['description'];
+$Submititem     = $_POST['Submititem'];
+$action         = $_REQUEST['action'];
+$id             = (int) $_REQUEST['id'];
+$type           = $_REQUEST['type'];
+$direction      = $_REQUEST['direction'];
+$moduleid       = $_REQUEST['moduleid'];
+$prereq         = $_REQUEST['prereq'];
+$type           = $_REQUEST['type'];
+*/
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+// using the resource linker as a tool for adding resources to the learning path
+if ($action=="add" and $type=="learnpathitem")
+{
+	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
+}
+if ( (! $is_allowed_to_edit) or ($isStudentView) )
+{
+	error_log('New LP - User not authorized in lp_add_item.php');
+	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
+}
+//from here on, we are admin because of the previous condition, so don't check anymore
+
 $sql_query = "SELECT * FROM $tbl_lp WHERE id = $learnpath_id";
-$result=Database::query($sql_query);
+$result=Database::query($sql_query);
 $therow=Database::fetch_array($result);
-
-//$admin_output = '';
-/*
------------------------------------------------------------
-	Course admin section
-	- all the functions not available for students - always available in this case (page only shown to admin)
------------------------------------------------------------
+
+//$admin_output = '';
+/*
+-----------------------------------------------------------
+	Course admin section
+	- all the functions not available for students - always available in this case (page only shown to admin)
+-----------------------------------------------------------
 */
-/*==================================================
-			SHOWING THE ADMIN TOOLS
- ==================================================*/
-
-
-
-/*==================================================
-	prerequisites setting end
+/*==================================================
+			SHOWING THE ADMIN TOOLS
+ ==================================================*/
+
+
+
+/*==================================================
+	prerequisites setting end
  ==================================================*/
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
-$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" =>stripslashes("{$therow['name']}"));
-//Theme calls
-$show_learn_path=true;
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-
-Display::display_header(null,'Path');
-//api_display_tool_title($therow['name']);
-
-$suredel = trim(get_lang('AreYouSureToDelete'));
-//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
-?>
-<script type='text/javascript'>
-/* <![CDATA[ */
-function stripslashes(str) {
-	str=str.replace(/\\'/g,'\'');
-	str=str.replace(/\\"/g,'"');
-	str=str.replace(/\\\\/g,'\\');
-	str=str.replace(/\\0/g,'\0');
-	return str;
-}
-function confirmation(name)
-{
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
+$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" =>stripslashes("{$therow['name']}"));
+//Theme calls
+$show_learn_path=true;
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+
+Display::display_header(null,'Path');
+//api_display_tool_title($therow['name']);
+
+$suredel = trim(get_lang('AreYouSureToDelete'));
+//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
+?>
+<script type='text/javascript'>
+/* <![CDATA[ */
+function stripslashes(str) {
+	str=str.replace(/\\'/g,'\'');
+	str=str.replace(/\\"/g,'"');
+	str=str.replace(/\\\\/g,'\\');
+	str=str.replace(/\\0/g,'\0');
+	return str;
+}
+function confirmation(name)
+{
 	name=stripslashes(name);
-	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
-	{
-		return true;
-	}
-	else
-	{
-		return false;
+	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
+	{
+		return true;
+	}
+	else
+	{
+		return false;
 	}
-}
-</script>
-<?php
-
-//echo $admin_output;
-/*
------------------------------------------------------------
-	DISPLAY SECTION
------------------------------------------------------------
-*/
-
-echo $_SESSION['oLP']->build_action_menu();
-echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
+}
+</script>
+<?php
+
+//echo $admin_output;
+/*
+-----------------------------------------------------------
+	DISPLAY SECTION
+-----------------------------------------------------------
+*/
+
+echo $_SESSION['oLP']->build_action_menu();
+echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
 		echo '<tr>';
-		echo '<td class="tree">';
+		echo '<td class="tree">';
 
 		$path_item = isset($_GET['path_item'])?$_GET['path_item']:0;
-		$path_item = Database::escape_string($path_item);
-		$tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
-		$sql_doc = "SELECT path FROM " . $tbl_doc . " WHERE id = '". $path_item."' ";
-		$res_doc=Database::query($sql_doc, __FILE__, __LINE__);
+		$path_item = Database::escape_string($path_item);
+		$tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
+		$sql_doc = "SELECT path FROM " . $tbl_doc . " WHERE id = '". $path_item."' ";
+		$res_doc=Database::query($sql_doc, __FILE__, __LINE__);
 		$path_file=Database::result($res_doc,0,0);
-		$path_parts = pathinfo($path_file);
+		$path_parts = pathinfo($path_file);
 
-		if (Database::num_rows($res_doc) > 0 && $path_parts['extension']=='html'){
-			$count_items = count($_SESSION['oLP']->ordered_items);
-			$style = ($count_items > 12)?' style="height:250px;width:230px;overflow-x : auto; overflow : scroll;" ':' class="lp_tree" ';
+		if (Database::num_rows($res_doc) > 0 && $path_parts['extension']=='html'){
+			$count_items = count($_SESSION['oLP']->ordered_items);
+			$style = ($count_items > 12)?' style="height:250px;width:230px;overflow-x : auto; overflow : scroll;" ':' class="lp_tree" ';
 			echo '<div '.$style.'>';
-			//build the tree with the menu items in it
+			//build the tree with the menu items in it
 			echo $_SESSION['oLP']->build_tree();
-			echo '</div>';
+			echo '</div>';
 			// show the template list
 			echo '<p style="border-bottom:1px solid #999999; margin:0; padding:2px;"></p>'; //line
 			echo '<br>';
-			echo '<div id="frmModel" style="display:block; height:890px;width:100px; position:relative;"></div>';
-		} else {
+			echo '<div id="frmModel" style="display:block; height:890px;width:100px; position:relative;"></div>';
+		} else {
 			echo '<div class="lp_tree" style="height:90%" >';
-			//build the tree with the menu items in it
+			//build the tree with the menu items in it
 			echo $_SESSION['oLP']->build_tree();
-			echo '</div>';
+			echo '</div>';
 		}
 
 		echo '</td>';
 		echo '<td class="workspace">';
-			if(isset($is_success) && $is_success === true) {
+			if(isset($is_success) && $is_success === true) {
 				$msg = '<div class="lp_message" style="margin-bottom:10px;">';
 					$msg .= 'The item has been edited.';
 				$msg .= '</div>';
-				echo $_SESSION['oLP']->display_item($_GET['id'], $msg);
-			} else {
-				echo $_SESSION['oLP']->display_edit_item($_GET['id']);
+				echo $_SESSION['oLP']->display_item($_GET['id'], $msg);
+			} else {
+				echo $_SESSION['oLP']->display_edit_item($_GET['id']);
 			}
 		echo '</td>';
 	echo '</tr>';
-echo '</table>';
-
-/*
-==============================================================================
+echo '</table>';
+
+/*
+==============================================================================
 		FOOTER
-==============================================================================
+==============================================================================
 */
-Display::display_footer();
+Display::display_footer();
 ?>

+ 177 - 177
main/newscorm/lp_edit_item_prereq.php

@@ -1,211 +1,211 @@
-<?php
-/*
+<?php
+/*
 ==============================================================================
-	Dokeos - elearning and course management software
+	Dokeos - elearning and course management software
 
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Patrick Cool
-	Copyright (c) Denes Nagy
-	Copyright (c) Yannick Warnier
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Patrick Cool
+	Copyright (c) Denes Nagy
+	Copyright (c) Yannick Warnier
 
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
+	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.
+	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.
+	See the GNU General Public License for more details.
 
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
 ==============================================================================
-*/
-/**
+*/
+/**
 ==============================================================================
-* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
-*
-* @author Patrick Cool
-* @author Denes Nagy
-* @author Roan Embrechts, refactoring and code cleaning
-* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
-* @package dokeos.learnpath
+* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
+*
+* @author Patrick Cool
+* @author Denes Nagy
+* @author Roan Embrechts, refactoring and code cleaning
+* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
+* @package dokeos.learnpath
 ==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
 */
-$this_section=SECTION_COURSES;
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
 */
-//the main_api.lib.php, database.lib.php and display.lib.php
-//libraries are included by default
-
-include('learnpath_functions.inc.php');
-//include('../resourcelinker/resourcelinker.inc.php');
-include('resourcelinker.inc.php');
-//rewrite the language file, sadly overwritten by resourcelinker.inc.php
+$this_section=SECTION_COURSES;
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+//the main_api.lib.php, database.lib.php and display.lib.php
+//libraries are included by default
+
+include('learnpath_functions.inc.php');
+//include('../resourcelinker/resourcelinker.inc.php');
+include('resourcelinker.inc.php');
+//rewrite the language file, sadly overwritten by resourcelinker.inc.php
 // name of the language file that needs to be included
-$language_file = "learnpath";
-
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
+$language_file = "learnpath";
+
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
 */
-$is_allowed_to_edit = api_is_allowed_to_edit();
-
-$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
-
-$isStudentView  = (int) $_REQUEST['isStudentView'];
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-$submit			= $_POST['submit_button'];
-/*
-$chapter_id     = $_GET['chapter_id'];
-$title          = $_POST['title'];
-$description   = $_POST['description'];
-$Submititem     = $_POST['Submititem'];
-$action         = $_REQUEST['action'];
-$id             = (int) $_REQUEST['id'];
-$type           = $_REQUEST['type'];
-$direction      = $_REQUEST['direction'];
-$moduleid       = $_REQUEST['moduleid'];
-$prereq         = $_REQUEST['prereq'];
-$type           = $_REQUEST['type'];
-*/
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-// using the resource linker as a tool for adding resources to the learning path
-if ($action=="add" and $type=="learnpathitem")
-{
-	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
-}
-if ( (! $is_allowed_to_edit) or ($isStudentView) )
-{
-	error_log('New LP - User not authorized in lp_edit_item_prereq.php');
-	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
-}
-//from here on, we are admin because of the previous condition, so don't check anymore
-
+$is_allowed_to_edit = api_is_allowed_to_edit();
+
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
+
+$isStudentView  = (int) $_REQUEST['isStudentView'];
+$learnpath_id   = (int) $_REQUEST['lp_id'];
+$submit			= $_POST['submit_button'];
+/*
+$chapter_id     = $_GET['chapter_id'];
+$title          = $_POST['title'];
+$description   = $_POST['description'];
+$Submititem     = $_POST['Submititem'];
+$action         = $_REQUEST['action'];
+$id             = (int) $_REQUEST['id'];
+$type           = $_REQUEST['type'];
+$direction      = $_REQUEST['direction'];
+$moduleid       = $_REQUEST['moduleid'];
+$prereq         = $_REQUEST['prereq'];
+$type           = $_REQUEST['type'];
+*/
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+// using the resource linker as a tool for adding resources to the learning path
+if ($action=="add" and $type=="learnpathitem")
+{
+	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
+}
+if ( (! $is_allowed_to_edit) or ($isStudentView) )
+{
+	error_log('New LP - User not authorized in lp_edit_item_prereq.php');
+	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
+}
+//from here on, we are admin because of the previous condition, so don't check anymore
+
 $sql_query = "SELECT * FROM $tbl_lp WHERE id = $learnpath_id";
-$result=Database::query($sql_query);
+$result=Database::query($sql_query);
 $therow=Database::fetch_array($result);
-
-//$admin_output = '';
-/*
------------------------------------------------------------
-	Course admin section
-	- all the functions not available for students - always available in this case (page only shown to admin)
------------------------------------------------------------
+
+//$admin_output = '';
+/*
+-----------------------------------------------------------
+	Course admin section
+	- all the functions not available for students - always available in this case (page only shown to admin)
+-----------------------------------------------------------
 */
-/*==================================================
-			SHOWING THE ADMIN TOOLS
- ==================================================*/
-
-
-
-/*==================================================
-	prerequisites setting end
+/*==================================================
+			SHOWING THE ADMIN TOOLS
  ==================================================*/
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+
+
+
+/*==================================================
+	prerequisites setting end
+ ==================================================*/
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
-
-$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
-
-//Theme calls
-$show_learn_path=true;
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-
-Display::display_header(null,'Path');
-//api_display_tool_title($therow['name']);
-
-$suredel = trim(get_lang('AreYouSureToDelete'));
-//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
-?>
-<script type='text/javascript'>
-/* <![CDATA[ */
-function stripslashes(str) {
-	str=str.replace(/\\'/g,'\'');
-	str=str.replace(/\\"/g,'"');
-	str=str.replace(/\\\\/g,'\\');
-	str=str.replace(/\\0/g,'\0');
-	return str;
-}
-function confirmation(name)
-{
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
+
+$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
+
+//Theme calls
+$show_learn_path=true;
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+
+Display::display_header(null,'Path');
+//api_display_tool_title($therow['name']);
+
+$suredel = trim(get_lang('AreYouSureToDelete'));
+//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
+?>
+<script type='text/javascript'>
+/* <![CDATA[ */
+function stripslashes(str) {
+	str=str.replace(/\\'/g,'\'');
+	str=str.replace(/\\"/g,'"');
+	str=str.replace(/\\\\/g,'\\');
+	str=str.replace(/\\0/g,'\0');
+	return str;
+}
+function confirmation(name)
+{
 	name=stripslashes(name);
-	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
-	{
-		return true;
-	}
-	else
-	{
-		return false;
+	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
+	{
+		return true;
+	}
+	else
+	{
+		return false;
 	}
-}
-</script>
-<?php
-
-//echo $admin_output;
-/*
------------------------------------------------------------
-	DISPLAY SECTION
------------------------------------------------------------
-*/
-echo $_SESSION['oLP']->build_action_menu();
-echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
-	echo '<tr>';
+}
+</script>
+<?php
+
+//echo $admin_output;
+/*
+-----------------------------------------------------------
+	DISPLAY SECTION
+-----------------------------------------------------------
+*/
+echo $_SESSION['oLP']->build_action_menu();
+echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
+	echo '<tr>';
 
 		echo '<td class="tree">';
 			echo '<div class="lp_tree">';
-				//build the tree with the menu items in it
-				echo $_SESSION['oLP']->build_tree();
+				//build the tree with the menu items in it
+				echo $_SESSION['oLP']->build_tree();
 
 			echo '</div>';
-		echo '</td>';
-		echo '<td class="workspace">';
+		echo '</td>';
+		echo '<td class="workspace">';
 
-			if(isset($is_success) && $is_success === true) {
+			if(isset($is_success) && $is_success === true) {
 				echo '<div class="lp_message" style="margin:3px 10px;">';
 				echo get_lang("PrerequisitesAdded");
-				echo '</div>';
-			} else {
-				echo $_SESSION['oLP']->display_item_prerequisites_form($_GET['id']);
+				echo '</div>';
+			} else {
+				echo $_SESSION['oLP']->display_item_prerequisites_form($_GET['id']);
 			}
 		echo '</td>';
 	echo '</tr>';
-echo '</table>';
-
-/*
-==============================================================================
+echo '</table>';
+
+/*
+==============================================================================
 		FOOTER
-==============================================================================
+==============================================================================
 */
-Display::display_footer();
+Display::display_footer();
 ?>

+ 17 - 17
main/newscorm/lp_export.php

@@ -1,19 +1,19 @@
-<?php //$id: $
-/**
- * Script to export the current path as a SCORM zip package.
+<?php //$id: $
+/**
+ * Script to export the current path as a SCORM zip package.
  * This script cannot use the common controller lp_controller.php because we need to keep
- * the headers clean of any session prior to output-ing the resulting file.
- * As we still need to check the user's credentials (because he might not have access to this file),
- * we need to get some ID proof.
- * Once the ID is checked with the database info, generate the file, send the corresponding headers
- * to force the download and let the user do the rest. This script should not change the screen
- * at all, so the user will still be able to continue what he was doing.
- * @todo get some ID proof
+ * the headers clean of any session prior to output-ing the resulting file.
+ * As we still need to check the user's credentials (because he might not have access to this file),
+ * we need to get some ID proof.
+ * Once the ID is checked with the database info, generate the file, send the corresponding headers
+ * to force the download and let the user do the rest. This script should not change the screen
+ * at all, so the user will still be able to continue what he was doing.
+ * @todo get some ID proof
  * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * The script takes three get parameters that enable the export.
- */
-
-?>
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * The script takes three get parameters that enable the export.
+ */
+
+?>

+ 14 - 14
main/newscorm/lp_footer.php

@@ -1,15 +1,15 @@
-<?php //$id: $
-/**
- * Script that displays the footer frame for lp_view.php
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-require_once('back_compat.inc.php');
-include_once('../inc/reduced_header.inc.php');
-Display::display_footer();
+<?php //$id: $
+/**
+ * Script that displays the footer frame for lp_view.php
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+require_once('back_compat.inc.php');
+include_once('../inc/reduced_header.inc.php');
+Display::display_footer();
 ?>

+ 80 - 80
main/newscorm/lp_header.php

@@ -1,83 +1,83 @@
-<?php //$id: $
-/**
- * Script that displays the header frame for lp_view.php
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
+<?php //$id: $
+/**
+ * Script that displays the header frame for lp_view.php
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
 // name of the language file that needs to be included
-$language_file[] = "scormdocument";
-require_once('back_compat.inc.php');
-require_once('learnpath.class.php');
-require_once('scorm.class.php');
-require_once('aicc.class.php');
-if(isset($_SESSION['lpobject'])){
-	$temp = $_SESSION['lpobject'];
-	$_SESSION['oLP'] = unserialize($temp);
-}
-$path_name = $_SESSION['oLP']->get_name();
-$path_id = $_SESSION['oLP']->get_id();
-// use the flag set in lp_view.php to check if this script has been loaded
-// as a frame of lp_view.php. Otherwise, redirect to lp_controller
-if(!isset($_SESSION['loaded_lp_view']) || $_SESSION['loaded_lp_view']==false)
-{
-	header('location: lp_controller.php?'.api_get_cidreq().'&action=view&item_id='.$path_id);
-}
-//unset the flag as it has been used already
-$_SESSION['loaded_lp_view'] = false;
-// Check if the learnpaths list should be accessible to the user
-$show_link = true;
-if(!api_is_allowed_to_edit()) //if the user has no edit permission (simple user)
-{
-	$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
-	$result = Database::query("SELECT * FROM $course_tool_table WHERE name='learnpath'",__FILE__,__LINE__);
-	if(Database::num_rows($result)>0)
-	{
-		$row = Database::fetch_array($result);
-		if($row['visibility'] == '0') //if the tool is *not* visible
-		{
-			$show_link = false;
-		}
-	}
-	else
-	{
-		$show_link = false;
-	}
-}
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+$language_file[] = "scormdocument";
+require_once('back_compat.inc.php');
+require_once('learnpath.class.php');
+require_once('scorm.class.php');
+require_once('aicc.class.php');
+if(isset($_SESSION['lpobject'])){
+	$temp = $_SESSION['lpobject'];
+	$_SESSION['oLP'] = unserialize($temp);
+}
+$path_name = $_SESSION['oLP']->get_name();
+$path_id = $_SESSION['oLP']->get_id();
+// use the flag set in lp_view.php to check if this script has been loaded
+// as a frame of lp_view.php. Otherwise, redirect to lp_controller
+if(!isset($_SESSION['loaded_lp_view']) || $_SESSION['loaded_lp_view']==false)
+{
+	header('location: lp_controller.php?'.api_get_cidreq().'&action=view&item_id='.$path_id);
+}
+//unset the flag as it has been used already
+$_SESSION['loaded_lp_view'] = false;
+// Check if the learnpaths list should be accessible to the user
+$show_link = true;
+if(!api_is_allowed_to_edit()) //if the user has no edit permission (simple user)
+{
+	$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
+	$result = Database::query("SELECT * FROM $course_tool_table WHERE name='learnpath'",__FILE__,__LINE__);
+	if(Database::num_rows($result)>0)
+	{
+		$row = Database::fetch_array($result);
+		if($row['visibility'] == '0') //if the tool is *not* visible
+		{
+			$show_link = false;
+		}
+	}
+	else
+	{
+		$show_link = false;
+	}
+}
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-$header_hide_main_div = true;
-if($show_link)
-{
-	$interbreadcrumb[]= array ("url"=>"./lp_controller.php?action=list", "name"=> get_lang(ucfirst(TOOL_LEARNPATH)));
-}
-// else we don't display get_lang(ucfirst(TOOL_LEARNPATH)) in the breadcrumb since the learner accessed it directly from the course homepage
-$interbreadcrumb[] = array("url"=>"./lp_controller.php?action=view&lp_id=".$path_id,'name'=>$path_name);
-$noPHP_SELF = true;
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-include('../inc/reduced_header.inc.php');
-echo '<div style="font-size:14px;padding-left: 17px;">';
-echo '<table ><tr><td>';
-echo '<a href="./lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">';
-echo '<img src="../img/lp_arrow.gif">';
-echo '<a>';
-echo '</td><td>';
-echo '<a class="link" href="./lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">'.get_lang('CourseHomepageLink').'</a>';
-echo '</td></tr><table>';
-echo '</div>';
-?>
-</body>
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+$header_hide_main_div = true;
+if($show_link)
+{
+	$interbreadcrumb[]= array ("url"=>"./lp_controller.php?action=list", "name"=> get_lang(ucfirst(TOOL_LEARNPATH)));
+}
+// else we don't display get_lang(ucfirst(TOOL_LEARNPATH)) in the breadcrumb since the learner accessed it directly from the course homepage
+$interbreadcrumb[] = array("url"=>"./lp_controller.php?action=view&lp_id=".$path_id,'name'=>$path_name);
+$noPHP_SELF = true;
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+include('../inc/reduced_header.inc.php');
+echo '<div style="font-size:14px;padding-left: 17px;">';
+echo '<table ><tr><td>';
+echo '<a href="./lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">';
+echo '<img src="../img/lp_arrow.gif">';
+echo '<a>';
+echo '</td><td>';
+echo '<a class="link" href="./lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">'.get_lang('CourseHomepageLink').'</a>';
+echo '</td></tr><table>';
+echo '</div>';
+?>
+</body>
 </html>

+ 43 - 43
main/newscorm/lp_log.php

@@ -1,44 +1,44 @@
-<?php //$id: $
-/**
- * Container script for the messages coming from the learnpath object. Initially, this wasn't supposed to be
- * a separate file but rather some text included in lp_view.php, but SCORM involves loading a script that
- * saves the data asynchronously while the SCORM learning path carries on. Having an informational iframe
- * helps not popping up an additional window when saving data.
+<?php //$id: $
+/**
+ * Container script for the messages coming from the learnpath object. Initially, this wasn't supposed to be
+ * a separate file but rather some text included in lp_view.php, but SCORM involves loading a script that
+ * saves the data asynchronously while the SCORM learning path carries on. Having an informational iframe
+ * helps not popping up an additional window when saving data.
  *
- * This script is also used to refresh the TOC as sometimes the SCORM JS messages are taken into account
- * only after the TOC is drawn. As such, you might complete an item, browse to the next page, have the
- * TOC drawn with your 'incomplete' status, while the SCORM messages generally arrives just after the TOC
- * is drawn. By updating it here and in lp_save.php, we avoid funny visual effect like having a complete
- * item showing as incomplete.
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-require_once('back_compat.inc.php');
-if (empty($charset)) {
-	$charset = 'ISO-8859-15';
-}
-
-$htmlHeadXtra[] = '<script language="javascript">
-function cleanlog(){
-  if(document.getElementById){
-  	document.getElementById("log_content").innerHTML = "";
-  }
-}
-</script>';
-
-$scorm_css_header=true;
-$display_mode='';
-$lp_theme_log=true;
-include_once('../inc/reduced_header.inc.php');
-?>
-<body>
-<div id="log_content">
-</div>
-<div style="color: white;" onclick="cleanlog();">.</div>
-</body>
-</html>
+ * This script is also used to refresh the TOC as sometimes the SCORM JS messages are taken into account
+ * only after the TOC is drawn. As such, you might complete an item, browse to the next page, have the
+ * TOC drawn with your 'incomplete' status, while the SCORM messages generally arrives just after the TOC
+ * is drawn. By updating it here and in lp_save.php, we avoid funny visual effect like having a complete
+ * item showing as incomplete.
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+require_once('back_compat.inc.php');
+if (empty($charset)) {
+	$charset = 'ISO-8859-15';
+}
+
+$htmlHeadXtra[] = '<script language="javascript">
+function cleanlog(){
+  if(document.getElementById){
+  	document.getElementById("log_content").innerHTML = "";
+  }
+}
+</script>';
+
+$scorm_css_header=true;
+$display_mode='';
+$lp_theme_log=true;
+include_once('../inc/reduced_header.inc.php');
+?>
+<body>
+<div id="log_content">
+</div>
+<div style="color: white;" onclick="cleanlog();">.</div>
+</body>
+</html>

+ 53 - 53
main/newscorm/lp_message.php

@@ -1,55 +1,55 @@
-<?php //$id: $
-/**
- * Container script for the messages coming from the learnpath object. Initially, this wasn't supposed to be
- * a separate file but rather some text included in lp_view.php, but SCORM involves loading a script that
- * saves the data asynchronously while the SCORM learning path carries on. Having an informational iframe
- * helps not popping up an additional window when saving data.
+<?php //$id: $
+/**
+ * Container script for the messages coming from the learnpath object. Initially, this wasn't supposed to be
+ * a separate file but rather some text included in lp_view.php, but SCORM involves loading a script that
+ * saves the data asynchronously while the SCORM learning path carries on. Having an informational iframe
+ * helps not popping up an additional window when saving data.
  *
- * This script is also used to refresh the TOC as sometimes the SCORM JS messages are taken into account
- * only after the TOC is drawn. As such, you might complete an item, browse to the next page, have the
- * TOC drawn with your 'incomplete' status, while the SCORM messages generally arrives just after the TOC
- * is drawn. By updating it here and in lp_save.php, we avoid funny visual effect like having a complete
- * item showing as incomplete.
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
+ * This script is also used to refresh the TOC as sometimes the SCORM JS messages are taken into account
+ * only after the TOC is drawn. As such, you might complete an item, browse to the next page, have the
+ * TOC drawn with your 'incomplete' status, while the SCORM messages generally arrives just after the TOC
+ * is drawn. By updating it here and in lp_save.php, we avoid funny visual effect like having a complete
+ * item showing as incomplete.
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
 // name of the language file that needs to be included
-$language_file = "learnpath";
-require_once('back_compat.inc.php');
-require_once('learnpath.class.php');
-require_once('scorm.class.php');
-if(empty($debug)){$debug=0;}
-$error = '';
-$display_mode = '';
-if(isset($_SESSION['lpobject'])){
-	$temp = $_SESSION['lpobject'];
-	$_SESSION['oLP'] = unserialize($temp);
-	$error = $_SESSION['oLP']->error;
-	$display_mode = $_SESSION['oLP']->mode;
-}
-if($debug>0){error_log('New LP - Loaded lp_message : '.$_SERVER['REQUEST_URI'].' from '.$_SERVER['HTTP_REFERER'],0);}
-if (empty($charset)) {
-	$charset = 'ISO-8859-15';
-}
-
-$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
-  var dokeos_xajax_handler = window.parent.oxajax;
-</script>';
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-$scorm_css_header=true;
-include_once('../inc/reduced_header.inc.php');
-//close the session immediately to avoid concurrent access problems
-session_write_close();
-?>
-<body>
-<div id="msg_div_id">
-<?php
-echo $error;
-?>
-</div>
-</body></html>
+$language_file = "learnpath";
+require_once('back_compat.inc.php');
+require_once('learnpath.class.php');
+require_once('scorm.class.php');
+if(empty($debug)){$debug=0;}
+$error = '';
+$display_mode = '';
+if(isset($_SESSION['lpobject'])){
+	$temp = $_SESSION['lpobject'];
+	$_SESSION['oLP'] = unserialize($temp);
+	$error = $_SESSION['oLP']->error;
+	$display_mode = $_SESSION['oLP']->mode;
+}
+if($debug>0){error_log('New LP - Loaded lp_message : '.$_SERVER['REQUEST_URI'].' from '.$_SERVER['HTTP_REFERER'],0);}
+if (empty($charset)) {
+	$charset = 'ISO-8859-15';
+}
+
+$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
+  var dokeos_xajax_handler = window.parent.oxajax;
+</script>';
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+$scorm_css_header=true;
+include_once('../inc/reduced_header.inc.php');
+//close the session immediately to avoid concurrent access problems
+session_write_close();
+?>
+<body>
+<div id="msg_div_id">
+<?php
+echo $error;
+?>
+</div>
+</body></html>

+ 182 - 182
main/newscorm/lp_move_item.php

@@ -1,216 +1,216 @@
-<?php
-/*
+<?php
+/*
 ==============================================================================
-	Dokeos - elearning and course management software
+	Dokeos - elearning and course management software
 
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Patrick Cool
-	Copyright (c) Denes Nagy
-	Copyright (c) Yannick Warnier
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Patrick Cool
+	Copyright (c) Denes Nagy
+	Copyright (c) Yannick Warnier
 
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
+	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.
+	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.
+	See the GNU General Public License for more details.
 
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
 ==============================================================================
-*/
-/**
+*/
+/**
 ==============================================================================
-* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
-*
-* @author Patrick Cool
-* @author Denes Nagy
-* @author Roan Embrechts, refactoring and code cleaning
-* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
-* @package dokeos.learnpath
+* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
+*
+* @author Patrick Cool
+* @author Denes Nagy
+* @author Roan Embrechts, refactoring and code cleaning
+* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
+* @package dokeos.learnpath
 ==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
 */
-$this_section=SECTION_COURSES;
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
 */
-//the main_api.lib.php, database.lib.php and display.lib.php
-//libraries are included by default
-
-include('learnpath_functions.inc.php');
-//include('../resourcelinker/resourcelinker.inc.php');
-include('resourcelinker.inc.php');
-//rewrite the language file, sadly overwritten by resourcelinker.inc.php
+$this_section=SECTION_COURSES;
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+//the main_api.lib.php, database.lib.php and display.lib.php
+//libraries are included by default
+
+include('learnpath_functions.inc.php');
+//include('../resourcelinker/resourcelinker.inc.php');
+include('resourcelinker.inc.php');
+//rewrite the language file, sadly overwritten by resourcelinker.inc.php
 // name of the language file that needs to be included
-$language_file = "learnpath";
-
-/*
------------------------------------------------------------
-	Header and action code
------------------------------------------------------------
+$language_file = "learnpath";
+
+/*
+-----------------------------------------------------------
+	Header and action code
+-----------------------------------------------------------
 */
-$htmlHeadXtra[] = $_SESSION['oLP']->create_js();
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
+$htmlHeadXtra[] = $_SESSION['oLP']->create_js();
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
 */
-$is_allowed_to_edit = api_is_allowed_to_edit();
-
-$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
-
-$isStudentView  = (int) $_REQUEST['isStudentView'];
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-$submit			= $_POST['submit_button'];
-/*
-$chapter_id     = $_GET['chapter_id'];
-$title          = $_POST['title'];
-$description   = $_POST['description'];
-$Submititem     = $_POST['Submititem'];
-$action         = $_REQUEST['action'];
-$id             = (int) $_REQUEST['id'];
-$type           = $_REQUEST['type'];
-$direction      = $_REQUEST['direction'];
-$moduleid       = $_REQUEST['moduleid'];
-$prereq         = $_REQUEST['prereq'];
-$type           = $_REQUEST['type'];
-*/
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-// using the resource linker as a tool for adding resources to the learning path
-if ($action=="add" and $type=="learnpathitem")
-{
-	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
-}
-if ( (! $is_allowed_to_edit) or ($isStudentView) )
-{
-	error_log('New LP - User not authorized in lp_add_item.php');
-	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
-}
-//from here on, we are admin because of the previous condition, so don't check anymore
-
+$is_allowed_to_edit = api_is_allowed_to_edit();
+
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
+
+$isStudentView  = (int) $_REQUEST['isStudentView'];
+$learnpath_id   = (int) $_REQUEST['lp_id'];
+$submit			= $_POST['submit_button'];
+/*
+$chapter_id     = $_GET['chapter_id'];
+$title          = $_POST['title'];
+$description   = $_POST['description'];
+$Submititem     = $_POST['Submititem'];
+$action         = $_REQUEST['action'];
+$id             = (int) $_REQUEST['id'];
+$type           = $_REQUEST['type'];
+$direction      = $_REQUEST['direction'];
+$moduleid       = $_REQUEST['moduleid'];
+$prereq         = $_REQUEST['prereq'];
+$type           = $_REQUEST['type'];
+*/
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+// using the resource linker as a tool for adding resources to the learning path
+if ($action=="add" and $type=="learnpathitem")
+{
+	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
+}
+if ( (! $is_allowed_to_edit) or ($isStudentView) )
+{
+	error_log('New LP - User not authorized in lp_add_item.php');
+	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
+}
+//from here on, we are admin because of the previous condition, so don't check anymore
+
 $sql_query = "SELECT * FROM $tbl_lp WHERE id = $learnpath_id";
-$result=Database::query($sql_query);
+$result=Database::query($sql_query);
 $therow=Database::fetch_array($result);
-
-//$admin_output = '';
-/*
------------------------------------------------------------
-	Course admin section
-	- all the functions not available for students - always available in this case (page only shown to admin)
------------------------------------------------------------
+
+//$admin_output = '';
+/*
+-----------------------------------------------------------
+	Course admin section
+	- all the functions not available for students - always available in this case (page only shown to admin)
+-----------------------------------------------------------
 */
-/*==================================================
-			SHOWING THE ADMIN TOOLS
- ==================================================*/
-
-
-
-/*==================================================
-	prerequisites setting end
+/*==================================================
+			SHOWING THE ADMIN TOOLS
  ==================================================*/
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+
+
+
+/*==================================================
+	prerequisites setting end
+ ==================================================*/
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
-
-$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
-
-//Theme calls
-$show_learn_path=true;
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-
-Display::display_header(null,'Path');
-//api_display_tool_title($therow['name']);
-
-$suredel = trim(get_lang('AreYouSureToDelete'));
-//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
-?>
-<script type='text/javascript'>
-/* <![CDATA[ */
-function stripslashes(str) {
-	str=str.replace(/\\'/g,'\'');
-	str=str.replace(/\\"/g,'"');
-	str=str.replace(/\\\\/g,'\\');
-	str=str.replace(/\\0/g,'\0');
-	return str;
-}
-function confirmation(name)
-{
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
+
+$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
+
+//Theme calls
+$show_learn_path=true;
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+
+Display::display_header(null,'Path');
+//api_display_tool_title($therow['name']);
+
+$suredel = trim(get_lang('AreYouSureToDelete'));
+//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
+?>
+<script type='text/javascript'>
+/* <![CDATA[ */
+function stripslashes(str) {
+	str=str.replace(/\\'/g,'\'');
+	str=str.replace(/\\"/g,'"');
+	str=str.replace(/\\\\/g,'\\');
+	str=str.replace(/\\0/g,'\0');
+	return str;
+}
+function confirmation(name)
+{
 	name=stripslashes(name);
-	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
-	{
-		return true;
-	}
-	else
-	{
-		return false;
+	if (confirm("<?php echo $suredel; ?> " + name + " ?"))
+	{
+		return true;
 	}
-}
-</script>
-<?php
-
-//echo $admin_output;
-
-/*
------------------------------------------------------------
-	DISPLAY SECTION
------------------------------------------------------------
-*/
-echo $_SESSION['oLP']->build_action_menu();
-echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
+	else
+	{
+		return false;
+	}
+}
+</script>
+<?php
+
+//echo $admin_output;
+
+/*
+-----------------------------------------------------------
+	DISPLAY SECTION
+-----------------------------------------------------------
+*/
+echo $_SESSION['oLP']->build_action_menu();
+echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
 	echo '<tr>';
-		echo '<td class="tree">';
+		echo '<td class="tree">';
 			echo '<div class="lp_tree">';
-				//build the tree with the menu items in it
+				//build the tree with the menu items in it
 				echo $_SESSION['oLP']->build_tree();
 			echo '</div>';
-		echo '</td>';
-		echo '<td class="workspace">';
-			if(isset($is_success) && $is_success === true) {
+		echo '</td>';
+		echo '<td class="workspace">';
+			if(isset($is_success) && $is_success === true) {
 				$msg = '<div class="lp_message" style="margin-bottom:10px;">';
 					$msg .= 'The item has been moved.';
 				$msg .= '</div>';
-				echo $_SESSION['oLP']->display_item($_GET['id'], $msg);
-			} else {
-				echo $_SESSION['oLP']->display_move_item($_GET['id']);
+				echo $_SESSION['oLP']->display_item($_GET['id'], $msg);
+			} else {
+				echo $_SESSION['oLP']->display_move_item($_GET['id']);
 			}
 		echo '</td>';
 	echo '</tr>';
-echo '</table>';
-
-/*
-==============================================================================
+echo '</table>';
+
+/*
+==============================================================================
 		FOOTER
-==============================================================================
+==============================================================================
 */
-Display::display_footer();
+Display::display_footer();
 ?>

+ 48 - 48
main/newscorm/lp_nav.php

@@ -1,57 +1,57 @@
-<?php //$id: $
-/**
- * Script opened in an iframe and containing the learning path's navigation and progress bar
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
+<?php //$id: $
+/**
+ * Script opened in an iframe and containing the learning path's navigation and progress bar
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
 // name of the language file that needs to be included
-$language_file[] = "scormdocument";
-$language_file[] = "scorm";
-$language_file[] = "learnpath";
-require_once('back_compat.inc.php');
-require_once('learnpath.class.php');
-require_once('scorm.class.php');
-require_once('aicc.class.php');
-//error_log('New LP - Loaded lp_nav: '.$_SERVER['REQUEST_URI'],0);
-$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
-	  var dokeos_xajax_handler = window.parent.oxajax;
-	</script>';
-$progress_bar = '';
-$navigation_bar = '';
-$display_mode = '';
-$autostart = 'true';
-
-if(isset($_SESSION['lpobject'])) {
-	//if($debug>0) //error_log('New LP - in lp_nav.php - SESSION[lpobject] is defined',0);
-	$oLP = unserialize($_SESSION['lpobject']);
-	if(is_object($oLP)) {
-		$_SESSION['oLP'] = $oLP;
-	} else {
-		//error_log('New LP - in lp_nav.php - SESSION[lpobject] is not object - dying',0);
-		die('Could not instanciate lp object');
+$language_file[] = "scormdocument";
+$language_file[] = "scorm";
+$language_file[] = "learnpath";
+require_once('back_compat.inc.php');
+require_once('learnpath.class.php');
+require_once('scorm.class.php');
+require_once('aicc.class.php');
+//error_log('New LP - Loaded lp_nav: '.$_SERVER['REQUEST_URI'],0);
+$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
+	  var dokeos_xajax_handler = window.parent.oxajax;
+	</script>';
+$progress_bar = '';
+$navigation_bar = '';
+$display_mode = '';
+$autostart = 'true';
+
+if(isset($_SESSION['lpobject'])) {
+	//if($debug>0) //error_log('New LP - in lp_nav.php - SESSION[lpobject] is defined',0);
+	$oLP = unserialize($_SESSION['lpobject']);
+	if(is_object($oLP)) {
+		$_SESSION['oLP'] = $oLP;
+	} else {
+		//error_log('New LP - in lp_nav.php - SESSION[lpobject] is not object - dying',0);
+		die('Could not instanciate lp object');
 	}
 	$display_mode = $_SESSION['oLP']->mode;
-	$scorm_css_header = true;
-	$lp_theme_css = $_SESSION['oLP']->get_theme();
-	//Setting up the CSS theme if exists
-	include_once('../inc/reduced_header.inc.php');
+	$scorm_css_header = true;
+	$lp_theme_css = $_SESSION['oLP']->get_theme();
+	//Setting up the CSS theme if exists
+	include_once('../inc/reduced_header.inc.php');
 
-	if (!empty($lp_theme_css) && !empty($mycourselptheme) && $mycourselptheme!=-1 && $mycourselptheme== 1 ) {
+	if (!empty($lp_theme_css) && !empty($mycourselptheme) && $mycourselptheme!=-1 && $mycourselptheme== 1 ) {
 		global $lp_theme_css;
-	} else {
-		$lp_theme_css=$my_style;
-	}
+	} else {
+		$lp_theme_css=$my_style;
+	}
 	//$progress_bar = $_SESSION['oLP']->get_progress_bar();
 	$progress_bar = $_SESSION['oLP']->get_progress_bar('',-1,'',true);
 	$navigation_bar = $_SESSION['oLP']->get_navigation_bar();
-	$mediaplayer = $_SESSION['oLP']->get_mediaplayer($autostart);
-}
-session_write_close();
-?>
+	$mediaplayer = $_SESSION['oLP']->get_mediaplayer($autostart);
+}
+session_write_close();
+?>
 <span><?php echo (!empty($mediaplayer))?$mediaplayer:'&nbsp;' ?></span>

+ 32 - 32
main/newscorm/lp_save.php

@@ -1,33 +1,33 @@
-<?php //$id: $
-/**
- * Script that handles the saving of item status
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Init
- */
-//done by lp_controller.php
-/**
- * Switching within the field to update
- */
-$msg = $_SESSION['oLP']->get_message();
-$charset = 'ISO-8859-15'; //not taken into account here as we don't include a header
-error_log('New LP - Loaded lp_save : '.$_SERVER['REQUEST_URI'].' from '.$_SERVER['HTTP_REFERER'],0);
-?>
+<?php //$id: $
+/**
+ * Script that handles the saving of item status
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Init
+ */
+//done by lp_controller.php
+/**
+ * Switching within the field to update
+ */
+$msg = $_SESSION['oLP']->get_message();
+$charset = 'ISO-8859-15'; //not taken into account here as we don't include a header
+error_log('New LP - Loaded lp_save : '.$_SERVER['REQUEST_URI'].' from '.$_SERVER['HTTP_REFERER'],0);
+?>
 <!DOCTYPE html
-     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
-
-<script language='javascript'>
-<?php
-if($_SESSION['oLP']->mode != 'fullscreen'){
-}
-?>
-</script>
-
-</head>
-<body>
-</body></html>
+     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+
+<script language='javascript'>
+<?php
+if($_SESSION['oLP']->mode != 'fullscreen'){
+}
+?>
+</script>
+
+</head>
+<body>
+</body></html>

+ 671 - 671
main/newscorm/lp_stats.php

@@ -1,774 +1,774 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-/**
- * This script displays statistics on the current learning path (scorm)
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+/**
+ * This script displays statistics on the current learning path (scorm)
  *
- * This script must be included by lp_controller.php to get basic initialisation
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-
-require_once('learnpath.class.php');
-//require_once('scorm.class.php');
-require_once ('resourcelinker.inc.php');
-require_once ('../inc/lib/tracking.lib.php');
-require_once ('../inc/lib/course.lib.php');
-
-if(empty($_SESSION['_course']['id']) && isset($_GET['course'])) {
-	$course_code = Security::remove_XSS($_GET['course']);
-} else {
-	$course_code = $_SESSION['_course']['id'];
-}
-
-
-if (isset($_GET['student_id'])) {
-	$student_id = intval($_GET['student_id']);
+ * This script must be included by lp_controller.php to get basic initialisation
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+
+require_once('learnpath.class.php');
+//require_once('scorm.class.php');
+require_once ('resourcelinker.inc.php');
+require_once ('../inc/lib/tracking.lib.php');
+require_once ('../inc/lib/course.lib.php');
+
+if(empty($_SESSION['_course']['id']) && isset($_GET['course'])) {
+	$course_code = Security::remove_XSS($_GET['course']);
+} else {
+	$course_code = $_SESSION['_course']['id'];
 }
-
+
+
+if (isset($_GET['student_id'])) {
+	$student_id = intval($_GET['student_id']);
+}
+
 //The two following variables have to be declared by the includer script
-//$lp_id = $_SESSION['oLP']->get_id();
-//$list = $_SESSION['oLP']->get_flat_ordered_items_list($lp_id);
-//$user_id = $_user['user_id'];
-//$stats_charset = $_SESSION['oLP']->encoding
-if(!isset($origin))
-	$origin = '';
-if($origin != 'tracking') {
-	if (!empty ($stats_charset)) {
-		$lp_charset = $stats_charset;
-	} else {
-		$lp_charset = api_get_setting('platform_charset');
-	}
-	$charset = $lp_charset;
-	//$w = $tablewidth -20;
-	$htmlHeadXtra[] = ''.'<style type="text/css" media="screen, projection">
-		/*<![CDATA[*/
-		@import "../css/public_admin/scorm.css";
-		/*]]>*/
-	</style>';
-	include_once ('../inc/reduced_header.inc.php');
-	echo '<body>';
-} else {
-    //Get learning path's encoding
-    $TBL_LP = Database :: get_course_table(TABLE_LP_MAIN);
-    $sql = "SELECT default_encoding FROM $TBL_LP " .
-                "WHERE id = '".(int)$_GET['lp_id']."'";
-    $res = Database::query($sql, __FILE__, __LINE__);
-    if (Database :: num_rows($res) > 0) {
-        $row = Database::fetch_array($res);
-        $lp_charset = $row['default_encoding'];
-    }
-}
-
-// The dokeos interface's encoding
-$dokeos_charset = api_get_setting('platform_charset');
-$output = '';
-//if display in fullscreen required
-if (!empty($_GET['fs']) && strcmp($_GET['fs'], 'true') == 0) {
-	$output .= '<table width="100%" align="center">';
-} else {
-	$output .= '<table width="100%">';
-}
-
-//check if the user asked for the "extend all" option
-$extend_all_link = '';
-$extend_all = 0;
-if ($origin == 'tracking') {
-	$url_suffix = '&course=' . Security::remove_XSS($_GET['course']) . '&student_id=' . $student_id . '&lp_id=' . Security::remove_XSS($_GET['lp_id']) . '&origin=' . Security::remove_XSS($_GET['origin']).$from_link;
-} else {
-	$url_suffix = '';
-}
-
-if (!empty ($_GET['extend_all'])) {
-	$extend_all_link = '<a href="' . api_get_self() . '?action=stats' . $url_suffix . '"><img src="../img/view_less_stats.gif" alt="fold_view" border="0" title="'.api_convert_encoding(get_lang('HideAllAttempts'), $lp_charset, $dokeos_charset).'"></a>';
-	$extend_all = 1;
-} else {
-	$extend_all_link = '<a href="' . api_get_self() . '?action=stats&extend_all=1' . $url_suffix . '"><img src="../img/view_more_stats.gif" alt="extend_view" border="0" title="'.api_convert_encoding(get_lang('ShowAllAttempts'), $lp_charset, $dokeos_charset).'"></a>';
-}
-
-if ($origin != 'tracking') {
-	$output .= "<tr><td><div class='title'>" . api_convert_encoding(get_lang('ScormMystatus'), $lp_charset, $dokeos_charset) . "</div></td></tr>";
-}
-$output .= "<tr><td>&nbsp;</td></tr>" . "<tr><td>" . "<table border='0' class='data_table'><tr>\n" . '<td width="16">' . $extend_all_link . '</td>' . '<td colspan="4" class="title"><div class="mystatusfirstrow">' . api_convert_encoding(get_lang('ScormLessonTitle'), $lp_charset, $dokeos_charset) . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . api_convert_encoding(get_lang('ScormStatus'), $lp_charset, $dokeos_charset) . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . api_convert_encoding(get_lang('ScormScore'), $lp_charset, $dokeos_charset) . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . api_convert_encoding(get_lang('ScormTime'), $lp_charset, $dokeos_charset) . "</div></td><td class='title'><div class='mystatusfirstrow'>" . api_convert_encoding(get_lang('Actions'), $lp_charset, $dokeos_charset) . "</div></td></tr>\n";
-//going through the items using the $items[] array instead of the database order ensures
-// we get them in the same order as in the imsmanifest file, which is rather random when using
-// the database table
-$TBL_LP_ITEM = Database :: get_course_table(TABLE_LP_ITEM);
-$TBL_LP_ITEM_VIEW = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
-$TBL_LP_VIEW = Database :: get_course_table(TABLE_LP_VIEW);
-$tbl_stats_exercices = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$tbl_stats_attempts= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-$tbl_quiz_questions= Database :: get_course_table(TABLE_QUIZ_QUESTION);
-$sql = "SELECT max(view_count) FROM $TBL_LP_VIEW " .
-"WHERE lp_id = $lp_id AND user_id = '" . $user_id . "'";
-$res = Database::query($sql, __FILE__, __LINE__);
-$view = '';
-$num = 0;
-if (Database :: num_rows($res) > 0) {
-	$myrow = Database :: fetch_array($res);
-	$view = $myrow[0];
-}
-
-$counter = 0;
-//error_log('New LP - Querying views for latest attempt: '.$sql,0);
-$total_score = 0;
-$total_max_score = 0;
-$total_time = 0;
-$h = api_convert_encoding(get_lang('h'), $lp_charset, $dokeos_charset);
-
-if (!empty($export_csv)) {
-	$csv_content[] = array (
-		api_convert_encoding(get_lang('ScormLessonTitle'), $lp_charset, $dokeos_charset),
-		api_convert_encoding(get_lang('ScormStatus'), $lp_charset, $dokeos_charset),
-		api_convert_encoding(get_lang('ScormScore'), $lp_charset, $dokeos_charset),
-		api_convert_encoding(get_lang('ScormTime'), $lp_charset, $dokeos_charset)
-	);
-}
-
-// get attempts of a exercise
-if (isset($_GET['lp_id']) && isset($_GET['my_lp_id'])) {
-	$clean_lp_item_id = Database::escape_string($_GET['my_lp_id']);
-	$clean_lp_id = Database::escape_string($_GET['lp_id']);
-	$clean_course_code = Database :: escape_string($course_code);
-	$sql_path = "SELECT path FROM $TBL_LP_ITEM WHERE id = '$clean_lp_item_id' AND lp_id = '$clean_lp_id'";
+//$lp_id = $_SESSION['oLP']->get_id();
+//$list = $_SESSION['oLP']->get_flat_ordered_items_list($lp_id);
+//$user_id = $_user['user_id'];
+//$stats_charset = $_SESSION['oLP']->encoding
+if(!isset($origin))
+	$origin = '';
+if($origin != 'tracking') {
+	if (!empty ($stats_charset)) {
+		$lp_charset = $stats_charset;
+	} else {
+		$lp_charset = api_get_setting('platform_charset');
+	}
+	$charset = $lp_charset;
+	//$w = $tablewidth -20;
+	$htmlHeadXtra[] = ''.'<style type="text/css" media="screen, projection">
+		/*<![CDATA[*/
+		@import "../css/public_admin/scorm.css";
+		/*]]>*/
+	</style>';
+	include_once ('../inc/reduced_header.inc.php');
+	echo '<body>';
+} else {
+    //Get learning path's encoding
+    $TBL_LP = Database :: get_course_table(TABLE_LP_MAIN);
+    $sql = "SELECT default_encoding FROM $TBL_LP " .
+                "WHERE id = '".(int)$_GET['lp_id']."'";
+    $res = Database::query($sql, __FILE__, __LINE__);
+    if (Database :: num_rows($res) > 0) {
+        $row = Database::fetch_array($res);
+        $lp_charset = $row['default_encoding'];
+    }
+}
+
+// The dokeos interface's encoding
+$dokeos_charset = api_get_setting('platform_charset');
+$output = '';
+//if display in fullscreen required
+if (!empty($_GET['fs']) && strcmp($_GET['fs'], 'true') == 0) {
+	$output .= '<table width="100%" align="center">';
+} else {
+	$output .= '<table width="100%">';
+}
+
+//check if the user asked for the "extend all" option
+$extend_all_link = '';
+$extend_all = 0;
+if ($origin == 'tracking') {
+	$url_suffix = '&course=' . Security::remove_XSS($_GET['course']) . '&student_id=' . $student_id . '&lp_id=' . Security::remove_XSS($_GET['lp_id']) . '&origin=' . Security::remove_XSS($_GET['origin']).$from_link;
+} else {
+	$url_suffix = '';
+}
+
+if (!empty ($_GET['extend_all'])) {
+	$extend_all_link = '<a href="' . api_get_self() . '?action=stats' . $url_suffix . '"><img src="../img/view_less_stats.gif" alt="fold_view" border="0" title="'.api_convert_encoding(get_lang('HideAllAttempts'), $lp_charset, $dokeos_charset).'"></a>';
+	$extend_all = 1;
+} else {
+	$extend_all_link = '<a href="' . api_get_self() . '?action=stats&extend_all=1' . $url_suffix . '"><img src="../img/view_more_stats.gif" alt="extend_view" border="0" title="'.api_convert_encoding(get_lang('ShowAllAttempts'), $lp_charset, $dokeos_charset).'"></a>';
+}
+
+if ($origin != 'tracking') {
+	$output .= "<tr><td><div class='title'>" . api_convert_encoding(get_lang('ScormMystatus'), $lp_charset, $dokeos_charset) . "</div></td></tr>";
+}
+$output .= "<tr><td>&nbsp;</td></tr>" . "<tr><td>" . "<table border='0' class='data_table'><tr>\n" . '<td width="16">' . $extend_all_link . '</td>' . '<td colspan="4" class="title"><div class="mystatusfirstrow">' . api_convert_encoding(get_lang('ScormLessonTitle'), $lp_charset, $dokeos_charset) . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . api_convert_encoding(get_lang('ScormStatus'), $lp_charset, $dokeos_charset) . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . api_convert_encoding(get_lang('ScormScore'), $lp_charset, $dokeos_charset) . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . api_convert_encoding(get_lang('ScormTime'), $lp_charset, $dokeos_charset) . "</div></td><td class='title'><div class='mystatusfirstrow'>" . api_convert_encoding(get_lang('Actions'), $lp_charset, $dokeos_charset) . "</div></td></tr>\n";
+//going through the items using the $items[] array instead of the database order ensures
+// we get them in the same order as in the imsmanifest file, which is rather random when using
+// the database table
+$TBL_LP_ITEM = Database :: get_course_table(TABLE_LP_ITEM);
+$TBL_LP_ITEM_VIEW = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+$TBL_LP_VIEW = Database :: get_course_table(TABLE_LP_VIEW);
+$tbl_stats_exercices = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$tbl_stats_attempts= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+$tbl_quiz_questions= Database :: get_course_table(TABLE_QUIZ_QUESTION);
+$sql = "SELECT max(view_count) FROM $TBL_LP_VIEW " .
+"WHERE lp_id = $lp_id AND user_id = '" . $user_id . "'";
+$res = Database::query($sql, __FILE__, __LINE__);
+$view = '';
+$num = 0;
+if (Database :: num_rows($res) > 0) {
+	$myrow = Database :: fetch_array($res);
+	$view = $myrow[0];
+}
+
+$counter = 0;
+//error_log('New LP - Querying views for latest attempt: '.$sql,0);
+$total_score = 0;
+$total_max_score = 0;
+$total_time = 0;
+$h = api_convert_encoding(get_lang('h'), $lp_charset, $dokeos_charset);
+
+if (!empty($export_csv)) {
+	$csv_content[] = array (
+		api_convert_encoding(get_lang('ScormLessonTitle'), $lp_charset, $dokeos_charset),
+		api_convert_encoding(get_lang('ScormStatus'), $lp_charset, $dokeos_charset),
+		api_convert_encoding(get_lang('ScormScore'), $lp_charset, $dokeos_charset),
+		api_convert_encoding(get_lang('ScormTime'), $lp_charset, $dokeos_charset)
+	);
+}
+
+// get attempts of a exercise
+if (isset($_GET['lp_id']) && isset($_GET['my_lp_id'])) {
+	$clean_lp_item_id = Database::escape_string($_GET['my_lp_id']);
+	$clean_lp_id = Database::escape_string($_GET['lp_id']);
+	$clean_course_code = Database :: escape_string($course_code);
+	$sql_path = "SELECT path FROM $TBL_LP_ITEM WHERE id = '$clean_lp_item_id' AND lp_id = '$clean_lp_id'";
 	$res_path = Database::query($sql_path,__FILE__,__LINE__);
-	$row_path = Database::fetch_array($res_path);
+	$row_path = Database::fetch_array($res_path);
 
 	if (Database::num_rows($res_path) > 0 ){
 		if ($origin != 'tracking') {
-			$sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '" AND exe_user_id="' . (int)api_get_user_id() . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '" AND status <> "incomplete" ORDER BY exe_date';
+			$sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '" AND exe_user_id="' . (int)api_get_user_id() . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '" AND status <> "incomplete" ORDER BY exe_date';
 		} else {
-			$sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '" AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '" AND status <> "incomplete" ORDER BY exe_date';
+			$sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '" AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '" AND status <> "incomplete" ORDER BY exe_date';
 		}
 	}
 
-}
-
-$TBL_QUIZ = Database :: get_course_table(TABLE_QUIZ_TEST);
-
-if (is_array($list) && count($list) > 0){
-	foreach ($list as $my_item_id) {
-		$extend_this = 0;
-		$qry_order = 'DESC';
-		if ((!empty ($_GET['extend_id']) and $_GET['extend_id'] == $my_item_id) OR $extend_all) {
-			$extend_this = 1;
-			$qry_order = 'ASC';
-		}
-		//prepare statement to go through each attempt
-
-		if (!empty ($view)) {
-			$sql = "SELECT iv.status as mystatus, v.view_count as mycount, " .
-			"iv.score as myscore, iv.total_time as mytime, i.id as myid, i.lp_id as mylpid, iv.lp_view_id as mylpviewid, " .
-			"i.title as mytitle, i.max_score as mymaxscore, " .
-			"iv.max_score as myviewmaxscore, " .
-			"i.item_type as item_type, iv.view_count as iv_view_count, " .
-			"iv.id as iv_id, path as path" .
-			" FROM $TBL_LP_ITEM as i, $TBL_LP_ITEM_VIEW as iv, $TBL_LP_VIEW as v" .
-			" WHERE i.id = iv.lp_item_id " .
-			" AND i.id = $my_item_id " .
-			" AND iv.lp_view_id = v.id " .
-			" AND i.lp_id = $lp_id " .
-			" AND v.user_id = " . $user_id . " " .
-			" AND v.view_count = $view " .
-			" ORDER BY iv.view_count $qry_order ";
-		} else {
-			$sql = "SELECT iv.status as mystatus, v.view_count as mycount, " .
-			"iv.score as myscore, iv.total_time as mytime, i.id as myid, i.lp_id as mylpid, iv.lp_view_id as mylpviewid, " .
-			"i.title as mytitle, i.max_score as mymaxscore, " .
-			"iv.max_score as myviewmaxscore, " .
-			"i.item_type as item_type, iv.view_count as iv_view_count, " .
-			"iv.id as iv_id, path as path " .
-			" FROM $TBL_LP_ITEM as i, $TBL_LP_ITEM_VIEW as iv, $TBL_LP_VIEW as v " .
-			" WHERE i.id = iv.lp_item_id " .
-			" AND i.id = $my_item_id " .
-			" AND iv.lp_view_id = v.id " .
-			" AND i.lp_id = $lp_id " .
-			" AND v.user_id = " . $user_id . " " .
-			" ORDER BY iv.view_count $qry_order ";
-		}
-
-		$result = Database::query($sql, __FILE__, __LINE__);
+}
+
+$TBL_QUIZ = Database :: get_course_table(TABLE_QUIZ_TEST);
+
+if (is_array($list) && count($list) > 0){
+	foreach ($list as $my_item_id) {
+		$extend_this = 0;
+		$qry_order = 'DESC';
+		if ((!empty ($_GET['extend_id']) and $_GET['extend_id'] == $my_item_id) OR $extend_all) {
+			$extend_this = 1;
+			$qry_order = 'ASC';
+		}
+		//prepare statement to go through each attempt
+
+		if (!empty ($view)) {
+			$sql = "SELECT iv.status as mystatus, v.view_count as mycount, " .
+			"iv.score as myscore, iv.total_time as mytime, i.id as myid, i.lp_id as mylpid, iv.lp_view_id as mylpviewid, " .
+			"i.title as mytitle, i.max_score as mymaxscore, " .
+			"iv.max_score as myviewmaxscore, " .
+			"i.item_type as item_type, iv.view_count as iv_view_count, " .
+			"iv.id as iv_id, path as path" .
+			" FROM $TBL_LP_ITEM as i, $TBL_LP_ITEM_VIEW as iv, $TBL_LP_VIEW as v" .
+			" WHERE i.id = iv.lp_item_id " .
+			" AND i.id = $my_item_id " .
+			" AND iv.lp_view_id = v.id " .
+			" AND i.lp_id = $lp_id " .
+			" AND v.user_id = " . $user_id . " " .
+			" AND v.view_count = $view " .
+			" ORDER BY iv.view_count $qry_order ";
+		} else {
+			$sql = "SELECT iv.status as mystatus, v.view_count as mycount, " .
+			"iv.score as myscore, iv.total_time as mytime, i.id as myid, i.lp_id as mylpid, iv.lp_view_id as mylpviewid, " .
+			"i.title as mytitle, i.max_score as mymaxscore, " .
+			"iv.max_score as myviewmaxscore, " .
+			"i.item_type as item_type, iv.view_count as iv_view_count, " .
+			"iv.id as iv_id, path as path " .
+			" FROM $TBL_LP_ITEM as i, $TBL_LP_ITEM_VIEW as iv, $TBL_LP_VIEW as v " .
+			" WHERE i.id = iv.lp_item_id " .
+			" AND i.id = $my_item_id " .
+			" AND iv.lp_view_id = v.id " .
+			" AND i.lp_id = $lp_id " .
+			" AND v.user_id = " . $user_id . " " .
+			" ORDER BY iv.view_count $qry_order ";
+		}
+
+		$result = Database::query($sql, __FILE__, __LINE__);
 		$num = Database :: num_rows($result);
-		$time_for_total = 'NaN';
+		$time_for_total = 'NaN';
 
-		if (($extend_this || $extend_all) && $num > 0) {
-			$row = Database :: fetch_array($result);
-			$result_disabled_ext_all = false;
-			if($row['item_type'] == 'quiz') {
-				//check results_disabled in quiz table
+		if (($extend_this || $extend_all) && $num > 0) {
+			$row = Database :: fetch_array($result);
+			$result_disabled_ext_all = false;
+			if($row['item_type'] == 'quiz') {
+				//check results_disabled in quiz table
 				$my_path = Database::escape_string($row['path']);
 
-				$sql = "SELECT results_disabled FROM $TBL_QUIZ WHERE id ='".(int)$my_path."'";
-				$res_result_disabled = Database::query($sql,__FILE__,__LINE__);
-				$row_result_disabled = Database::fetch_row($res_result_disabled);
-
-				if (Database::num_rows($res_result_disabled) > 0 && (int)$row_result_disabled[0]===1) {
-					$result_disabled_ext_all = true;
-				}
-			}
-
-			//echo '<br><pre>'; print_r($row); echo '</pre><br>';
-			//if there are several attempts, and the link to extend has been clicked, show each attempt...
-			if (($counter % 2) == 0) {
-				$oddclass = "row_odd";
-			} else {
-				$oddclass = "row_even";
-			}
-	        $extend_link='';
-			if (!empty($inter_num)) {
-				$extend_link = '<a href="' . api_get_self() . '?action=stats&fold_id=' . $my_item_id . $url_suffix . '"><img src="../img/visible.gif" alt="'.api_convert_encoding(get_lang('HideAttemptView'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('HideAttemptView'), $lp_charset, $dokeos_charset).'"  border="0"></a>' . "\n";
-			}
-			$title = $row['mytitle'];
-
-			if (empty ($title)) {
-				$title = rl_get_resource_name(api_get_course_id(), $lp_id, $row['myid']);
-			}
+				$sql = "SELECT results_disabled FROM $TBL_QUIZ WHERE id ='".(int)$my_path."'";
+				$res_result_disabled = Database::query($sql,__FILE__,__LINE__);
+				$row_result_disabled = Database::fetch_row($res_result_disabled);
+
+				if (Database::num_rows($res_result_disabled) > 0 && (int)$row_result_disabled[0]===1) {
+					$result_disabled_ext_all = true;
+				}
+			}
+
+			//echo '<br><pre>'; print_r($row); echo '</pre><br>';
+			//if there are several attempts, and the link to extend has been clicked, show each attempt...
+			if (($counter % 2) == 0) {
+				$oddclass = "row_odd";
+			} else {
+				$oddclass = "row_even";
+			}
+	        $extend_link='';
+			if (!empty($inter_num)) {
+				$extend_link = '<a href="' . api_get_self() . '?action=stats&fold_id=' . $my_item_id . $url_suffix . '"><img src="../img/visible.gif" alt="'.api_convert_encoding(get_lang('HideAttemptView'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('HideAttemptView'), $lp_charset, $dokeos_charset).'"  border="0"></a>' . "\n";
+			}
+			$title = $row['mytitle'];
+
+			if (empty ($title)) {
+				$title = rl_get_resource_name(api_get_course_id(), $lp_id, $row['myid']);
+			}
 
 			if ($row['item_type'] != 'dokeos_chapter') {
-				$correct_test_link = '-';
-				//api_convert_encoding($title, $lp_charset, $lp_charset)
-				$title = Security::remove_XSS($title);
-				$output .= "<tr class='$oddclass'>\n" . "<td>$extend_link</td>\n" . '<td colspan="4" class="content"><div class="mystatus">' . $title . "</div></td>\n" . '<td colspan="2" class="content"></td>' . "\n" . '<td colspan="2" class="content"></td>' . "\n" . '<td colspan="2" class="content"></td><td class="content"></td>' . "\n" . "</tr>\n";
-			}
-
-			$counter++;
-			do {
-				//check if there are interactions below
-				$extend_attempt_link = '';
-				$extend_this_attempt = 0;
-				if ((learnpath :: get_interactions_count_from_db($row['iv_id']) > 0 || learnpath :: get_objectives_count_from_db($row['iv_id']) > 0) && !$extend_all) {
-					if (!empty ($_GET['extend_attempt_id']) && $_GET['extend_attempt_id'] == $row['iv_id']) {
-						//the extend button for this attempt has been clicked
-						$extend_this_attempt = 1;
-						$extend_attempt_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&fold_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/visible.gif" alt="'.api_convert_encoding(get_lang('HideAttemptView'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('HideAttemptView'), $lp_charset, $dokeos_charset).'" border="0"></a>' . "\n";
-					} else { //same case if fold_attempt_id is set, so not implemented explicitly
-						//the extend button for this attempt has not been clicked
-						$extend_attempt_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/invisible.gif" alt="'.api_convert_encoding(get_lang('ExtendAttemptView'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('ExtendAttemptView'), $lp_charset, $dokeos_charset).'"  border="0"></a>' . "\n";
-					}
-				}
-
-				if (($counter % 2) == 0) {
-					$oddclass = "row_odd";
-				} else {
-					$oddclass = "row_even";
-				}
-				$lesson_status = $row['mystatus'];
-				$score = $row['myscore'];
-				$time_for_total = $row['mytime'];
-				$time = learnpathItem :: get_scorm_time('js', $row['mytime']);
-				$type;
-				$scoIdentifier = $row['myid'];
-				if ($score == 0) {
-					$maxscore = $row['mymaxscore'];
-				} else {
-					if ($row['item_type'] == 'sco') {
-
-						if (!empty ($row['myviewmaxscore']) && $row['myviewmaxscore'] > 0) {
-							$maxscore = $row['myviewmaxscore'];
-						}
-						elseif ($row['myviewmaxscore'] === '') {
-							$maxscore = 0;
-						} else {
-							$maxscore = $row['mymaxscore'];
-						}
-					}
+				$correct_test_link = '-';
+				//api_convert_encoding($title, $lp_charset, $lp_charset)
+				$title = Security::remove_XSS($title);
+				$output .= "<tr class='$oddclass'>\n" . "<td>$extend_link</td>\n" . '<td colspan="4" class="content"><div class="mystatus">' . $title . "</div></td>\n" . '<td colspan="2" class="content"></td>' . "\n" . '<td colspan="2" class="content"></td>' . "\n" . '<td colspan="2" class="content"></td><td class="content"></td>' . "\n" . "</tr>\n";
+			}
+
+			$counter++;
+			do {
+				//check if there are interactions below
+				$extend_attempt_link = '';
+				$extend_this_attempt = 0;
+				if ((learnpath :: get_interactions_count_from_db($row['iv_id']) > 0 || learnpath :: get_objectives_count_from_db($row['iv_id']) > 0) && !$extend_all) {
+					if (!empty ($_GET['extend_attempt_id']) && $_GET['extend_attempt_id'] == $row['iv_id']) {
+						//the extend button for this attempt has been clicked
+						$extend_this_attempt = 1;
+						$extend_attempt_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&fold_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/visible.gif" alt="'.api_convert_encoding(get_lang('HideAttemptView'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('HideAttemptView'), $lp_charset, $dokeos_charset).'" border="0"></a>' . "\n";
+					} else { //same case if fold_attempt_id is set, so not implemented explicitly
+						//the extend button for this attempt has not been clicked
+						$extend_attempt_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/invisible.gif" alt="'.api_convert_encoding(get_lang('ExtendAttemptView'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('ExtendAttemptView'), $lp_charset, $dokeos_charset).'"  border="0"></a>' . "\n";
+					}
+				}
+
+				if (($counter % 2) == 0) {
+					$oddclass = "row_odd";
+				} else {
+					$oddclass = "row_even";
+				}
+				$lesson_status = $row['mystatus'];
+				$score = $row['myscore'];
+				$time_for_total = $row['mytime'];
+				$time = learnpathItem :: get_scorm_time('js', $row['mytime']);
+				$type;
+				$scoIdentifier = $row['myid'];
+				if ($score == 0) {
+					$maxscore = $row['mymaxscore'];
+				} else {
+					if ($row['item_type'] == 'sco') {
+
+						if (!empty ($row['myviewmaxscore']) && $row['myviewmaxscore'] > 0) {
+							$maxscore = $row['myviewmaxscore'];
+						}
+						elseif ($row['myviewmaxscore'] === '') {
+							$maxscore = 0;
+						} else {
+							$maxscore = $row['mymaxscore'];
+						}
+					}
 					else
-					{
-						$maxscore = $row['mymaxscore'];
-					}
-				}
-				//Remove "NaN" if any (@todo: locate the source of these NaN)
-				$time = str_replace('NaN', '00' . $h . '00\'00"', $time);
-				if (($lesson_status == 'completed') or ($lesson_status == 'passed')) {
-					$color = 'green';
-				} else {
-					$color = 'black';
-				}
-				$mylanglist = array (
-					'completed' => 'ScormCompstatus',
-					'incomplete' => 'ScormIncomplete',
-					'failed' => 'ScormFailed',
-					'passed' => 'ScormPassed',
-					'browsed' => 'ScormBrowsed',
-					'not attempted' => 'ScormNotAttempted',
-
-				);
+					{
+						$maxscore = $row['mymaxscore'];
+					}
+				}
+				//Remove "NaN" if any (@todo: locate the source of these NaN)
+				$time = str_replace('NaN', '00' . $h . '00\'00"', $time);
+				if (($lesson_status == 'completed') or ($lesson_status == 'passed')) {
+					$color = 'green';
+				} else {
+					$color = 'black';
+				}
+				$mylanglist = array (
+					'completed' => 'ScormCompstatus',
+					'incomplete' => 'ScormIncomplete',
+					'failed' => 'ScormFailed',
+					'passed' => 'ScormPassed',
+					'browsed' => 'ScormBrowsed',
+					'not attempted' => 'ScormNotAttempted',
+
+				);
 
 				$my_lesson_status = api_convert_encoding(get_lang($mylanglist[$lesson_status]), $lp_charset, $dokeos_charset);
 
-				if ($row['item_type'] != 'dokeos_chapter') {
-					if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
-						$view_score = '/';
-					} else {
-						$view_score = ($score == 0 ? '/' : ($maxscore === 0 ? $score : $score . '/' . float_format($maxscore, 1)));
-					}
-					$output .= "<tr class='$oddclass'>\n" . "<td></td>\n" . "<td>$extend_attempt_link</td>\n" . '<td colspan="3">' . api_convert_encoding(get_lang('Attempt'), $lp_charset, $dokeos_charset) . ' ' . $row['iv_view_count'] . "</td>\n"
-					//."<td><font color='$color'><div class='mystatus'>".api_htmlentities($array_status[$lesson_status],ENT_QUOTES,$lp_charset)."</div></font></td>\n"
-					 . '<td colspan="2"><font color="' . $color . '"><div class="mystatus">' . $my_lesson_status . "</div></font></td>\n" . '<td colspan="2"><div class="mystatus" align="center">' . $view_score . "</div></td>\n" . '<td colspan="2"><div class="mystatus">'.$time.'</div></td><td></td></tr>';
-
-					if (!empty($export_csv)) {
+				if ($row['item_type'] != 'dokeos_chapter') {
+					if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
+						$view_score = '/';
+					} else {
+						$view_score = ($score == 0 ? '/' : ($maxscore === 0 ? $score : $score . '/' . float_format($maxscore, 1)));
+					}
+					$output .= "<tr class='$oddclass'>\n" . "<td></td>\n" . "<td>$extend_attempt_link</td>\n" . '<td colspan="3">' . api_convert_encoding(get_lang('Attempt'), $lp_charset, $dokeos_charset) . ' ' . $row['iv_view_count'] . "</td>\n"
+					//."<td><font color='$color'><div class='mystatus'>".api_htmlentities($array_status[$lesson_status],ENT_QUOTES,$lp_charset)."</div></font></td>\n"
+					 . '<td colspan="2"><font color="' . $color . '"><div class="mystatus">' . $my_lesson_status . "</div></font></td>\n" . '<td colspan="2"><div class="mystatus" align="center">' . $view_score . "</div></td>\n" . '<td colspan="2"><div class="mystatus">'.$time.'</div></td><td></td></tr>';
+
+					if (!empty($export_csv)) {
 						$temp = array ();
 						$temp[] = $title = Security::remove_XSS($title);
-						$temp[] = Security::remove_XSS($my_lesson_status);
+						$temp[] = Security::remove_XSS($my_lesson_status);
 
-						if ($row['item_type'] == 'quiz') {
+						if ($row['item_type'] == 'quiz') {
 
-							if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
-								$temp[] =  '/';
-							} else {
-								$temp[] = ($score == 0 ? '0/'.$maxscore : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
-							}
+							if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
+								$temp[] =  '/';
+							} else {
+								$temp[] = ($score == 0 ? '0/'.$maxscore : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
+							}
 
-						} else {
-							$temp[] = ($score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
-						}
+						} else {
+							$temp[] = ($score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
+						}
 
-						$temp[] = $time;
-						$csv_content[] = $temp;
+						$temp[] = $time;
+						$csv_content[] = $temp;
 					}
-				}
-
-				$counter++;
-
-				if ($extend_this_attempt OR $extend_all) {
-					$list1 = learnpath :: get_iv_interactions_array($row['iv_id']);
-					foreach ($list1 as $id => $interaction) {
-						if (($counter % 2) == 0) {
-							$oddclass = "row_odd";
-						} else {
-							$oddclass = "row_even";
-						}
-						$student_response=urldecode($interaction['student_response']);//code added by isaac flores
-						$content_student_response=array();
-						$content_student_response=explode('__|',$student_response);
-
-						if (count($content_student_response)>0) {
-							if (count($content_student_response)>=3) {
-								$new_content_student_response=array_pop($content_student_response);//Pop the element off the end of array
-							}
-							$student_response=implode(',',$content_student_response);
-						}
-						$output .= "<tr class='$oddclass'>\n" . '<td></td>' . "\n" . '<td></td>' . "\n" . '<td>&nbsp;</td>' . "\n" . '<td>' . $interaction['order_id'] . '</td>' . "\n" . '<td>' . $interaction['id'] . '</td>' . "\n"
-						//."<td><font color='$color'><div class='mystatus'>".api_convert_encoding($array_status[$lesson_status],$lp_charset,$lp_charset)."</div></font></td>\n"
-						 . '<td colspan="2">' . $interaction['type'] . "</td>\n"
-						//.'<td>'.$interaction['correct_responses']."</td>\n"
-						 . '<td>' . $student_response . "</td>\n" . '<td>' . $interaction['result'] . "</td>\n" . '<td>' . $interaction['latency'] . "</td>\n" . '<td>' . $interaction['time'] . "</td>\n<td></td>\n</tr>\n";
-						$counter++;
-					}
-					$list2 = learnpath :: get_iv_objectives_array($row['iv_id']);
-					foreach ($list2 as $id => $interaction) {
-						if (($counter % 2) == 0) {
-							$oddclass = "row_odd";
-						} else {
-							$oddclass = "row_even";
-						}
-						$output .= "<tr class='$oddclass'>\n" . '<td></td>' . "\n" . '<td></td>' . "\n" . '<td>&nbsp;</td>' . "\n" . '<td>' . $interaction['order_id'] . '</td>' . "\n" . '<td colspan="2">' . $interaction['objective_id'] . '</td>' . "\n" .
-						'<td colspan="2">' . $interaction['status'] . "</td>\n" .
-						'<td>' . $interaction['score_raw'] . "</td>\n" . '<td>' . $interaction['score_max'] . "</td>\n" . '<td>' . $interaction['score_min'] . "</td>\n<td></td>\n</tr>\n";
-						$counter++;
-					}
-				}
+				}
+
+				$counter++;
+
+				if ($extend_this_attempt OR $extend_all) {
+					$list1 = learnpath :: get_iv_interactions_array($row['iv_id']);
+					foreach ($list1 as $id => $interaction) {
+						if (($counter % 2) == 0) {
+							$oddclass = "row_odd";
+						} else {
+							$oddclass = "row_even";
+						}
+						$student_response=urldecode($interaction['student_response']);//code added by isaac flores
+						$content_student_response=array();
+						$content_student_response=explode('__|',$student_response);
+
+						if (count($content_student_response)>0) {
+							if (count($content_student_response)>=3) {
+								$new_content_student_response=array_pop($content_student_response);//Pop the element off the end of array
+							}
+							$student_response=implode(',',$content_student_response);
+						}
+						$output .= "<tr class='$oddclass'>\n" . '<td></td>' . "\n" . '<td></td>' . "\n" . '<td>&nbsp;</td>' . "\n" . '<td>' . $interaction['order_id'] . '</td>' . "\n" . '<td>' . $interaction['id'] . '</td>' . "\n"
+						//."<td><font color='$color'><div class='mystatus'>".api_convert_encoding($array_status[$lesson_status],$lp_charset,$lp_charset)."</div></font></td>\n"
+						 . '<td colspan="2">' . $interaction['type'] . "</td>\n"
+						//.'<td>'.$interaction['correct_responses']."</td>\n"
+						 . '<td>' . $student_response . "</td>\n" . '<td>' . $interaction['result'] . "</td>\n" . '<td>' . $interaction['latency'] . "</td>\n" . '<td>' . $interaction['time'] . "</td>\n<td></td>\n</tr>\n";
+						$counter++;
+					}
+					$list2 = learnpath :: get_iv_objectives_array($row['iv_id']);
+					foreach ($list2 as $id => $interaction) {
+						if (($counter % 2) == 0) {
+							$oddclass = "row_odd";
+						} else {
+							$oddclass = "row_even";
+						}
+						$output .= "<tr class='$oddclass'>\n" . '<td></td>' . "\n" . '<td></td>' . "\n" . '<td>&nbsp;</td>' . "\n" . '<td>' . $interaction['order_id'] . '</td>' . "\n" . '<td colspan="2">' . $interaction['objective_id'] . '</td>' . "\n" .
+						'<td colspan="2">' . $interaction['status'] . "</td>\n" .
+						'<td>' . $interaction['score_raw'] . "</td>\n" . '<td>' . $interaction['score_max'] . "</td>\n" . '<td>' . $interaction['score_min'] . "</td>\n<td></td>\n</tr>\n";
+						$counter++;
+					}
+				}
 			} while ($row = Database :: fetch_array($result));
-		}
-		elseif ($num > 0) {
-			$row = Database :: fetch_array($result);
-			$my_id = $row['myid'];
-			$my_lp_id = $row['mylpid'];
-			$my_lp_view_id = $row['mylpviewid'];
+		}
+		elseif ($num > 0) {
+			$row = Database :: fetch_array($result);
+			$my_id = $row['myid'];
+			$my_lp_id = $row['mylpid'];
+			$my_lp_view_id = $row['mylpviewid'];
 			$my_path = $row['path'];
 
-			$result_disabled_ext_all = false;
+			$result_disabled_ext_all = false;
 
-			if($row['item_type'] == 'quiz') {
-				//check results_disabled in quiz table
+			if($row['item_type'] == 'quiz') {
+				//check results_disabled in quiz table
 				$my_path = Database::escape_string($my_path);
 
-				$sql = "SELECT results_disabled FROM $TBL_QUIZ WHERE id ='".(int)$my_path."'";
-				$res_result_disabled = Database::query($sql,__FILE__,__LINE__);
-				$row_result_disabled = Database::fetch_row($res_result_disabled);
+				$sql = "SELECT results_disabled FROM $TBL_QUIZ WHERE id ='".(int)$my_path."'";
+				$res_result_disabled = Database::query($sql,__FILE__,__LINE__);
+				$row_result_disabled = Database::fetch_row($res_result_disabled);
+
+				if (Database::num_rows($res_result_disabled) > 0 && (int)$row_result_disabled[0]===1) {
+					$result_disabled_ext_all = true;
+				}
+			}
 
-				if (Database::num_rows($res_result_disabled) > 0 && (int)$row_result_disabled[0]===1) {
-					$result_disabled_ext_all = true;
-				}
+			//check if there are interactions below
+			$extend_attempt_link = '';
+			$extend_this_attempt = 0;
+			$inter_num = learnpath :: get_interactions_count_from_db($row['iv_id']);
+			$objec_num = learnpath :: get_objectives_count_from_db($row['iv_id']);
+			if (($inter_num > 0 || $objec_num > 0) && !$extend_all) {
+				if (!empty ($_GET['extend_attempt_id']) && $_GET['extend_attempt_id'] == $row['iv_id']) {
+					//the extend button for this attempt has been clicked
+					$extend_this_attempt = 1;
+					$extend_attempt_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&fold_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/visible.gif" alt="'.api_convert_encoding(get_lang('HideAttemptView'),$lp_charset,$charset).'" title="'.api_convert_encoding(get_lang('HideAttemptView'),$lp_charset,$charset).'" border="0"></a>' . "\n";
+				} else { //same case if fold_attempt_id is set, so not implemented explicitly
+					//the extend button for this attempt has not been clicked
+					$extend_attempt_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/invisible.gif" alt="'.api_convert_encoding(get_lang('ExtendAttemptView'),$lp_charset,$charset).'" title="'.api_convert_encoding(get_lang('ExtendAttemptView'),$lp_charset,$charset).'" border="0"></a>' . "\n";
+				}
 			}
 
-			//check if there are interactions below
-			$extend_attempt_link = '';
-			$extend_this_attempt = 0;
-			$inter_num = learnpath :: get_interactions_count_from_db($row['iv_id']);
-			$objec_num = learnpath :: get_objectives_count_from_db($row['iv_id']);
-			if (($inter_num > 0 || $objec_num > 0) && !$extend_all) {
-				if (!empty ($_GET['extend_attempt_id']) && $_GET['extend_attempt_id'] == $row['iv_id']) {
-					//the extend button for this attempt has been clicked
-					$extend_this_attempt = 1;
-					$extend_attempt_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&fold_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/visible.gif" alt="'.api_convert_encoding(get_lang('HideAttemptView'),$lp_charset,$charset).'" title="'.api_convert_encoding(get_lang('HideAttemptView'),$lp_charset,$charset).'" border="0"></a>' . "\n";
-				} else { //same case if fold_attempt_id is set, so not implemented explicitly
-					//the extend button for this attempt has not been clicked
-					$extend_attempt_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/invisible.gif" alt="'.api_convert_encoding(get_lang('ExtendAttemptView'),$lp_charset,$charset).'" title="'.api_convert_encoding(get_lang('ExtendAttemptView'),$lp_charset,$charset).'" border="0"></a>' . "\n";
-				}
-			}
-
-			if (($counter % 2) == 0) {
-				$oddclass = "row_odd";
-			} else {
-				$oddclass = "row_even";
-			}
-			//$extend_link = '<img src="../img/invisible.gif" alt="extend_disabled">';
-			$extend_link = '';
-			if ($inter_num > 1) {
-				$extend_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/invisible.gif" alt="'.api_convert_encoding(get_lang('ExtendAttemptView'),$lp_charset,$charset).'" title="'.api_convert_encoding(get_lang('ExtendAttemptView'),$lp_charset,$charset).'"  border="0"></a>';
-			}
-			if (($counter % 2) == 0) {
-				$oddclass = "row_odd";
-			} else {
-				$oddclass = "row_even";
-			}
-			$lesson_status = $row['mystatus'];
-			$score = $row['myscore'];
-			$subtotal_time = $row['mytime'];
-			//if($row['mytime']==0){
-			while ($tmp_row = Database :: fetch_array($result)) {
-				$subtotal_time += $tmp_row['mytime'];
-			}
-			//}
-			//$time_for_total = $subtotal_time;
-			//$time = learnpathItem :: get_scorm_time('js', $subtotal_time);
-			$scoIdentifier = $row['myid'];
-			$title = $row['mytitle'];
-
-			// selecting the exe_id from stats attempts tables in order to look the max score value
-			if ($origin != 'tracking') {
-				$sql_last_attempt = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $row['path'] . '" AND exe_user_id="' . api_get_user_id() . '" AND orig_lp_id = "'.$lp_id.'" AND orig_lp_item_id = "'.$row['myid'].'" AND exe_cours_id="' . $course_code . '" AND status <> "incomplete" ORDER BY exe_date DESC limit 1';
-			} else {
-				$sql_last_attempt = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $row['path'] . '" AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.$lp_id.'" AND orig_lp_item_id = "'.$row['myid'].'" AND exe_cours_id="' . $course_code . '" AND status <> "incomplete" ORDER BY exe_date DESC limit 1';
-			}
-
-			$resultLastAttempt = Database::query($sql_last_attempt, __FILE__, __LINE__);
-			$num = Database :: num_rows($resultLastAttempt);
-			if ($num > 0) {
-				while ($rowLA = Database :: fetch_array($resultLastAttempt)) {
-					$id_last_attempt = $rowLA['exe_id'];
-				}
-			}
-
-			if ($score == 0)
-			{
-				$maxscore = $row['mymaxscore'];
-			}
+			if (($counter % 2) == 0) {
+				$oddclass = "row_odd";
+			} else {
+				$oddclass = "row_even";
+			}
+			//$extend_link = '<img src="../img/invisible.gif" alt="extend_disabled">';
+			$extend_link = '';
+			if ($inter_num > 1) {
+				$extend_link = '<a href="' . api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix . '"><img src="../img/invisible.gif" alt="'.api_convert_encoding(get_lang('ExtendAttemptView'),$lp_charset,$charset).'" title="'.api_convert_encoding(get_lang('ExtendAttemptView'),$lp_charset,$charset).'"  border="0"></a>';
+			}
+			if (($counter % 2) == 0) {
+				$oddclass = "row_odd";
+			} else {
+				$oddclass = "row_even";
+			}
+			$lesson_status = $row['mystatus'];
+			$score = $row['myscore'];
+			$subtotal_time = $row['mytime'];
+			//if($row['mytime']==0){
+			while ($tmp_row = Database :: fetch_array($result)) {
+				$subtotal_time += $tmp_row['mytime'];
+			}
+			//}
+			//$time_for_total = $subtotal_time;
+			//$time = learnpathItem :: get_scorm_time('js', $subtotal_time);
+			$scoIdentifier = $row['myid'];
+			$title = $row['mytitle'];
+
+			// selecting the exe_id from stats attempts tables in order to look the max score value
+			if ($origin != 'tracking') {
+				$sql_last_attempt = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $row['path'] . '" AND exe_user_id="' . api_get_user_id() . '" AND orig_lp_id = "'.$lp_id.'" AND orig_lp_item_id = "'.$row['myid'].'" AND exe_cours_id="' . $course_code . '" AND status <> "incomplete" ORDER BY exe_date DESC limit 1';
+			} else {
+				$sql_last_attempt = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $row['path'] . '" AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.$lp_id.'" AND orig_lp_item_id = "'.$row['myid'].'" AND exe_cours_id="' . $course_code . '" AND status <> "incomplete" ORDER BY exe_date DESC limit 1';
+			}
+
+			$resultLastAttempt = Database::query($sql_last_attempt, __FILE__, __LINE__);
+			$num = Database :: num_rows($resultLastAttempt);
+			if ($num > 0) {
+				while ($rowLA = Database :: fetch_array($resultLastAttempt)) {
+					$id_last_attempt = $rowLA['exe_id'];
+				}
+			}
+
+			if ($score == 0)
+			{
+				$maxscore = $row['mymaxscore'];
+			}
 			else
-			{
+			{
 				if ($row['item_type'] == 'sco')
-				{
-					if (!empty ($row['myviewmaxscore']) and $row['myviewmaxscore'] > 0) {
-						$maxscore = $row['myviewmaxscore'];
-					}
-					elseif ($row['myviewmaxscore'] === '') {
-						$maxscore = 0;
-					} else {
-						$maxscore = $row['mymaxscore'];
-					}
+				{
+					if (!empty ($row['myviewmaxscore']) and $row['myviewmaxscore'] > 0) {
+						$maxscore = $row['myviewmaxscore'];
+					}
+					elseif ($row['myviewmaxscore'] === '') {
+						$maxscore = 0;
+					} else {
+						$maxscore = $row['mymaxscore'];
+					}
 				}
-				else
-				{
+				else
+				{
 					if ($row['item_type'] == 'quiz')
-					{
+					{
 						// get score and total time from last attempt of a exercise en lp
-						$sql = "SELECT score FROM $TBL_LP_ITEM_VIEW WHERE lp_item_id = '".(int)$my_id."' and lp_view_id = '".(int)$my_lp_view_id."'
-								ORDER BY view_count DESC limit 1";
-						$res_score = Database::query($sql,__FILE__,__LINE__);
-						$row_score = Database::fetch_array($res_score);
+						$sql = "SELECT score FROM $TBL_LP_ITEM_VIEW WHERE lp_item_id = '".(int)$my_id."' and lp_view_id = '".(int)$my_lp_view_id."'
+								ORDER BY view_count DESC limit 1";
+						$res_score = Database::query($sql,__FILE__,__LINE__);
+						$row_score = Database::fetch_array($res_score);
 
-						$sql = "SELECT SUM(total_time) as total_time FROM $TBL_LP_ITEM_VIEW WHERE lp_item_id = '".(int)$my_id."' and lp_view_id = '".(int)$my_lp_view_id."'";
-						$res_time = Database::query($sql,__FILE__,__LINE__);
-						$row_time = Database::fetch_array($res_time);
+						$sql = "SELECT SUM(total_time) as total_time FROM $TBL_LP_ITEM_VIEW WHERE lp_item_id = '".(int)$my_id."' and lp_view_id = '".(int)$my_lp_view_id."'";
+						$res_time = Database::query($sql,__FILE__,__LINE__);
+						$row_time = Database::fetch_array($res_time);
 
 						if (Database::num_rows($res_score) > 0 && Database::num_rows($res_time) > 0) {
-							$score = (float)$row_score['score'];
+							$score = (float)$row_score['score'];
 							$subtotal_time = (int)$row_time['total_time'];
-						} else {
-							$score = 0;
-							$subtotal_time =  0;
-						}
+						} else {
+							$score = 0;
+							$subtotal_time =  0;
+						}
 
 						//$time = learnpathItem :: get_scorm_time('js', $subtotal_time);
-						// selecting the max score from an attempt
-						$sql = "SELECT SUM(t.ponderation) as maxscore from ( SELECT distinct question_id, marks,ponderation FROM $tbl_stats_attempts as at " .
-							  "INNER JOIN  $tbl_quiz_questions as q  on(q.id = at.question_id) where exe_id ='$id_last_attempt' ) as t";
+						// selecting the max score from an attempt
+						$sql = "SELECT SUM(t.ponderation) as maxscore from ( SELECT distinct question_id, marks,ponderation FROM $tbl_stats_attempts as at " .
+							  "INNER JOIN  $tbl_quiz_questions as q  on(q.id = at.question_id) where exe_id ='$id_last_attempt' ) as t";
 
-						$result = Database::query($sql, __FILE__, __LINE__);
+						$result = Database::query($sql, __FILE__, __LINE__);
 						$row_max_score = Database :: fetch_array($result);
-						$maxscore = $row_max_score['maxscore'];
-					}
-					else
-					{
-						$maxscore = $row['mymaxscore'];
-					}
-				}
-			}
-			$time_for_total = $subtotal_time;
+						$maxscore = $row_max_score['maxscore'];
+					}
+					else
+					{
+						$maxscore = $row['mymaxscore'];
+					}
+				}
+			}
+			$time_for_total = $subtotal_time;
 			$time = learnpathItem :: get_scorm_time('js', $subtotal_time);
-			if (empty ($title)) {
-				$title = rl_get_resource_name(api_get_course_id(), $lp_id, $row['myid']);
-			}
-			//Remove "NaN" if any (@todo: locate the source of these NaN)
-			//$time = str_replace('NaN', '00'.$h.'00\'00"', $time);
-
-			if (($lesson_status == 'completed') or ($lesson_status == 'passed')) {
-				$color = 'green';
-			} else {
-				$color = 'black';
-			}
-			$mylanglist = array (
-				'completed' => 'ScormCompstatus',
-				'incomplete' => 'ScormIncomplete',
-				'failed' => 'ScormFailed',
-				'passed' => 'ScormPassed',
-				'browsed' => 'ScormBrowsed',
-				'not attempted' => 'ScormNotAttempted',
-
-			);
-			$my_lesson_status = api_convert_encoding(get_lang($mylanglist[$lesson_status]), $lp_charset, $dokeos_charset);
-
-			if ($row['item_type'] != 'dokeos_chapter') {
-				if ($row['item_type'] == 'quiz') {
-					$correct_test_link = '';
-					$my_url_suffix ='';
-					if ($origin != 'tracking' && $origin != 'tracking_course') {
-						$my_url_suffix = '&course=' . api_get_course_id() . '&student_id=' . api_get_user_id() . '&lp_id=' . Security::remove_XSS($row['mylpid']);
-						$sql_last_attempt = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $row['path'] . '" AND exe_user_id="' . api_get_user_id() . '" AND orig_lp_id = "'.$lp_id.'" AND orig_lp_item_id = "'.$row['myid'].'" AND exe_cours_id="' . $course_code . '" AND status <> "incomplete" ORDER BY exe_date DESC ';
-					} else {
-						$my_url_suffix = '&course=' . Security::remove_XSS($_GET['course']) . '&student_id=' . $student_id . '&lp_id=' . Security::remove_XSS($row['mylpid']).'&origin=' . Security::remove_XSS($_GET['origin'].$from_link);
-						$sql_last_attempt = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $row['path'] . '" AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.$lp_id.'" AND orig_lp_item_id = "'.$row['myid'].'" AND exe_cours_id="' . Database :: escape_string($_GET['course']) . '" AND status <> "incomplete"  ORDER BY exe_date DESC ';
-					}
-
-					$resultLastAttempt = Database::query($sql_last_attempt, __FILE__, __LINE__);
-					$num = Database :: num_rows($resultLastAttempt);
+			if (empty ($title)) {
+				$title = rl_get_resource_name(api_get_course_id(), $lp_id, $row['myid']);
+			}
+			//Remove "NaN" if any (@todo: locate the source of these NaN)
+			//$time = str_replace('NaN', '00'.$h.'00\'00"', $time);
+
+			if (($lesson_status == 'completed') or ($lesson_status == 'passed')) {
+				$color = 'green';
+			} else {
+				$color = 'black';
+			}
+			$mylanglist = array (
+				'completed' => 'ScormCompstatus',
+				'incomplete' => 'ScormIncomplete',
+				'failed' => 'ScormFailed',
+				'passed' => 'ScormPassed',
+				'browsed' => 'ScormBrowsed',
+				'not attempted' => 'ScormNotAttempted',
+
+			);
+			$my_lesson_status = api_convert_encoding(get_lang($mylanglist[$lesson_status]), $lp_charset, $dokeos_charset);
+
+			if ($row['item_type'] != 'dokeos_chapter') {
+				if ($row['item_type'] == 'quiz') {
+					$correct_test_link = '';
+					$my_url_suffix ='';
+					if ($origin != 'tracking' && $origin != 'tracking_course') {
+						$my_url_suffix = '&course=' . api_get_course_id() . '&student_id=' . api_get_user_id() . '&lp_id=' . Security::remove_XSS($row['mylpid']);
+						$sql_last_attempt = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $row['path'] . '" AND exe_user_id="' . api_get_user_id() . '" AND orig_lp_id = "'.$lp_id.'" AND orig_lp_item_id = "'.$row['myid'].'" AND exe_cours_id="' . $course_code . '" AND status <> "incomplete" ORDER BY exe_date DESC ';
+					} else {
+						$my_url_suffix = '&course=' . Security::remove_XSS($_GET['course']) . '&student_id=' . $student_id . '&lp_id=' . Security::remove_XSS($row['mylpid']).'&origin=' . Security::remove_XSS($_GET['origin'].$from_link);
+						$sql_last_attempt = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . $row['path'] . '" AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.$lp_id.'" AND orig_lp_item_id = "'.$row['myid'].'" AND exe_cours_id="' . Database :: escape_string($_GET['course']) . '" AND status <> "incomplete"  ORDER BY exe_date DESC ';
+					}
+
+					$resultLastAttempt = Database::query($sql_last_attempt, __FILE__, __LINE__);
+					$num = Database :: num_rows($resultLastAttempt);
 					if ($num > 0) {
 						if (isset($_GET['extend_attempt']) && $_GET['extend_attempt'] == 1 && (isset($_GET['lp_id']) && $_GET['lp_id'] == $my_lp_id) && (isset($_GET['my_lp_id']) && $_GET['my_lp_id'] == $my_id)  ) {
-							$correct_test_link = '<a href="' . api_get_self() . '?action=stats' . $my_url_suffix . '&my_ext_lp_id='.$my_id.'"><img src="../img/view_less_stats.gif" alt="fold_view" border="0" title="'.api_convert_encoding(get_lang('HideAllAttempts'),$lp_charset,$charset).'"></a>';
-							$extend_attempt = 1;
+							$correct_test_link = '<a href="' . api_get_self() . '?action=stats' . $my_url_suffix . '&my_ext_lp_id='.$my_id.'"><img src="../img/view_less_stats.gif" alt="fold_view" border="0" title="'.api_convert_encoding(get_lang('HideAllAttempts'),$lp_charset,$charset).'"></a>';
+							$extend_attempt = 1;
 						} else {
-							$correct_test_link = '<a href="' . api_get_self() . '?action=stats&extend_attempt=1'.$my_url_suffix.'&my_lp_id='.$my_id.'"><img src="../img/view_more_stats.gif" alt="extend_view" border="0" title="'.api_convert_encoding(get_lang('ShowAllAttemptsByExercise'),$lp_charset,$charset).'"></a>';
-						}
-					} else {
-						$correct_test_link = '-';
-					}
-				} else {
-					$correct_test_link = '-';
-				}
-
-				//."<td><font color='$color'><div class='mystatus'>".api_htmlentities($array_status[$lesson_status],ENT_QUOTES,$lp_charset)."</div></font></td>\n"
-				$title = Security::remove_XSS($title);
+							$correct_test_link = '<a href="' . api_get_self() . '?action=stats&extend_attempt=1'.$my_url_suffix.'&my_lp_id='.$my_id.'"><img src="../img/view_more_stats.gif" alt="extend_view" border="0" title="'.api_convert_encoding(get_lang('ShowAllAttemptsByExercise'),$lp_charset,$charset).'"></a>';
+						}
+					} else {
+						$correct_test_link = '-';
+					}
+				} else {
+					$correct_test_link = '-';
+				}
+
+				//."<td><font color='$color'><div class='mystatus'>".api_htmlentities($array_status[$lesson_status],ENT_QUOTES,$lp_charset)."</div></font></td>\n"
+				$title = Security::remove_XSS($title);
 				if ( (isset($_GET['lp_id']) && $_GET['lp_id'] == $my_lp_id ) && (isset($_GET['my_lp_id']) && $_GET['my_lp_id'] == $my_id)) {
 					$output .= "<tr class='$oddclass' >\n" . "<td>$extend_link</td>\n" . '<td colspan="4"><div class="mystatus">' .$title. '</div></td>' . "\n";
-					$output .= '<td colspan="2">&nbsp;</td><td colspan="2">&nbsp;</td><td colspan="2">&nbsp;</td><td>'.$correct_test_link.'</td></tr>';
+					$output .= '<td colspan="2">&nbsp;</td><td colspan="2">&nbsp;</td><td colspan="2">&nbsp;</td><td>'.$correct_test_link.'</td></tr>';
 					$output .= "</tr>\n";
-				} else {
-					if ( (isset($_GET['lp_id']) && $_GET['lp_id'] == $my_lp_id ) && (isset($_GET['my_ext_lp_id']) && $_GET['my_ext_lp_id'] == $my_id)) {
+				} else {
+					if ( (isset($_GET['lp_id']) && $_GET['lp_id'] == $my_lp_id ) && (isset($_GET['my_ext_lp_id']) && $_GET['my_ext_lp_id'] == $my_id)) {
 						$output .= "<tr class='$oddclass' >\n";
-					} else {
+					} else {
 						$output .= "<tr class='$oddclass'>\n";
-					}
+					}
 					$output .= "<td>$extend_link</td>\n" . '<td colspan="4"><div class="mystatus">' .$title. '</div></td>' . "\n";
 					$output .= '<td colspan="2"><font color="' . $color . '"><div class="mystatus">' . $my_lesson_status . "</div></font></td>\n" . '<td colspan="2"><div class="mystatus" align="center">';
-					 if ($row['item_type'] == 'quiz') {
+					 if ($row['item_type'] == 'quiz') {
 
-					 	if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
-							$output .=  '/';
+					 	if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
+							$output .=  '/';
 						} else {
 							$output .= ($score == 0 ? '0/'.float_format($maxscore, 1) : ($maxscore == 0 ? $score : float_format($score, 1) . '/' . float_format($maxscore, 1)));
-						}
+						}
 
-					 } else {
+					 } else {
 					    $output .= ($score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . $maxscore));
 					 }
-					 $output .= "</div></td>\n" . '<td colspan="2"><div class="mystatus">' . $time . "</div></td><td>$correct_test_link</td>\n";
+					 $output .= "</div></td>\n" . '<td colspan="2"><div class="mystatus">' . $time . "</div></td><td>$correct_test_link</td>\n";
 					 $output .= "</tr>\n";
-				}
-
-				if (!empty($export_csv)) {
-					$temp = array ();
-					$temp[] = api_html_entity_decode($title, ENT_QUOTES, $lp_charset);
-					$temp[] = api_html_entity_decode($my_lesson_status, ENT_QUOTES, $lp_charset);
-
-					if ($row['item_type'] == 'quiz') {
-
-						if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
-							$temp[] =  '/';
-						} else {
-							$temp[] = ($score == 0 ? '0/'.$maxscore : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
-						}
-
-					} else {
-						$temp[] = ($score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
-					}
-
-					$temp[] = $time;
-					$csv_content[] = $temp;
-				}
-
-			}
-
-			$counter++;
-
-			if ($extend_this_attempt OR $extend_all) {
-				$list1 = learnpath :: get_iv_interactions_array($row['iv_id']);
-				foreach ($list1 as $id => $interaction) {
-					if (($counter % 2) == 0) {
-						$oddclass = "row_odd";
-					} else {
-						$oddclass = "row_even";
-					}
-					$output .= "<tr class='$oddclass'>\n" . '<td></td>' . "\n" . '<td></td>' . "\n" . '<td>&nbsp;</td>' . "\n" . '<td>' . $interaction['order_id'] . '</td>' . "\n" . '<td>' . $interaction['id'] . '</td>' . "\n"
-					//."<td><font color='$color'><div class='mystatus'>"api_convert_encoding($array_status[$lesson_status],$lp_charset,$lp_charset)."</div></font></td>\n"
-					 . '<td colspan="2">' . $interaction['type'] . "</td>\n"
-					//.'<td>'.$interaction['correct_responses']."</td>\n"
-					 . '<td>' . urldecode($interaction['student_response']) . "</td>\n" . '<td>' . $interaction['result'] . "</td>\n" . '<td>' . $interaction['latency'] . "</td>\n" . '<td>' . $interaction['time'] . "</td>\n<td></td>\n</tr>\n";
-					$counter++;
-				}
-				$list2 = learnpath :: get_iv_objectives_array($row['iv_id']);
-				foreach ($list2 as $id => $interaction) {
-					if (($counter % 2) == 0) {
-						$oddclass = "row_odd";
-					} else {
-						$oddclass = "row_even";
-					}
-					$output .= "<tr class='$oddclass'>\n" . '<td></td>' . "\n" . '<td></td>' . "\n" . '<td>&nbsp;</td>' . "\n" . '<td>' . $interaction['order_id'] . '</td>' . "\n" . '<td colspan="2">' . $interaction['objective_id'] . '</td>' . "\n" .
-					'<td colspan="2">' . $interaction['status'] . "</td>\n" .
-					'<td>' . $interaction['score_raw'] . "</td>\n" . '<td>' . $interaction['score_max'] . "</td>\n" . '<td>' . $interaction['score_min'] . "</td>\n<td></td>\n</tr>\n";
-					$counter++;
-				}
-			}
+				}
+
+				if (!empty($export_csv)) {
+					$temp = array ();
+					$temp[] = api_html_entity_decode($title, ENT_QUOTES, $lp_charset);
+					$temp[] = api_html_entity_decode($my_lesson_status, ENT_QUOTES, $lp_charset);
+
+					if ($row['item_type'] == 'quiz') {
+
+						if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
+							$temp[] =  '/';
+						} else {
+							$temp[] = ($score == 0 ? '0/'.$maxscore : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
+						}
+
+					} else {
+						$temp[] = ($score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
+					}
+
+					$temp[] = $time;
+					$csv_content[] = $temp;
+				}
+
+			}
+
+			$counter++;
+
+			if ($extend_this_attempt OR $extend_all) {
+				$list1 = learnpath :: get_iv_interactions_array($row['iv_id']);
+				foreach ($list1 as $id => $interaction) {
+					if (($counter % 2) == 0) {
+						$oddclass = "row_odd";
+					} else {
+						$oddclass = "row_even";
+					}
+					$output .= "<tr class='$oddclass'>\n" . '<td></td>' . "\n" . '<td></td>' . "\n" . '<td>&nbsp;</td>' . "\n" . '<td>' . $interaction['order_id'] . '</td>' . "\n" . '<td>' . $interaction['id'] . '</td>' . "\n"
+					//."<td><font color='$color'><div class='mystatus'>"api_convert_encoding($array_status[$lesson_status],$lp_charset,$lp_charset)."</div></font></td>\n"
+					 . '<td colspan="2">' . $interaction['type'] . "</td>\n"
+					//.'<td>'.$interaction['correct_responses']."</td>\n"
+					 . '<td>' . urldecode($interaction['student_response']) . "</td>\n" . '<td>' . $interaction['result'] . "</td>\n" . '<td>' . $interaction['latency'] . "</td>\n" . '<td>' . $interaction['time'] . "</td>\n<td></td>\n</tr>\n";
+					$counter++;
+				}
+				$list2 = learnpath :: get_iv_objectives_array($row['iv_id']);
+				foreach ($list2 as $id => $interaction) {
+					if (($counter % 2) == 0) {
+						$oddclass = "row_odd";
+					} else {
+						$oddclass = "row_even";
+					}
+					$output .= "<tr class='$oddclass'>\n" . '<td></td>' . "\n" . '<td></td>' . "\n" . '<td>&nbsp;</td>' . "\n" . '<td>' . $interaction['order_id'] . '</td>' . "\n" . '<td colspan="2">' . $interaction['objective_id'] . '</td>' . "\n" .
+					'<td colspan="2">' . $interaction['status'] . "</td>\n" .
+					'<td>' . $interaction['score_raw'] . "</td>\n" . '<td>' . $interaction['score_max'] . "</td>\n" . '<td>' . $interaction['score_min'] . "</td>\n<td></td>\n</tr>\n";
+					$counter++;
+				}
+			}
 
 			// attempts list by exercise
-			if ( (isset($_GET['lp_id']) && $_GET['lp_id'] == $my_lp_id ) && (isset($_GET['my_lp_id']) && $_GET['my_lp_id'] == $my_id)) {
+			if ( (isset($_GET['lp_id']) && $_GET['lp_id'] == $my_lp_id ) && (isset($_GET['my_lp_id']) && $_GET['my_lp_id'] == $my_id)) {
 
-					$res_attempts = Database::query($sql_attempts,__FILE__,__LINE__);
+					$res_attempts = Database::query($sql_attempts,__FILE__,__LINE__);
 					$num_attempts = Database :: num_rows($res_attempts);
 					if ($row['item_type'] === 'quiz') {
 						if ($num_attempts > 0) {
 							$n=1;
-							while ($row_attempts = Database :: fetch_array($res_attempts)) {
-								$my_score = $row_attempts['exe_result'];
-								$my_maxscore = $row_attempts['exe_weighting'];
-								$my_exe_id	= $row_attempts['exe_id'];
-								$my_orig_lp = $row_attempts['orig_lp_id'];
-								$my_orig_lp_item = $row_attempts['orig_lp_item_id'];
+							while ($row_attempts = Database :: fetch_array($res_attempts)) {
+								$my_score = $row_attempts['exe_result'];
+								$my_maxscore = $row_attempts['exe_weighting'];
+								$my_exe_id	= $row_attempts['exe_id'];
+								$my_orig_lp = $row_attempts['orig_lp_id'];
+								$my_orig_lp_item = $row_attempts['orig_lp_item_id'];
 								$my_exo_exe_id=$row_attempts['exe_exo_id'];
-								$mktime_start_date = convert_mysql_date($row_attempts['start_date']);
-								$mktime_exe_date = convert_mysql_date($row_attempts['exe_date']);
+								$mktime_start_date = convert_mysql_date($row_attempts['start_date']);
+								$mktime_exe_date = convert_mysql_date($row_attempts['exe_date']);
 								$mytime = ((int)$mktime_exe_date-(int)$mktime_start_date);
-								$time_attemp = learnpathItem :: get_scorm_time('js', $mytime);
-								$time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
+								$time_attemp = learnpathItem :: get_scorm_time('js', $mytime);
+								$time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
 
-								if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
-									$view_score =  '-';
-								} else {
-									//show only float when need it
+								if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
+									$view_score =  '-';
+								} else {
+									//show only float when need it
 									$my_score  = float_format( $my_score, 1);
 									$my_maxscore =float_format($my_maxscore, 1);
-									if ($my_score == 0 ){
-										$view_score = 	'0/'.$my_maxscore;
-									} else {
+									if ($my_score == 0 ){
+										$view_score = 	'0/'.$my_maxscore;
+									} else {
 										if ($my_maxscore==0)
-											$view_score = $my_score;
+											$view_score = $my_score;
 										else
 											$view_score = $my_score . '/' . $my_maxscore;
-									}
+									}
 									//$view_score = ($my_score == 0 ? '0.00/'.$my_maxscore : ($my_maxscore == 0 ? $my_score : $my_score . '/' . $my_maxscore));
-								}
+								}
 
 								$output .= '<tr class="'.$oddclass.'" ><td>&nbsp;</td><td>'.$extend_attempt_link.'</td><td colspan="3">' . api_convert_encoding(get_lang('Attempt'), $lp_charset, $dokeos_charset) . ' ' . $n . '</td>'
-							 			. '<td colspan="2"><font color="' . $color . '"><div class="mystatus">' . $my_lesson_status . '</div></font></td><td colspan="2"><div class="mystatus" align="center">' . $view_score  . '</div></td><td colspan="2"><div class="mystatus">' . $time_attemp . '</div></td>';
-							 	if ($origin != 'tracking') {
-							 		if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
-										$output .= '<td><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="'.api_convert_encoding(get_lang('ShowAttempt'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('ShowAttempt'), $lp_charset, $dokeos_charset).'"></td>';
-									} else {
+							 			. '<td colspan="2"><font color="' . $color . '"><div class="mystatus">' . $my_lesson_status . '</div></font></td><td colspan="2"><div class="mystatus" align="center">' . $view_score  . '</div></td><td colspan="2"><div class="mystatus">' . $time_attemp . '</div></td>';
+							 	if ($origin != 'tracking') {
+							 		if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
+										$output .= '<td><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="'.api_convert_encoding(get_lang('ShowAttempt'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('ShowAttempt'), $lp_charset, $dokeos_charset).'"></td>';
+									} else {
 										$output .= '<td><a href="../exercice/exercise_show.php?origin=student_progress&myid='.$my_orig_lp.'&my_lp_id='.$my_orig_lp_item.'&id=' . $my_exe_id . '&cidReq=' . $course_code . '&student=' . $student_id .$from_link. '" target="_parent"><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" alt="'.api_convert_encoding(get_lang('ShowAttempt'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('ShowAttempt'), $lp_charset, $dokeos_charset).'"></a></td>';
 									}
 								} else {
-									if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
-										$output .= '<td><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="'.api_convert_encoding(get_lang('ShowAndQualifyAttempt'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('ShowAndQualifyAttempt'), $lp_charset, $dokeos_charset).'"></td>';
-									} else {
+									if (!api_is_allowed_to_edit() && $result_disabled_ext_all) {
+										$output .= '<td><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="'.api_convert_encoding(get_lang('ShowAndQualifyAttempt'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('ShowAndQualifyAttempt'), $lp_charset, $dokeos_charset).'"></td>';
+									} else {
 										$output .= '<td><a href="../exercice/exercise_show.php?origin=tracking_course&myid='.$my_orig_lp.'&my_lp_id='.$my_orig_lp_item.'&id=' . $my_exe_id . '&cidReq=' . $course_code . '&student=' . $student_id . '&total_time='.$mytime.'&my_exe_exo_id='.$my_exo_exe_id.$from_link.' " target="_parent"><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" alt="'.api_convert_encoding(get_lang('ShowAndQualifyAttempt'), $lp_charset, $dokeos_charset).'" title="'.api_convert_encoding(get_lang('ShowAndQualifyAttempt'), $lp_charset, $dokeos_charset).'"></a></td>';
 									}
 
 								}
-							 	$output .= '</tr>';
+							 	$output .= '</tr>';
 								$n++;
 							}
-						}
+						}
 						$output .= '<tr><td colspan="12">&nbsp;</td></tr>';
 					}
-				}
-		}
+				}
+		}
 
-		$total_time += $time_for_total;
-		//QUIZZ IN LP
+		$total_time += $time_for_total;
+		//QUIZZ IN LP
 		$a_my_id = array();
-		if (!empty($my_lp_id)) {
+		if (!empty($my_lp_id)) {
 			$a_my_id[] = $my_lp_id;
-		}
-	}
-}
-
-if (!empty($a_my_id)) {
-	$my_studen_id = 0;
-	$my_course_id = '';
-	if ($origin == 'tracking') {
-		$my_studen_id = $student_id;
-		$my_course_id = Database::escape_string($_GET['course']);
-	} else {
-		$my_studen_id = intval(api_get_user_id());
-		$my_course_id = Database::escape_string(api_get_course_id());
+		}
+	}
+}
+
+if (!empty($a_my_id)) {
+	$my_studen_id = 0;
+	$my_course_id = '';
+	if ($origin == 'tracking') {
+		$my_studen_id = $student_id;
+		$my_course_id = Database::escape_string($_GET['course']);
+	} else {
+		$my_studen_id = intval(api_get_user_id());
+		$my_course_id = Database::escape_string(api_get_course_id());
 	}
 	$total_score = Tracking::get_avg_student_score($my_studen_id, $my_course_id, $a_my_id);
-} else {
-	$total_score = 0;
-}
-
-$total_time = learnpathItem :: get_scorm_time('js', $total_time);
-//$total_time = str_replace('NaN','00:00:00',$total_time);
-$total_time = str_replace('NaN', '00' . $h . '00\'00"', $total_time);
-$lp_type = learnpath :: get_type_static($lp_id);
-$total_percent = 0;
-$final_score = $total_score.'%';
-
-if (($counter % 2) == 0) {
-	$oddclass = "row_odd";
-} else {
-	$oddclass = "row_even";
-}
-
-if (empty($extend_all)) {
-	$output .= "<tr class='$oddclass'>\n" . "<td></td>\n" . '<td colspan="4"><div class="mystatus"><i>' . api_convert_encoding(get_lang('AccomplishedStepsTotal') , $lp_charset, $dokeos_charset) . "</i></div></td>\n"
+} else {
+	$total_score = 0;
+}
+
+$total_time = learnpathItem :: get_scorm_time('js', $total_time);
+//$total_time = str_replace('NaN','00:00:00',$total_time);
+$total_time = str_replace('NaN', '00' . $h . '00\'00"', $total_time);
+$lp_type = learnpath :: get_type_static($lp_id);
+$total_percent = 0;
+$final_score = $total_score.'%';
+
+if (($counter % 2) == 0) {
+	$oddclass = "row_odd";
+} else {
+	$oddclass = "row_even";
+}
+
+if (empty($extend_all)) {
+	$output .= "<tr class='$oddclass'>\n" . "<td></td>\n" . '<td colspan="4"><div class="mystatus"><i>' . api_convert_encoding(get_lang('AccomplishedStepsTotal') , $lp_charset, $dokeos_charset) . "</i></div></td>\n"
  			. '<td colspan="2"></td>' . "\n" . '<td colspan="2"><div class="mystatus" align="center">' . $final_score . "</div></td>\n" . '<td colspan="2"><div class="mystatus">' . $total_time . '</div></td><td></td>' . "\n" . "</tr>\n";
-}
-
-$output .= "</table></td></tr></table>";
-
-if (!empty($export_csv)) {
-	$temp = array (
-		'',
-		'',
-		'',
-		''
-	);
-	$csv_content[] = $temp;
-	$temp = array (
-		api_convert_encoding(get_lang('AccomplishedStepsTotal') , $lp_charset, $dokeos_charset),
-		'',
-		$final_score,
-		$total_time
-	);
-	$csv_content[] = $temp;
-	ob_end_clean();
-	Export :: export_table_csv($csv_content, 'reporting_learning_path_details');
-}
-
-if ($origin != 'tracking') {
-	$output .= "</body></html>";
-}
-
-if (empty($export_csv)) {
-	echo $output;
-}
+}
+
+$output .= "</table></td></tr></table>";
+
+if (!empty($export_csv)) {
+	$temp = array (
+		'',
+		'',
+		'',
+		''
+	);
+	$csv_content[] = $temp;
+	$temp = array (
+		api_convert_encoding(get_lang('AccomplishedStepsTotal') , $lp_charset, $dokeos_charset),
+		'',
+		$final_score,
+		$total_time
+	);
+	$csv_content[] = $temp;
+	ob_end_clean();
+	Export :: export_table_csv($csv_content, 'reporting_learning_path_details');
+}
+
+if ($origin != 'tracking') {
+	$output .= "</body></html>";
+}
+
+if (empty($export_csv)) {
+	echo $output;
+}

+ 48 - 48
main/newscorm/lp_toc.php

@@ -1,49 +1,49 @@
-<?php //$id: $
-/**
- * Script opened in an iframe and containing the learning path's table of contents
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
- * Script
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-$language_file[] = "scormdocument";
-$language_file[] = "scorm";
-$language_file[] = "learnpath";
-require_once('back_compat.inc.php');
-require_once('learnpath.class.php');
-require_once('scorm.class.php');
-require_once('aicc.class.php');
-
-if(isset($_SESSION['lpobject']))
-{
-	//if($debug>0) error_log('New LP - in lp_toc.php - SESSION[lpobject] is defined',0);
-	$oLP = unserialize($_SESSION['lpobject']);
-	if(is_object($oLP)){
-		$_SESSION['oLP'] = $oLP;
-	}else{
-		//error_log('New LP - in lp_toc.php - SESSION[lpobject] is not object - dying',0);
-		die('Could not instanciate lp object');
-	}
-}
-$charset = $_SESSION['oLP']->encoding;
-$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
-  var dokeos_xajax_handler = window.parent.oxajax;
-</script>';
-$scorm_css_header=true;
-$display_mode='';
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-include_once('../inc/reduced_header.inc.php');
-?>
-<body>
-  <?php  echo $_SESSION['oLP']->get_html_toc();?><br/>
-</body>
-</html>
-<?php
-if(!empty($_SESSION['oLP'])){
-	$_SESSION['lpobject'] = serialize($_SESSION['oLP']);
-}
+<?php //$id: $
+/**
+ * Script opened in an iframe and containing the learning path's table of contents
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * Script
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+$language_file[] = "scormdocument";
+$language_file[] = "scorm";
+$language_file[] = "learnpath";
+require_once('back_compat.inc.php');
+require_once('learnpath.class.php');
+require_once('scorm.class.php');
+require_once('aicc.class.php');
+
+if(isset($_SESSION['lpobject']))
+{
+	//if($debug>0) error_log('New LP - in lp_toc.php - SESSION[lpobject] is defined',0);
+	$oLP = unserialize($_SESSION['lpobject']);
+	if(is_object($oLP)){
+		$_SESSION['oLP'] = $oLP;
+	}else{
+		//error_log('New LP - in lp_toc.php - SESSION[lpobject] is not object - dying',0);
+		die('Could not instanciate lp object');
+	}
+}
+$charset = $_SESSION['oLP']->encoding;
+$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
+  var dokeos_xajax_handler = window.parent.oxajax;
+</script>';
+$scorm_css_header=true;
+$display_mode='';
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+include_once('../inc/reduced_header.inc.php');
+?>
+<body>
+  <?php  echo $_SESSION['oLP']->get_html_toc();?><br/>
+</body>
+</html>
+<?php
+if(!empty($_SESSION['oLP'])){
+	$_SESSION['lpobject'] = serialize($_SESSION['oLP']);
+}
 ?>

+ 155 - 155
main/newscorm/lp_upload.php

@@ -1,165 +1,165 @@
-<?php //$id: $
-/**
- * Script managing the learnpath upload. To best treat the uploaded file, make sure we can identify it.
- * @package dokeos.learnpath
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Script initialisations
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-require_once('back_compat.inc.php');
-$course_dir  = api_get_course_path().'/scorm';
-$course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_dir;
-if ( empty($_POST['current_dir']) ) {
-	$current_dir = '';
-} else {
-    $current_dir = replace_dangerous_char(trim($_POST['current_dir']),'strict');
-}
-$uncompress  = 1;
-
-//error_log('New LP - lp_upload.php',0);
-/*
- * check the request method in place of a variable from POST
- * because if the file size exceed the maximum file upload
- * size set in php.ini, all variables from POST are cleared !
- */
-
+<?php //$id: $
+/**
+ * Script managing the learnpath upload. To best treat the uploaded file, make sure we can identify it.
+ * @package dokeos.learnpath
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Script initialisations
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+require_once('back_compat.inc.php');
+$course_dir  = api_get_course_path().'/scorm';
+$course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_dir;
+if ( empty($_POST['current_dir']) ) {
+	$current_dir = '';
+} else {
+    $current_dir = replace_dangerous_char(trim($_POST['current_dir']),'strict');
+}
+$uncompress  = 1;
+
+//error_log('New LP - lp_upload.php',0);
+/*
+ * check the request method in place of a variable from POST
+ * because if the file size exceed the maximum file upload
+ * size set in php.ini, all variables from POST are cleared !
+ */
+
 if ($_SERVER['REQUEST_METHOD'] == 'POST'
-	&& count($_FILES)>0
-	&& !empty($_FILES['user_file']['name'])
-	)
-{
-
-	// A file upload has been detected, now deal with the file...
-	//directory creation
-
-	$stopping_error = false;
-
-	$s=$_FILES['user_file']['name'];
-	//get name of the zip file without the extension
-	$info = pathinfo($s);
-	$filename = $info['basename'];
-	$extension = $info['extension'];
-	$file_base_name = str_replace('.'.$extension,'',$filename);
+	&& count($_FILES)>0
+	&& !empty($_FILES['user_file']['name'])
+	)
+{
+
+	// A file upload has been detected, now deal with the file...
+	//directory creation
+
+	$stopping_error = false;
+
+	$s=$_FILES['user_file']['name'];
+	//get name of the zip file without the extension
+	$info = pathinfo($s);
+	$filename = $info['basename'];
+	$extension = $info['extension'];
+	$file_base_name = str_replace('.'.$extension,'',$filename);
+
 
+	$new_dir = replace_dangerous_char(trim($file_base_name),'strict');
 
-	$new_dir = replace_dangerous_char(trim($file_base_name),'strict');
-
-	require_once('learnpath.class.php');
-	$type = learnpath::get_package_type($_FILES['user_file']['tmp_name'],$_FILES['user_file']['name']);
-	switch($type){
-		case 'scorm':
-			require_once('scorm.class.php');
-			$oScorm = new scorm();
-			$manifest = $oScorm->import_package($_FILES['user_file'],$current_dir);
-			if(!empty($manifest)){
-				$oScorm->parse_manifest($manifest);
-				$oScorm->import_manifest(api_get_course_id());
-			}else{
-				//show error message stored in $oScrom->error_msg
-			}
+	require_once('learnpath.class.php');
+	$type = learnpath::get_package_type($_FILES['user_file']['tmp_name'],$_FILES['user_file']['name']);
+	switch($type){
+		case 'scorm':
+			require_once('scorm.class.php');
+			$oScorm = new scorm();
+			$manifest = $oScorm->import_package($_FILES['user_file'],$current_dir);
+			if(!empty($manifest)){
+				$oScorm->parse_manifest($manifest);
+				$oScorm->import_manifest(api_get_course_id());
+			}else{
+				//show error message stored in $oScrom->error_msg
+			}
 
-			$proximity = '';
-			if(!empty($_REQUEST['content_proximity'])){$proximity = Database::escape_string($_REQUEST['content_proximity']);}
-			$maker = '';
-			if(!empty($_REQUEST['content_maker'])){$maker = Database::escape_string($_REQUEST['content_maker']);}
-			$oScorm->set_proximity($proximity);
-			$oScorm->set_maker($maker);
-			$oScorm->set_jslib('scorm_api.php');
-			break;
-		case 'aicc':
-			require_once('aicc.class.php');
-			$oAICC = new aicc();
-			$config_dir = $oAICC->import_package($_FILES['user_file']);
-			if(!empty($config_dir)){
-				$oAICC->parse_config_files($config_dir);
-				$oAICC->import_aicc(api_get_course_id());
-			}
-			$proximity = '';
-			if(!empty($_REQUEST['content_proximity'])){$proximity = mysql_real_escape_string($_REQUEST['content_proximity']);}
-			$maker = '';
-			if(!empty($_REQUEST['content_maker'])){$maker = mysql_real_escape_string($_REQUEST['content_maker']);}
-			$oAICC->set_proximity($proximity);
-			$oAICC->set_maker($maker);
-			$oAICC->set_jslib('aicc_api.php');
-			break;
-		case 'oogie':
-			require_once('openoffice_presentation.class.php');
-			$take_slide_name = empty($_POST['take_slide_name']) ? false : true;
-			$o_ppt = new OpenofficePresentation($take_slide_name);
+			$proximity = '';
+			if(!empty($_REQUEST['content_proximity'])){$proximity = Database::escape_string($_REQUEST['content_proximity']);}
+			$maker = '';
+			if(!empty($_REQUEST['content_maker'])){$maker = Database::escape_string($_REQUEST['content_maker']);}
+			$oScorm->set_proximity($proximity);
+			$oScorm->set_maker($maker);
+			$oScorm->set_jslib('scorm_api.php');
+			break;
+		case 'aicc':
+			require_once('aicc.class.php');
+			$oAICC = new aicc();
+			$config_dir = $oAICC->import_package($_FILES['user_file']);
+			if(!empty($config_dir)){
+				$oAICC->parse_config_files($config_dir);
+				$oAICC->import_aicc(api_get_course_id());
+			}
+			$proximity = '';
+			if(!empty($_REQUEST['content_proximity'])){$proximity = mysql_real_escape_string($_REQUEST['content_proximity']);}
+			$maker = '';
+			if(!empty($_REQUEST['content_maker'])){$maker = mysql_real_escape_string($_REQUEST['content_maker']);}
+			$oAICC->set_proximity($proximity);
+			$oAICC->set_maker($maker);
+			$oAICC->set_jslib('aicc_api.php');
+			break;
+		case 'oogie':
+			require_once('openoffice_presentation.class.php');
+			$take_slide_name = empty($_POST['take_slide_name']) ? false : true;
+			$o_ppt = new OpenofficePresentation($take_slide_name);
 			$first_item_id = $o_ppt -> convert_document($_FILES['user_file']);
-			break;
-		case 'woogie':
-			require_once('openoffice_text.class.php');
-			$split_steps = $_POST['split_steps'];
-			$o_doc = new OpenofficeText($split_steps);
+			break;
+		case 'woogie':
+			require_once('openoffice_text.class.php');
+			$split_steps = $_POST['split_steps'];
+			$o_doc = new OpenofficeText($split_steps);
 			$first_item_id = $o_doc -> convert_document($_FILES['user_file']);
-			break;
-		case '':
-		default:
-			return api_failure::set_failure('not_a_learning_path');
-	}
-} // end if is_uploaded_file
-elseif($_SERVER['REQUEST_METHOD'] == 'POST')
-{
-	//if file name given to get in claroline/upload/, try importing this way
+			break;
+		case '':
+		default:
+			return api_failure::set_failure('not_a_learning_path');
+	}
+} // end if is_uploaded_file
+elseif($_SERVER['REQUEST_METHOD'] == 'POST')
+{
+	//if file name given to get in claroline/upload/, try importing this way
+
+	// A file upload has been detected, now deal with the file...
+	//directory creation
+
+	$stopping_error = false;
+
+	//escape path with basename so it can only be directly into the claroline/upload directory
+	$s=api_get_path(SYS_ARCHIVE_PATH).basename($_POST['file_name']);
+	//get name of the zip file without the extension
+	$info = pathinfo($s);
+	$filename = $info['basename'];
+	$extension = $info['extension'];
+	$file_base_name = str_replace('.'.$extension,'',$filename);
+	$new_dir = replace_dangerous_char(trim($file_base_name),'strict');
+
+	require_once('learnpath.class.php');
 
-	// A file upload has been detected, now deal with the file...
-	//directory creation
-
-	$stopping_error = false;
-
-	//escape path with basename so it can only be directly into the claroline/upload directory
-	$s=api_get_path(SYS_ARCHIVE_PATH).basename($_POST['file_name']);
-	//get name of the zip file without the extension
-	$info = pathinfo($s);
-	$filename = $info['basename'];
-	$extension = $info['extension'];
-	$file_base_name = str_replace('.'.$extension,'',$filename);
-	$new_dir = replace_dangerous_char(trim($file_base_name),'strict');
-
-	require_once('learnpath.class.php');
-
-	$type = learnpath::get_package_type($s,basename($s));
-	switch($type){
-		case 'scorm':
-			require_once('scorm.class.php');
-			$oScorm = new scorm();
-			$manifest = $oScorm->import_local_package($s,$current_dir);
-			if(!empty($manifest)){
-				$oScorm->parse_manifest($manifest);
-				$oScorm->import_manifest(api_get_course_id());
-			}
+	$type = learnpath::get_package_type($s,basename($s));
+	switch($type){
+		case 'scorm':
+			require_once('scorm.class.php');
+			$oScorm = new scorm();
+			$manifest = $oScorm->import_local_package($s,$current_dir);
+			if(!empty($manifest)){
+				$oScorm->parse_manifest($manifest);
+				$oScorm->import_manifest(api_get_course_id());
+			}
 
-			$proximity = '';
-			if(!empty($_REQUEST['content_proximity'])){$proximity = mysql_real_escape_string($_REQUEST['content_proximity']);}
-			$maker = '';
-			if(!empty($_REQUEST['content_maker'])){$maker = mysql_real_escape_string($_REQUEST['content_maker']);}
-			$oScorm->set_proximity($proximity);
-			$oScorm->set_maker($maker);
-			$oScorm->set_jslib('scorm_api.php');
-			break;
-		case 'aicc':
-			require_once('aicc.class.php');
-			$oAICC = new aicc();
-			$config_dir = $oAICC->import_local_package($s,$current_dir);
-			if(!empty($config_dir)){
-				$oAICC->parse_config_files($config_dir);
-				$oAICC->import_aicc(api_get_course_id());
-			}
-			$proximity = '';
-			if(!empty($_REQUEST['content_proximity'])){$proximity = mysql_real_escape_string($_REQUEST['content_proximity']);}
-			$maker = '';
-			if(!empty($_REQUEST['content_maker'])){$maker = mysql_real_escape_string($_REQUEST['content_maker']);}
-			$oAICC->set_proximity($proximity);
-			$oAICC->set_maker($maker);
-			$oAICC->set_jslib('aicc_api.php');
-			break;
-		case '':
-		default:
-			return api_failure::set_failure('not_a_learning_path');
+			$proximity = '';
+			if(!empty($_REQUEST['content_proximity'])){$proximity = mysql_real_escape_string($_REQUEST['content_proximity']);}
+			$maker = '';
+			if(!empty($_REQUEST['content_maker'])){$maker = mysql_real_escape_string($_REQUEST['content_maker']);}
+			$oScorm->set_proximity($proximity);
+			$oScorm->set_maker($maker);
+			$oScorm->set_jslib('scorm_api.php');
+			break;
+		case 'aicc':
+			require_once('aicc.class.php');
+			$oAICC = new aicc();
+			$config_dir = $oAICC->import_local_package($s,$current_dir);
+			if(!empty($config_dir)){
+				$oAICC->parse_config_files($config_dir);
+				$oAICC->import_aicc(api_get_course_id());
+			}
+			$proximity = '';
+			if(!empty($_REQUEST['content_proximity'])){$proximity = mysql_real_escape_string($_REQUEST['content_proximity']);}
+			$maker = '';
+			if(!empty($_REQUEST['content_maker'])){$maker = mysql_real_escape_string($_REQUEST['content_maker']);}
+			$oAICC->set_proximity($proximity);
+			$oAICC->set_maker($maker);
+			$oAICC->set_jslib('aicc_api.php');
+			break;
+		case '':
+		default:
+			return api_failure::set_failure('not_a_learning_path');
 	}
-}
+}
 ?>

+ 60 - 60
main/newscorm/lp_view.lib.js

@@ -1,61 +1,61 @@
-/***********************************************
-* IFrame SSI script II- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
-* Visit DynamicDrive.com for hundreds of original DHTML scripts
-* This notice must stay intact for legal use
-***********************************************/
-
-//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
-//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
-var iframeid="lp_content_frame";
-
-//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
-var iframehide="no";
-
-//var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
-var FFextraHeight=32; //parseFloat(getFFVersion)>=0.1? 16 : 0; //extra height in px to add to iframe in FireFox 1.0+ browsers
-
-function resizeCaller() {
-	if (document.getElementById)
-		resizeIframe(iframeid);
-	//reveal iframe for lower end browsers? (see var above):
-	if ((document.all || document.getElementById) && iframehide=="no"){
-		var tempobj=document.all? document.all[iframeid] : document.getElementById(iframeid);
-		tempobj.style.display="block";
-	}
-}
-
-function resizeIframe(frameid){
-	var currentfr=document.getElementById(frameid);
-	if (currentfr && !window.opera){
-		currentfr.style.display="block";
-		if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight){ //ns6 syntax
-			currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight;
-		}
-		else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
-			currentfr.height = currentfr.Document.body.scrollHeight;
-
-		if(currentfr.height < 580){
-			currentfr.height = 580;
-		}
-		if (currentfr.addEventListener)
-			currentfr.addEventListener("load", readjustIframe, false);
-		else if (currentfr.attachEvent){
-			currentfr.detachEvent("onload", readjustIframe); // Bug fix line
-			currentfr.attachEvent("onload", readjustIframe);
-		}
-	}
-}
-
-function readjustIframe(loadevt) {
-	var crossevt=(window.event)? event : loadevt;
-	var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement;
-	if (iframeroot)
-		resizeIframe(iframeroot.id);
-}
-
-if (window.addEventListener)
-	window.addEventListener("load", resizeCaller, false);
-else if (window.attachEvent)
-	window.attachEvent("onload", resizeCaller);
-else
+/***********************************************
+* IFrame SSI script II- � Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
+* Visit DynamicDrive.com for hundreds of original DHTML scripts
+* This notice must stay intact for legal use
+***********************************************/
+
+//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
+//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
+var iframeid="lp_content_frame";
+
+//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
+var iframehide="no";
+
+//var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
+var FFextraHeight=32; //parseFloat(getFFVersion)>=0.1? 16 : 0; //extra height in px to add to iframe in FireFox 1.0+ browsers
+
+function resizeCaller() {
+	if (document.getElementById)
+		resizeIframe(iframeid);
+	//reveal iframe for lower end browsers? (see var above):
+	if ((document.all || document.getElementById) && iframehide=="no"){
+		var tempobj=document.all? document.all[iframeid] : document.getElementById(iframeid);
+		tempobj.style.display="block";
+	}
+}
+
+function resizeIframe(frameid){
+	var currentfr=document.getElementById(frameid);
+	if (currentfr && !window.opera){
+		currentfr.style.display="block";
+		if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight){ //ns6 syntax
+			currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight;
+		}
+		else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
+			currentfr.height = currentfr.Document.body.scrollHeight;
+
+		if(currentfr.height < 580){
+			currentfr.height = 580;
+		}
+		if (currentfr.addEventListener)
+			currentfr.addEventListener("load", readjustIframe, false);
+		else if (currentfr.attachEvent){
+			currentfr.detachEvent("onload", readjustIframe); // Bug fix line
+			currentfr.attachEvent("onload", readjustIframe);
+		}
+	}
+}
+
+function readjustIframe(loadevt) {
+	var crossevt=(window.event)? event : loadevt;
+	var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement;
+	if (iframeroot)
+		resizeIframe(iframeroot.id);
+}
+
+if (window.addEventListener)
+	window.addEventListener("load", resizeCaller, false);
+else if (window.attachEvent)
+	window.attachEvent("onload", resizeCaller);
+else
 	window.onload=resizeCaller;

+ 554 - 554
main/newscorm/lp_view.php

@@ -1,632 +1,632 @@
-<?php // $Id: lp_view.php,v 1.33 2006/09/12 10:20:46 yannoo Exp $
-/**
-==============================================================================
-* This file was origially the copy of document.php, but many modifications happened since then ;
-* the direct file view is not needed anymore, if the user uploads a scorm zip file, a directory
-* will be automatically created for it, and the files will be uncompressed there for example ;
-*
-* @package dokeos.learnpath
-* @author Yannick Warnier <ywarnier@beeznest.org> - redesign
-* @author Denes Nagy, principal author
-* @author Isthvan Mandak, several new features
-* @author Roan Embrechts, code improvements and refactoring
-* @license	GNU/GPL - See Dokeos license directory for details
-==============================================================================
-*/
-/**
- * Script
- */
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-
-$_SESSION['whereami'] = 'lp/view';
-$this_section=SECTION_COURSES;
-
-if($lp_controller_touched!=1){
-	header('location: lp_controller.php?action=view&item_id='.$_REQUEST['item_id']);
-}
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
-*/
-require_once('back_compat.inc.php');
-//require_once('../learnpath/learnpath_functions.inc.php');
-require_once('scorm.lib.php');
-require_once('learnpath.class.php');
-require_once('learnpathItem.class.php');
-//require_once('lp_comm.common.php'); //xajax functions
-
-if ($is_allowed_in_course == false) api_not_allowed();
-/*
------------------------------------------------------------
-	Variables
------------------------------------------------------------
-*/
-//$charset = 'UTF-8';
-//$charset = 'ISO-8859-1';
-
-// we set the encoding of the lp
-if (!empty($_SESSION['oLP']->encoding)) {
-	$charset = $_SESSION['oLP']->encoding;
+<?php // $Id: lp_view.php,v 1.33 2006/09/12 10:20:46 yannoo Exp $
+/**
+==============================================================================
+* This file was origially the copy of document.php, but many modifications happened since then ;
+* the direct file view is not needed anymore, if the user uploads a scorm zip file, a directory
+* will be automatically created for it, and the files will be uncompressed there for example ;
+*
+* @package dokeos.learnpath
+* @author Yannick Warnier <ywarnier@beeznest.org> - redesign
+* @author Denes Nagy, principal author
+* @author Isthvan Mandak, several new features
+* @author Roan Embrechts, code improvements and refactoring
+* @license	GNU/GPL - See Dokeos license directory for details
+==============================================================================
+*/
+/**
+ * Script
+ */
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+
+$_SESSION['whereami'] = 'lp/view';
+$this_section=SECTION_COURSES;
+
+if($lp_controller_touched!=1){
+	header('location: lp_controller.php?action=view&item_id='.$_REQUEST['item_id']);
+}
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+require_once('back_compat.inc.php');
+//require_once('../learnpath/learnpath_functions.inc.php');
+require_once('scorm.lib.php');
+require_once('learnpath.class.php');
+require_once('learnpathItem.class.php');
+//require_once('lp_comm.common.php'); //xajax functions
+
+if ($is_allowed_in_course == false) api_not_allowed();
+/*
+-----------------------------------------------------------
+	Variables
+-----------------------------------------------------------
+*/
+//$charset = 'UTF-8';
+//$charset = 'ISO-8859-1';
+
+// we set the encoding of the lp
+if (!empty($_SESSION['oLP']->encoding)) {
+	$charset = $_SESSION['oLP']->encoding;
 } else {
-	$charset = api_get_system_encoding();
-}
-if (empty($charset)) {
+	$charset = api_get_system_encoding();
+}
+if (empty($charset)) {
 	$charset = 'ISO-8859-1';
-}
-
-$oLearnpath = false;
-$course_code = api_get_course_id();
-$user_id = api_get_user_id();
-$platform_theme = api_get_setting('stylesheets'); 	// plataform's css
-$my_style=$platform_theme;
-//escape external variables
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-//$htmlHeadXtra[] = '<script type="text/javascript" src="lp_view.lib.js"></script>';
-//$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/')."\n";
-$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
-
-$htmlHeadXtra[] = '<script language="javascript">
-function cleanlog(){
-  if(document.getElementById){
-  	document.getElementById("log_content").innerHTML = "";
-  }
-}
-</script>';
-
-$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
-  	var dokeos_xajax_handler = window.oxajax;
-</script>';
-
-
-$_SESSION['oLP']->error = '';
-$lp_type = $_SESSION['oLP']->get_type();
-$lp_item_id = $_SESSION['oLP']->get_current_item_id();
-//$lp_item_id = learnpath::escape_string($_GET['item_id']);
-//$_SESSION['oLP']->set_current_item($lp_item_id); // already done by lp_controller.php
-
-//Prepare variables for the test tool (just in case) - honestly, this should disappear later on
-$_SESSION['scorm_view_id'] = $_SESSION['oLP']->get_view_id();
-$_SESSION['scorm_item_id'] = $lp_item_id;
-$_SESSION['lp_mode'] = $_SESSION['oLP']->mode;
-//reinit exercises variables to avoid spacename clashes (see exercise tool)
-if(isset($exerciseResult) or isset($_SESSION['exerciseResult']))
-{
-    api_session_unregister($exerciseResult);
-}
-unset($_SESSION['objExercise']);
-unset($_SESSION['questionList']);
-/**
- * Get a link to the corresponding document
- */
-
-
-if (!isset($src))
- {
- 	$src = '';
-	switch($lp_type)
-	{
-		case 1:
-			$_SESSION['oLP']->stop_previous_item();
-			$htmlHeadXtra[] = '<script src="scorm_api.php" type="text/javascript" language="javascript"></script>';
-			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
-			if($prereq_check === true){
-				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
-				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
-			}else{
-				$src = 'blank.php?error=prerequisites';
-			}
-			break;
-		case 2:
-			//save old if asset
-			$_SESSION['oLP']->stop_previous_item(); //save status manually if asset
-			$htmlHeadXtra[] = '<script src="scorm_api.php" type="text/javascript" language="javascript"></script>';
-			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
-			if($prereq_check === true){
-				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
-				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
-			}else{
-			$src = 'blank.php?error=prerequisites';
-			}
-			break;
-		case 3:
-			//aicc
-			$_SESSION['oLP']->stop_previous_item(); //save status manually if asset
-			$htmlHeadXtra[] = '<script src="'.$_SESSION['oLP']->get_js_lib().'" type="text/javascript" language="javascript"></script>';
-			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
-			if($prereq_check === true){
-				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
-				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
-			}else{
-				$src = 'blank.php';
-			}
-			break;
-		case 4:
-			break;
-	}
-}
-
-$list = $_SESSION['oLP']->get_toc();
-$type_quiz = false;
-
-foreach($list as $toc) {
-	if ($toc['id'] == $lp_item_id && ($toc['type']=='quiz') ) {
+}
+
+$oLearnpath = false;
+$course_code = api_get_course_id();
+$user_id = api_get_user_id();
+$platform_theme = api_get_setting('stylesheets'); 	// plataform's css
+$my_style=$platform_theme;
+//escape external variables
+/*
+-----------------------------------------------------------
+	Header
+-----------------------------------------------------------
+*/
+//$htmlHeadXtra[] = '<script type="text/javascript" src="lp_view.lib.js"></script>';
+//$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/')."\n";
+$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
+
+$htmlHeadXtra[] = '<script language="javascript">
+function cleanlog(){
+  if(document.getElementById){
+  	document.getElementById("log_content").innerHTML = "";
+  }
+}
+</script>';
+
+$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
+  	var dokeos_xajax_handler = window.oxajax;
+</script>';
+
+
+$_SESSION['oLP']->error = '';
+$lp_type = $_SESSION['oLP']->get_type();
+$lp_item_id = $_SESSION['oLP']->get_current_item_id();
+//$lp_item_id = learnpath::escape_string($_GET['item_id']);
+//$_SESSION['oLP']->set_current_item($lp_item_id); // already done by lp_controller.php
+
+//Prepare variables for the test tool (just in case) - honestly, this should disappear later on
+$_SESSION['scorm_view_id'] = $_SESSION['oLP']->get_view_id();
+$_SESSION['scorm_item_id'] = $lp_item_id;
+$_SESSION['lp_mode'] = $_SESSION['oLP']->mode;
+//reinit exercises variables to avoid spacename clashes (see exercise tool)
+if(isset($exerciseResult) or isset($_SESSION['exerciseResult']))
+{
+    api_session_unregister($exerciseResult);
+}
+unset($_SESSION['objExercise']);
+unset($_SESSION['questionList']);
+/**
+ * Get a link to the corresponding document
+ */
+
+
+if (!isset($src))
+ {
+ 	$src = '';
+	switch($lp_type)
+	{
+		case 1:
+			$_SESSION['oLP']->stop_previous_item();
+			$htmlHeadXtra[] = '<script src="scorm_api.php" type="text/javascript" language="javascript"></script>';
+			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
+			if($prereq_check === true){
+				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
+				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
+			}else{
+				$src = 'blank.php?error=prerequisites';
+			}
+			break;
+		case 2:
+			//save old if asset
+			$_SESSION['oLP']->stop_previous_item(); //save status manually if asset
+			$htmlHeadXtra[] = '<script src="scorm_api.php" type="text/javascript" language="javascript"></script>';
+			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
+			if($prereq_check === true){
+				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
+				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
+			}else{
+			$src = 'blank.php?error=prerequisites';
+			}
+			break;
+		case 3:
+			//aicc
+			$_SESSION['oLP']->stop_previous_item(); //save status manually if asset
+			$htmlHeadXtra[] = '<script src="'.$_SESSION['oLP']->get_js_lib().'" type="text/javascript" language="javascript"></script>';
+			$prereq_check = $_SESSION['oLP']->prerequisites_match($lp_item_id);
+			if($prereq_check === true){
+				$src = $_SESSION['oLP']->get_link('http',$lp_item_id);
+				$_SESSION['oLP']->start_current_item(); //starts time counter manually if asset
+			}else{
+				$src = 'blank.php';
+			}
+			break;
+		case 4:
+			break;
+	}
+}
+
+$list = $_SESSION['oLP']->get_toc();
+$type_quiz = false;
+
+foreach($list as $toc) {
+	if ($toc['id'] == $lp_item_id && ($toc['type']=='quiz') ) {
 		$type_quiz = true;
 	}
-}
-
-$autostart = 'true';
-// update status,total_time from lp_item_view table when you finish the exercises in learning path
-if ($type_quiz && !empty($_REQUEST['exeId']) && isset($_GET['lp_id']) && isset($_GET['lp_item_id'])) {
-	global $src;
+}
+
+$autostart = 'true';
+// update status,total_time from lp_item_view table when you finish the exercises in learning path
+if ($type_quiz && !empty($_REQUEST['exeId']) && isset($_GET['lp_id']) && isset($_GET['lp_item_id'])) {
+	global $src;
 	$_SESSION['oLP']->items[$_SESSION['oLP']->current]->write_to_db();
-	$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-	$TBL_LP_ITEM_VIEW		= Database::get_course_table(TABLE_LP_ITEM_VIEW);
-	$TBL_LP_VIEW			= Database::get_course_table(TABLE_LP_VIEW);
-	$TBL_LP_ITEM			= Database::get_course_table(TABLE_LP_ITEM);
-	$safe_item_id      = Database::escape_string($_GET['lp_item_id']);
-    $safe_id           = Database::escape_string($_GET['lp_id']);
-	$safe_exe_id = Database::escape_string($_REQUEST['exeId']);
-
-	if ($safe_id == strval(intval($safe_id)) && $safe_item_id == strval(intval($safe_item_id))) {
-
-		$sql = 'SELECT start_date,exe_date,exe_result,exe_weighting FROM ' . $TBL_TRACK_EXERCICES . ' WHERE exe_id = '.(int)$safe_exe_id;
-		$res = Database::query($sql,__FILE__,__LINE__);
-		$row_dates = Database::fetch_array($res);
-
-		$time_start_date = convert_mysql_date($row_dates['start_date']);
-		$time_exe_date 	 = convert_mysql_date($row_dates['exe_date']);
-		$mytime = ((int)$time_exe_date-(int)$time_start_date);
-		$score = (float)$row_dates['exe_result'];
-		$max_score = (float)$row_dates['exe_weighting'];
-
-		$sql_upd_status = "UPDATE $TBL_LP_ITEM_VIEW SET status = 'completed' WHERE lp_item_id = '".(int)$safe_item_id."'
-				 AND lp_view_id = (SELECT lp_view.id FROM $TBL_LP_VIEW lp_view WHERE user_id = '".(int)$_SESSION['oLP']->user_id."' AND lp_id='".(int)$safe_id."')";
-		Database::query($sql_upd_status,__FILE__,__LINE__);
-
-		$sql_upd_max_score = "UPDATE $TBL_LP_ITEM SET max_score = '$max_score' WHERE id = '".(int)$safe_item_id."'";
-		Database::query($sql_upd_max_score,__FILE__,__LINE__);
-
-		$sql_last_attempt = "SELECT id FROM $TBL_LP_ITEM_VIEW  WHERE lp_item_id = '$safe_item_id' AND lp_view_id = '".$_SESSION['oLP']->lp_view_id."' order by id desc limit 1";
-		$res_last_attempt = Database::query($sql_last_attempt,__FILE__,__LINE__);
-		$row_last_attempt = Database::fetch_row($res_last_attempt);
-
-		if (Database::num_rows($res_last_attempt)>0) {
-			$sql_upd_score = "UPDATE $TBL_LP_ITEM_VIEW SET score = $score,total_time = $mytime WHERE id='".$row_last_attempt[0]."'";
-			Database::query($sql_upd_score,__FILE__,__LINE__);
-		}
+	$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+	$TBL_LP_ITEM_VIEW		= Database::get_course_table(TABLE_LP_ITEM_VIEW);
+	$TBL_LP_VIEW			= Database::get_course_table(TABLE_LP_VIEW);
+	$TBL_LP_ITEM			= Database::get_course_table(TABLE_LP_ITEM);
+	$safe_item_id      = Database::escape_string($_GET['lp_item_id']);
+    $safe_id           = Database::escape_string($_GET['lp_id']);
+	$safe_exe_id = Database::escape_string($_REQUEST['exeId']);
+
+	if ($safe_id == strval(intval($safe_id)) && $safe_item_id == strval(intval($safe_item_id))) {
+
+		$sql = 'SELECT start_date,exe_date,exe_result,exe_weighting FROM ' . $TBL_TRACK_EXERCICES . ' WHERE exe_id = '.(int)$safe_exe_id;
+		$res = Database::query($sql,__FILE__,__LINE__);
+		$row_dates = Database::fetch_array($res);
+
+		$time_start_date = convert_mysql_date($row_dates['start_date']);
+		$time_exe_date 	 = convert_mysql_date($row_dates['exe_date']);
+		$mytime = ((int)$time_exe_date-(int)$time_start_date);
+		$score = (float)$row_dates['exe_result'];
+		$max_score = (float)$row_dates['exe_weighting'];
+
+		$sql_upd_status = "UPDATE $TBL_LP_ITEM_VIEW SET status = 'completed' WHERE lp_item_id = '".(int)$safe_item_id."'
+				 AND lp_view_id = (SELECT lp_view.id FROM $TBL_LP_VIEW lp_view WHERE user_id = '".(int)$_SESSION['oLP']->user_id."' AND lp_id='".(int)$safe_id."')";
+		Database::query($sql_upd_status,__FILE__,__LINE__);
+
+		$sql_upd_max_score = "UPDATE $TBL_LP_ITEM SET max_score = '$max_score' WHERE id = '".(int)$safe_item_id."'";
+		Database::query($sql_upd_max_score,__FILE__,__LINE__);
+
+		$sql_last_attempt = "SELECT id FROM $TBL_LP_ITEM_VIEW  WHERE lp_item_id = '$safe_item_id' AND lp_view_id = '".$_SESSION['oLP']->lp_view_id."' order by id desc limit 1";
+		$res_last_attempt = Database::query($sql_last_attempt,__FILE__,__LINE__);
+		$row_last_attempt = Database::fetch_row($res_last_attempt);
+
+		if (Database::num_rows($res_last_attempt)>0) {
+			$sql_upd_score = "UPDATE $TBL_LP_ITEM_VIEW SET score = $score,total_time = $mytime WHERE id='".$row_last_attempt[0]."'";
+			Database::query($sql_upd_score,__FILE__,__LINE__);
+		}
 	}
 
-	if(intval($_GET['fb_type']) > 0) {
+	if(intval($_GET['fb_type']) > 0) {
 		$src = 'blank.php?msg=exerciseFinished';
-	} else {
-		$src = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?id='.Security::remove_XSS($_REQUEST['exeId']).'&origin=learnpath&learnpath_id='.Security::remove_XSS($_GET['lp_id']).'&learnpath_item_id='.Security::remove_XSS($_GET['lp_id']).'&fb_type='.Security::remove_XSS($_GET['fb_type']);
-	}
-	$autostart = 'false';
-}
-
-$_SESSION['oLP']->set_previous_item($lp_item_id);
-$nameTools = Security :: remove_XSS(api_convert_encoding($_SESSION['oLP']->get_name(), $charset, api_get_system_encoding()));
-
-$save_setting = api_get_setting("show_navigation_menu");
-global $_setting;
-$_setting['show_navigation_menu'] = 'false';
+	} else {
+		$src = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?id='.Security::remove_XSS($_REQUEST['exeId']).'&origin=learnpath&learnpath_id='.Security::remove_XSS($_GET['lp_id']).'&learnpath_item_id='.Security::remove_XSS($_GET['lp_id']).'&fb_type='.Security::remove_XSS($_GET['fb_type']);
+	}
+	$autostart = 'false';
+}
+
+$_SESSION['oLP']->set_previous_item($lp_item_id);
+$nameTools = Security :: remove_XSS(api_convert_encoding($_SESSION['oLP']->get_name(), $charset, api_get_system_encoding()));
+
+$save_setting = api_get_setting("show_navigation_menu");
+global $_setting;
+$_setting['show_navigation_menu'] = 'false';
 $scorm_css_header=true;
-$lp_theme_css=$_SESSION['oLP']->get_theme(); //sets the css theme of the LP this call is also use at the frames (toc, nav, message)
+$lp_theme_css=$_SESSION['oLP']->get_theme(); //sets the css theme of the LP this call is also use at the frames (toc, nav, message)
 
-if($_SESSION['oLP']->mode == 'fullscreen') {
+if($_SESSION['oLP']->mode == 'fullscreen') {
 	$htmlHeadXtra[] = "<script>window.open('$src','content_id','toolbar=0,location=0,status=0,scrollbars=1,resizable=1');</script>";
-	include_once('../inc/reduced_header.inc.php');
-
-	//set flag to ensure lp_header.php is loaded by this script (flag is unset in lp_header.php)
-	$_SESSION['loaded_lp_view'] = true;
-	?>
-<input type="hidden" id="old_item" name ="old_item" value="0"/>
-<input type="hidden" id="current_item_id" name ="current_item_id" value="0" />
-
-<div id="learningPathMain"  style="width:100%;height:100%;" >
-	<div id="learningPathLeftZone" style="float:left;width:280px;height:100%">
-		<!-- header -->
-		<div id="header">
-		        <div id="learningPathHeader" style="font-size:14px;">
-		            <table>
-		                <tr>
-		                    <td>
-		                        <a href="lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">
-		                        	<img src="../img/lp_arrow.gif" />
-		                        </a>
-		                    </td>
-		                    <td>
-		                        <a class="link" href="lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">
-		                        <?php echo api_convert_encoding(get_lang('CourseHomepageLink'), $charset, api_get_system_encoding()); ?></a>
-		                    </td>
-		                </tr>
-		            </table>
-		        </div>
-		</div>
+	include_once('../inc/reduced_header.inc.php');
+
+	//set flag to ensure lp_header.php is loaded by this script (flag is unset in lp_header.php)
+	$_SESSION['loaded_lp_view'] = true;
+	?>
+<input type="hidden" id="old_item" name ="old_item" value="0"/>
+<input type="hidden" id="current_item_id" name ="current_item_id" value="0" />
+
+<div id="learningPathMain"  style="width:100%;height:100%;" >
+	<div id="learningPathLeftZone" style="float:left;width:280px;height:100%">
+		<!-- header -->
+		<div id="header">
+		        <div id="learningPathHeader" style="font-size:14px;">
+		            <table>
+		                <tr>
+		                    <td>
+		                        <a href="lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">
+		                        	<img src="../img/lp_arrow.gif" />
+		                        </a>
+		                    </td>
+		                    <td>
+		                        <a class="link" href="lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">
+		                        <?php echo api_convert_encoding(get_lang('CourseHomepageLink'), $charset, api_get_system_encoding()); ?></a>
+		                    </td>
+		                </tr>
+		            </table>
+		        </div>
+		</div>
 		<!-- end header -->
-
-<!-- Image preview Layout -->
+
+<!-- Image preview Layout -->
 	<div id="author_image" name="author_image" class="lp_author_image" style="height:23%; width:100%;margin-left:5px">
-		<?php $image = '../img/lp_author_background.gif'; ?>
+		<?php $image = '../img/lp_author_background.gif'; ?>
 			<div id="preview_image" style="padding:5px;background-image: url('../img/lp_author_background.gif');background-repeat:no-repeat;height:110px">
-		       	<div style="width:100; float:left;height:105;margin:5px">
-		       		<span>
-			        <?php if ($_SESSION['oLP']->get_preview_image()!=''): ?>
-			        <img width="115" height="100" src="<?php echo api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/learning_path/images/'.$_SESSION['oLP']->get_preview_image(); ?>">
+		       	<div style="width:100; float:left;height:105;margin:5px">
+		       		<span>
+			        <?php if ($_SESSION['oLP']->get_preview_image()!=''): ?>
+			        <img width="115" height="100" src="<?php echo api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/learning_path/images/'.$_SESSION['oLP']->get_preview_image(); ?>">
 			        <?php
-						else
-						: echo Display :: display_icon('unknown_250_100.jpg', ' ');
-						endif;
-						?>
-					</span>
-		       	</div>
-
-				<div id="nav_id" name="nav_name" class="lp_nav" style="margin-left:105;height:90">
+						else
+						: echo Display :: display_icon('unknown_250_100.jpg', ' ');
+						endif;
+						?>
+					</span>
+		       	</div>
+
+				<div id="nav_id" name="nav_name" class="lp_nav" style="margin-left:105;height:90">
 			        <?php
-						$display_mode = $_SESSION['oLP']->mode;
-						$scorm_css_header = true;
-						$lp_theme_css = $_SESSION['oLP']->get_theme();
+						$display_mode = $_SESSION['oLP']->mode;
+						$scorm_css_header = true;
+						$lp_theme_css = $_SESSION['oLP']->get_theme();
 
 						//Setting up the CSS theme if exists
 
-						if (!empty ($lp_theme_css) && !empty ($mycourselptheme) && $mycourselptheme != -1 && $mycourselptheme == 1) {
-							global $lp_theme_css;
-						} else {
-							$lp_theme_css = $my_style;
-						}
+						if (!empty ($lp_theme_css) && !empty ($mycourselptheme) && $mycourselptheme != -1 && $mycourselptheme == 1) {
+							global $lp_theme_css;
+						} else {
+							$lp_theme_css = $my_style;
+						}
 
-						$progress_bar = $_SESSION['oLP']->get_progress_bar('', -1, '', true);
-						$navigation_bar = $_SESSION['oLP']->get_navigation_bar();
+						$progress_bar = $_SESSION['oLP']->get_progress_bar('', -1, '', true);
+						$navigation_bar = $_SESSION['oLP']->get_navigation_bar();
 						$mediaplayer = $_SESSION['oLP']->get_mediaplayer($autostart);
 
-						$tbl_lp_item	= Database::get_course_table(TABLE_LP_ITEM);
-						$show_audioplayer = false;
-						// getting all the information about the item
-						$sql = "SELECT audio FROM " . $tbl_lp_item . " WHERE lp_id = '" . $_SESSION['oLP']->lp_id."'";
+						$tbl_lp_item	= Database::get_course_table(TABLE_LP_ITEM);
+						$show_audioplayer = false;
+						// getting all the information about the item
+						$sql = "SELECT audio FROM " . $tbl_lp_item . " WHERE lp_id = '" . $_SESSION['oLP']->lp_id."'";
 						$res_media= Database::query($sql, __FILE__, __LINE__);
 
-						if(Database::num_rows($res_media) > 0){
-							while($row_media= Database::fetch_array($res_media)) {
+						if(Database::num_rows($res_media) > 0){
+							while($row_media= Database::fetch_array($res_media)) {
 							     if(!empty($row_media['audio'])) {$show_audioplayer = true; break;}
-							}
-						}
-					?>
+							}
+						}
+					?>
 
-					<div id="lp_navigation_elem" class="lp_navigation_elem" style="padding-left:130px;margin-top:9px;">
+					<div id="lp_navigation_elem" class="lp_navigation_elem" style="padding-left:130px;margin-top:9px;">
 						<div style="padding-top:20px;padding-bottom:50px;" ><?php echo $navigation_bar; ?></div>
-						<div style="height:20px"><?php echo $progress_bar; ?></div>
+						<div style="height:20px"><?php echo $progress_bar; ?></div>
 					</div>
 				</div>
 		</div>
 
 	</div>
-	<!-- end image preview Layout -->
-				<div id="author_name" style="position:relative;top:2px;left:0px;margin:0;padding:0;text-align:center;width:100%">
-					<?php echo $_SESSION['oLP']->get_author() ?>
-				</div>
+	<!-- end image preview Layout -->
+				<div id="author_name" style="position:relative;top:2px;left:0px;margin:0;padding:0;text-align:center;width:100%">
+					<?php echo $_SESSION['oLP']->get_author() ?>
+				</div>
 
 	<!-- media player layaout -->
-	<?php $style_media = (($show_audioplayer)?' style= "position:relative;top:10px;left:10px;margin:8px;font-size:32pt;height:20px;"':'style="height:15px"'); ?>
-	<div id="media"  <?php echo $style_media ?>>
-		<?php echo (!empty($mediaplayer))?$mediaplayer:'&nbsp;' ?>
-	</div>
-	<!-- end media player layaout -->
+	<?php $style_media = (($show_audioplayer)?' style= "position:relative;top:10px;left:10px;margin:8px;font-size:32pt;height:20px;"':'style="height:15px"'); ?>
+	<div id="media"  <?php echo $style_media ?>>
+		<?php echo (!empty($mediaplayer))?$mediaplayer:'&nbsp;' ?>
+	</div>
+	<!-- end media player layaout -->
 
 	<!-- toc layout -->
-	<div id="toc_id" name="toc_name"  style="padding:0;margin-top:20px;height:60%;width:100%">
-		<div id="learningPathToc" style="font-size:9pt;margin:0;"><?php echo $_SESSION['oLP']->get_html_toc(); ?>
-		<!-- log message layout -->
-
-		<div id="lp_log_name" name="lp_log_name" class="lp_log" style="height:50px;overflow:auto;margin:15px">
-			<div id="log_content"></div>
-			<div style="color: white;" onClick="cleanlog();">.</div>
-		</div>
-	<!-- end log message layout -->
-		</div>
-
-	</div>
-	<!-- end toc layout -->
-
-
-	</div>
+	<div id="toc_id" name="toc_name"  style="padding:0;margin-top:20px;height:60%;width:100%">
+		<div id="learningPathToc" style="font-size:9pt;margin:0;"><?php echo $_SESSION['oLP']->get_html_toc(); ?>
+		<!-- log message layout -->
+
+		<div id="lp_log_name" name="lp_log_name" class="lp_log" style="height:50px;overflow:auto;margin:15px">
+			<div id="log_content"></div>
+			<div style="color: white;" onClick="cleanlog();">.</div>
+		</div>
+	<!-- end log message layout -->
+		</div>
+
+	</div>
+	<!-- end toc layout -->
+
+
+	</div>
 <!-- end left Zone -->
-
+
 <!-- right Zone -->
-	<div id="learningPathRightZone" style="margin-left:282px;border : 0pt solid blue;height:100%">
-		<iframe id="content_id_blank" name="content_name_blank" src="blank.php" border="0" frameborder="0"  style="width:100%;height:600px" ></iframe>
-	</div>
-<!-- end right Zone -->
-
-</div>
-
-	<script language="JavaScript" type="text/javascript">
-	// Need to be called after the <head> to be sure window.oxajax is defined
-  	var dokeos_xajax_handler = window.oxajax;
-	</script>
-    <script language="JavaScript" type="text/javascript">
-	<!--
-	var leftZoneHeightOccupied = 0;
-	var rightZoneHeightOccupied = 0;
-	var initialLeftZoneHeight = 0;
-	var initialRightZoneHeight = 0;
-
-	var updateContentHeight = function() {
-		winHeight = (window.innerHeight != undefined ? window.innerHeight : document.documentElement.clientHeight);
-		newLeftZoneHeight = winHeight - leftZoneHeightOccupied;
-		newRightZoneHeight = winHeight - rightZoneHeightOccupied;
-		if (newLeftZoneHeight <= initialLeftZoneHeight) {
-			newLeftZoneHeight = initialLeftZoneHeight;
-			newRightZoneHeight = newLeftZoneHeight + leftZoneHeightOccupied - rightZoneHeightOccupied;
-		}
-		if (newRightZoneHeight <= initialRightZoneHeight) {
-			newRightZoneHeight = initialRightZoneHeight;
-			newLeftZoneHeight = newRightZoneHeight + rightZoneHeightOccupied - leftZoneHeightOccupied;
-		}
-		document.getElementById('learningPathToc').style.height = newLeftZoneHeight + 'px';
-		document.getElementById('learningPathRightZone').style.height = newRightZoneHeight + 'px';
-		document.getElementById('content_id_blank').style.height = newRightZoneHeight + 'px';
-		if (document.body.clientHeight > winHeight) {
-			document.body.style.overflow = 'auto';
-		} else {
-			document.body.style.overflow = 'hidden';
-		}
-	};
-
-	window.onload = function() {
-
-		screen_height = screen.height;
-		screen_width = screen.height;
+	<div id="learningPathRightZone" style="margin-left:282px;border : 0pt solid blue;height:100%">
+		<iframe id="content_id_blank" name="content_name_blank" src="blank.php" border="0" frameborder="0"  style="width:100%;height:600px" ></iframe>
+	</div>
+<!-- end right Zone -->
+
+</div>
+
+	<script language="JavaScript" type="text/javascript">
+	// Need to be called after the <head> to be sure window.oxajax is defined
+  	var dokeos_xajax_handler = window.oxajax;
+	</script>
+    <script language="JavaScript" type="text/javascript">
+	<!--
+	var leftZoneHeightOccupied = 0;
+	var rightZoneHeightOccupied = 0;
+	var initialLeftZoneHeight = 0;
+	var initialRightZoneHeight = 0;
+
+	var updateContentHeight = function() {
+		winHeight = (window.innerHeight != undefined ? window.innerHeight : document.documentElement.clientHeight);
+		newLeftZoneHeight = winHeight - leftZoneHeightOccupied;
+		newRightZoneHeight = winHeight - rightZoneHeightOccupied;
+		if (newLeftZoneHeight <= initialLeftZoneHeight) {
+			newLeftZoneHeight = initialLeftZoneHeight;
+			newRightZoneHeight = newLeftZoneHeight + leftZoneHeightOccupied - rightZoneHeightOccupied;
+		}
+		if (newRightZoneHeight <= initialRightZoneHeight) {
+			newRightZoneHeight = initialRightZoneHeight;
+			newLeftZoneHeight = newRightZoneHeight + rightZoneHeightOccupied - leftZoneHeightOccupied;
+		}
+		document.getElementById('learningPathToc').style.height = newLeftZoneHeight + 'px';
+		document.getElementById('learningPathRightZone').style.height = newRightZoneHeight + 'px';
+		document.getElementById('content_id_blank').style.height = newRightZoneHeight + 'px';
+		if (document.body.clientHeight > winHeight) {
+			document.body.style.overflow = 'auto';
+		} else {
+			document.body.style.overflow = 'hidden';
+		}
+	};
+
+	window.onload = function() {
+
+		screen_height = screen.height;
+		screen_width = screen.height;
 
 		document.getElementById('learningPathLeftZone').style.height = "100%";
-		document.getElementById('learningPathToc').style.height = "60%";
-		document.getElementById('learningPathToc').style.width = "100%";
+		document.getElementById('learningPathToc').style.height = "60%";
+		document.getElementById('learningPathToc').style.width = "100%";
 		document.getElementById('learningPathRightZone').style.height = "100%"
 		document.getElementById('content_id').style.height = "100%" ;
 
-		if (screen_height <= 600) {
-			document.getElementById('inner_lp_toc').style.height = "100px" ;
+		if (screen_height <= 600) {
+			document.getElementById('inner_lp_toc').style.height = "100px" ;
 			document.getElementById('learningPathLeftZone').style.height = "415px";
 		}
 
-		initialLeftZoneHeight = document.getElementById('learningPathToc').offsetHeight;
-		initialRightZoneHeight = document.getElementById('learningPathRightZone').offsetHeight;
-		docHeight = document.body.clientHeight;
-		leftZoneHeightOccupied = docHeight - initialLeftZoneHeight;
-		rightZoneHeightOccupied = docHeight - initialRightZoneHeight;
-		document.body.style.overflow = 'hidden';
-		updateContentHeight();
-	}
-
-	window.onresize = updateContentHeight;
-	-->
-	</script>
-
-<?php
-}
-else
+		initialLeftZoneHeight = document.getElementById('learningPathToc').offsetHeight;
+		initialRightZoneHeight = document.getElementById('learningPathRightZone').offsetHeight;
+		docHeight = document.body.clientHeight;
+		leftZoneHeightOccupied = docHeight - initialLeftZoneHeight;
+		rightZoneHeightOccupied = docHeight - initialRightZoneHeight;
+		document.body.style.overflow = 'hidden';
+		updateContentHeight();
+	}
+
+	window.onresize = updateContentHeight;
+	-->
+	</script>
+
+<?php
+}
+else
 {
-	include_once('../inc/reduced_header.inc.php');
-	//$displayAudioRecorder = (api_get_setting('service_visio','active')=='true') ? true : false;
-	//check if audio recorder needs to be in studentview
-	$course_id=$_SESSION["_course"]["id"];
-	if($_SESSION["status"][$course_id]==5)
-	{
-		$audio_recorder_studentview = true;
-	}
-	else
-	{
-		$audio_recorder_studentview = false;
-	}
-	//set flag to ensure lp_header.php is loaded by this script (flag is unset in lp_header.php)
+	include_once('../inc/reduced_header.inc.php');
+	//$displayAudioRecorder = (api_get_setting('service_visio','active')=='true') ? true : false;
+	//check if audio recorder needs to be in studentview
+	$course_id=$_SESSION["_course"]["id"];
+	if($_SESSION["status"][$course_id]==5)
+	{
+		$audio_recorder_studentview = true;
+	}
+	else
+	{
+		$audio_recorder_studentview = false;
+	}
+	//set flag to ensure lp_header.php is loaded by this script (flag is unset in lp_header.php)
 	$_SESSION['loaded_lp_view'] = true;
-	?>
-
-	<input type="hidden" id="old_item" name ="old_item" value="0"/>
-	<input type="hidden" id="current_item_id" name ="current_item_id" value="0" />
-
-<div id="learningPathMain"  style="width:100%;height:100%;" >
-
-	<div id="learningPathLeftZone" style="float:left;width:280px;height:100%">
-
-		<!-- header -->
-		<div id="header">
-		        <div id="learningPathHeader" style="font-size:14px;">
-		            <table>
-		                <tr>
-		                    <td>
-		                        <a href="lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();"><img src="../img/lp_arrow.gif" /></a>
-		                    </td>
-		                    <td>
-		                        <a class="link" href="lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">
-		                        <?php echo api_convert_encoding(get_lang('CourseHomepageLink'), $charset, api_get_system_encoding()); ?></a>
-		                    </td>
-		                </tr>
-		            </table>
-		        </div>
-		</div>
+	?>
+
+	<input type="hidden" id="old_item" name ="old_item" value="0"/>
+	<input type="hidden" id="current_item_id" name ="current_item_id" value="0" />
+
+<div id="learningPathMain"  style="width:100%;height:100%;" >
+
+	<div id="learningPathLeftZone" style="float:left;width:280px;height:100%">
+
+		<!-- header -->
+		<div id="header">
+		        <div id="learningPathHeader" style="font-size:14px;">
+		            <table>
+		                <tr>
+		                    <td>
+		                        <a href="lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();"><img src="../img/lp_arrow.gif" /></a>
+		                    </td>
+		                    <td>
+		                        <a class="link" href="lp_controller.php?action=return_to_course_homepage" target="_self" onclick="window.parent.API.save_asset();">
+		                        <?php echo api_convert_encoding(get_lang('CourseHomepageLink'), $charset, api_get_system_encoding()); ?></a>
+		                    </td>
+		                </tr>
+		            </table>
+		        </div>
+		</div>
 		<!-- end header -->
-
-<!-- Image preview Layout -->
+
+<!-- Image preview Layout -->
 	<div id="author_image" name="author_image" class="lp_author_image" style="height:23%; width:100%;margin-left:5px;">
-		<?php $image = '../img/lp_author_background.gif'; ?>
-
-			<div id="preview_image" style="padding:5px;background-image: url('../img/lp_author_background.gif');background-repeat:no-repeat;height:110px">
-
-		       	<div style="width:100; float:left;height:105;margin:5px">
-		       		<span style="width:104px; height:96px; float:left; vertical-align:bottom;">
-			        <center><?php if ($_SESSION['oLP']->get_preview_image()!=''): ?>
-			        <?php
-			        	$picture = getimagesize(api_get_path(SYS_COURSE_PATH).api_get_course_path().'/upload/learning_path/images/'.$_SESSION['oLP']->get_preview_image());
-			        	if($picture['1'] < 96) $style = ' style="padding-top:'.((94 -$picture['1'])/2).'px;" ';
-			        	$size = ($picture['0'] > 104 && $picture['1'] > 96 )? ' width="104" height="96" ': $style;
+		<?php $image = '../img/lp_author_background.gif'; ?>
+
+			<div id="preview_image" style="padding:5px;background-image: url('../img/lp_author_background.gif');background-repeat:no-repeat;height:110px">
+
+		       	<div style="width:100; float:left;height:105;margin:5px">
+		       		<span style="width:104px; height:96px; float:left; vertical-align:bottom;">
+			        <center><?php if ($_SESSION['oLP']->get_preview_image()!=''): ?>
+			        <?php
+			        	$picture = getimagesize(api_get_path(SYS_COURSE_PATH).api_get_course_path().'/upload/learning_path/images/'.$_SESSION['oLP']->get_preview_image());
+			        	if($picture['1'] < 96) $style = ' style="padding-top:'.((94 -$picture['1'])/2).'px;" ';
+			        	$size = ($picture['0'] > 104 && $picture['1'] > 96 )? ' width="104" height="96" ': $style;
 			        	$flie = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/learning_path/images/'.$_SESSION['oLP']->get_preview_image();
 			        	echo '<img '.$size.' src="'.$flie.'">';
-			        ?>
+			        ?>
 			        <?php
-						else
-						: echo Display :: display_icon('unknown_250_100.jpg', ' ');
-						endif;
-						?></center>
-					</span>
-		       	</div>
-
-				<div id="nav_id" name="nav_name" class="lp_nav" style="margin-left:105;height:90">
+						else
+						: echo Display :: display_icon('unknown_250_100.jpg', ' ');
+						endif;
+						?></center>
+					</span>
+		       	</div>
+
+				<div id="nav_id" name="nav_name" class="lp_nav" style="margin-left:105;height:90">
 			        <?php
-						$display_mode = $_SESSION['oLP']->mode;
-						$scorm_css_header = true;
-						$lp_theme_css = $_SESSION['oLP']->get_theme();
-
-						//Setting up the CSS theme if exists
-						if (!empty ($lp_theme_css) && !empty ($mycourselptheme) && $mycourselptheme != -1 && $mycourselptheme == 1) {
-							global $lp_theme_css;
-						} else {
-							$lp_theme_css = $my_style;
-						}
-
-						$progress_bar = $_SESSION['oLP']->get_progress_bar('', -1, '', true);
-						$navigation_bar = $_SESSION['oLP']->get_navigation_bar();
-						$mediaplayer = $_SESSION['oLP']->get_mediaplayer($autostart);
-
-						$tbl_lp_item	= Database::get_course_table(TABLE_LP_ITEM);
-						$show_audioplayer = false;
-						// getting all the information about the item
-						$sql = "SELECT audio FROM " . $tbl_lp_item . " WHERE lp_id = '" . $_SESSION['oLP']->lp_id."'";
+						$display_mode = $_SESSION['oLP']->mode;
+						$scorm_css_header = true;
+						$lp_theme_css = $_SESSION['oLP']->get_theme();
+
+						//Setting up the CSS theme if exists
+						if (!empty ($lp_theme_css) && !empty ($mycourselptheme) && $mycourselptheme != -1 && $mycourselptheme == 1) {
+							global $lp_theme_css;
+						} else {
+							$lp_theme_css = $my_style;
+						}
+
+						$progress_bar = $_SESSION['oLP']->get_progress_bar('', -1, '', true);
+						$navigation_bar = $_SESSION['oLP']->get_navigation_bar();
+						$mediaplayer = $_SESSION['oLP']->get_mediaplayer($autostart);
+
+						$tbl_lp_item	= Database::get_course_table(TABLE_LP_ITEM);
+						$show_audioplayer = false;
+						// getting all the information about the item
+						$sql = "SELECT audio FROM " . $tbl_lp_item . " WHERE lp_id = '" . $_SESSION['oLP']->lp_id."'";
 						$res_media= Database::query($sql, __FILE__, __LINE__);
 
-						if(Database::num_rows($res_media) > 0){
-							while($row_media= Database::fetch_array($res_media)) {
+						if(Database::num_rows($res_media) > 0){
+							while($row_media= Database::fetch_array($res_media)) {
 							     if(!empty($row_media['audio'])) {$show_audioplayer = true; break;}
-							}
-						}
-					?>
+							}
+						}
+					?>
 
-					<div id="lp_navigation_elem" class="lp_navigation_elem" style="padding-left:130px;margin-top:9px;">
+					<div id="lp_navigation_elem" class="lp_navigation_elem" style="padding-left:130px;margin-top:9px;">
 						<div style="padding-top:15px;padding-bottom:50px;" ><?php echo $navigation_bar; ?></div>
-						<div style="height:20px"><?php echo $progress_bar; ?></div>
+						<div style="height:20px"><?php echo $progress_bar; ?></div>
 					</div>
 				</div>
 		</div>
 
 	</div>
-	<!-- end image preview Layout -->
-				<div id="author_name" style="position:relative;top:2px;left:0px;margin:0;padding:0;text-align:center;width:100%">
-					<?php echo $_SESSION['oLP']->get_author() ?>
-				</div>
+	<!-- end image preview Layout -->
+				<div id="author_name" style="position:relative;top:2px;left:0px;margin:0;padding:0;text-align:center;width:100%">
+					<?php echo $_SESSION['oLP']->get_author() ?>
+				</div>
 
 	<!-- media player layaout -->
-	<?php $style_media = (($show_audioplayer)?' style= "position:relative;top:10px;left:10px;margin:8px;font-size:32pt;height:20px;"':'style="height:15px"'); ?>
-	<div id="media"  <?php echo $style_media ?>>
-		<?php echo (!empty($mediaplayer))?$mediaplayer:'&nbsp;' ?>
-	</div>
-	<!-- end media player layaout -->
+	<?php $style_media = (($show_audioplayer)?' style= "position:relative;top:10px;left:10px;margin:8px;font-size:32pt;height:20px;"':'style="height:15px"'); ?>
+	<div id="media"  <?php echo $style_media ?>>
+		<?php echo (!empty($mediaplayer))?$mediaplayer:'&nbsp;' ?>
+	</div>
+	<!-- end media player layaout -->
 
 	<!-- toc layout -->
-	<div id="toc_id" name="toc_name"  style="padding:0;margin-top:20px;height:60%;width:100%">
-		<div id="learningPathToc" style="font-size:9pt;margin:0;"><?php echo $_SESSION['oLP']->get_html_toc(); ?>
-		<!-- log message layout -->
-
-		<div id="lp_log_name" name="lp_log_name" class="lp_log" style="height:50px;overflow:auto;margin:15px">
-			<div id="log_content"></div>
-			<div style="color: white;" onClick="cleanlog();">.</div>
-		</div>
-	<!-- end log message layout -->
-		</div>
-
-	</div>
-	<!-- end toc layout -->
-
-
-	</div>
+	<div id="toc_id" name="toc_name"  style="padding:0;margin-top:20px;height:60%;width:100%">
+		<div id="learningPathToc" style="font-size:9pt;margin:0;"><?php echo $_SESSION['oLP']->get_html_toc(); ?>
+		<!-- log message layout -->
+
+		<div id="lp_log_name" name="lp_log_name" class="lp_log" style="height:50px;overflow:auto;margin:15px">
+			<div id="log_content"></div>
+			<div style="color: white;" onClick="cleanlog();">.</div>
+		</div>
+	<!-- end log message layout -->
+		</div>
+
+	</div>
+	<!-- end toc layout -->
+
+
+	</div>
 <!-- end left Zone -->
-
+
 <!-- right Zone -->
-	<div id="learningPathRightZone" style="margin-left:282px;height:100%">
-		<iframe id="content_id" name="content_name" src="<?php echo $src; ?>" border="0" frameborder="0"  style="width:100%;height:600px" ></iframe>
-	</div>
-<!-- end right Zone -->
-
-</div>
-
-    <script language="JavaScript" type="text/javascript">
-	// Need to be called after the <head> to be sure window.oxajax is defined
-  	var dokeos_xajax_handler = window.oxajax;
-	</script>
-    <script language="JavaScript" type="text/javascript">
-	<!--
-	var leftZoneHeightOccupied = 0;
-	var rightZoneHeightOccupied = 0;
-	var initialLeftZoneHeight = 0;
-	var initialRightZoneHeight = 0;
-
-	var updateContentHeight = function() {
-		winHeight = (window.innerHeight != undefined ? window.innerHeight : document.documentElement.clientHeight);
-		newLeftZoneHeight = winHeight - leftZoneHeightOccupied;
-		newRightZoneHeight = winHeight - rightZoneHeightOccupied;
-		if (newLeftZoneHeight <= initialLeftZoneHeight) {
-			newLeftZoneHeight = initialLeftZoneHeight;
-			newRightZoneHeight = newLeftZoneHeight + leftZoneHeightOccupied - rightZoneHeightOccupied;
-		}
-		if (newRightZoneHeight <= initialRightZoneHeight) {
-			newRightZoneHeight = initialRightZoneHeight;
-			newLeftZoneHeight = newRightZoneHeight + rightZoneHeightOccupied - leftZoneHeightOccupied;
-		}
-		document.getElementById('learningPathToc').style.height = newLeftZoneHeight + 'px';
-		document.getElementById('learningPathRightZone').style.height = newRightZoneHeight + 'px';
-		document.getElementById('content_id').style.height = newRightZoneHeight + 'px';
-		if (document.body.clientHeight > winHeight) {
-			document.body.style.overflow = 'auto';
-		} else {
-			document.body.style.overflow = 'hidden';
-		}
-	};
-
-	window.onload = function() {
-
-		screen_height = screen.height;
-		screen_width = screen.height;
+	<div id="learningPathRightZone" style="margin-left:282px;height:100%">
+		<iframe id="content_id" name="content_name" src="<?php echo $src; ?>" border="0" frameborder="0"  style="width:100%;height:600px" ></iframe>
+	</div>
+<!-- end right Zone -->
+
+</div>
+
+    <script language="JavaScript" type="text/javascript">
+	// Need to be called after the <head> to be sure window.oxajax is defined
+  	var dokeos_xajax_handler = window.oxajax;
+	</script>
+    <script language="JavaScript" type="text/javascript">
+	<!--
+	var leftZoneHeightOccupied = 0;
+	var rightZoneHeightOccupied = 0;
+	var initialLeftZoneHeight = 0;
+	var initialRightZoneHeight = 0;
+
+	var updateContentHeight = function() {
+		winHeight = (window.innerHeight != undefined ? window.innerHeight : document.documentElement.clientHeight);
+		newLeftZoneHeight = winHeight - leftZoneHeightOccupied;
+		newRightZoneHeight = winHeight - rightZoneHeightOccupied;
+		if (newLeftZoneHeight <= initialLeftZoneHeight) {
+			newLeftZoneHeight = initialLeftZoneHeight;
+			newRightZoneHeight = newLeftZoneHeight + leftZoneHeightOccupied - rightZoneHeightOccupied;
+		}
+		if (newRightZoneHeight <= initialRightZoneHeight) {
+			newRightZoneHeight = initialRightZoneHeight;
+			newLeftZoneHeight = newRightZoneHeight + rightZoneHeightOccupied - leftZoneHeightOccupied;
+		}
+		document.getElementById('learningPathToc').style.height = newLeftZoneHeight + 'px';
+		document.getElementById('learningPathRightZone').style.height = newRightZoneHeight + 'px';
+		document.getElementById('content_id').style.height = newRightZoneHeight + 'px';
+		if (document.body.clientHeight > winHeight) {
+			document.body.style.overflow = 'auto';
+		} else {
+			document.body.style.overflow = 'hidden';
+		}
+	};
+
+	window.onload = function() {
+
+		screen_height = screen.height;
+		screen_width = screen.height;
 
 		document.getElementById('learningPathLeftZone').style.height = "100%";
-		document.getElementById('learningPathToc').style.height = "60%";
-		document.getElementById('learningPathToc').style.width = "100%";
+		document.getElementById('learningPathToc').style.height = "60%";
+		document.getElementById('learningPathToc').style.width = "100%";
 		document.getElementById('learningPathRightZone').style.height = "100%"
 		document.getElementById('content_id').style.height = "100%" ;
 
-		if (screen_height <= 600) {
-			document.getElementById('inner_lp_toc').style.height = "100px" ;
+		if (screen_height <= 600) {
+			document.getElementById('inner_lp_toc').style.height = "100px" ;
 			document.getElementById('learningPathLeftZone').style.height = "415px";
 		}
 
-		initialLeftZoneHeight = document.getElementById('learningPathToc').offsetHeight;
-		initialRightZoneHeight = document.getElementById('learningPathRightZone').offsetHeight;
-		docHeight = document.body.clientHeight;
-		leftZoneHeightOccupied = docHeight - initialLeftZoneHeight;
-		rightZoneHeightOccupied = docHeight - initialRightZoneHeight;
-		document.body.style.overflow = 'hidden';
-		updateContentHeight();
-	}
-
-	window.onresize = updateContentHeight;
-	-->
-	</script>
-
-<?php
-	/*
-	==============================================================================
-	  FOOTER
-	==============================================================================
-	*/
-	//Display::display_footer();
-}
-//restore global setting
-$_setting['show_navigation_menu'] = $save_setting;
-?>
+		initialLeftZoneHeight = document.getElementById('learningPathToc').offsetHeight;
+		initialRightZoneHeight = document.getElementById('learningPathRightZone').offsetHeight;
+		docHeight = document.body.clientHeight;
+		leftZoneHeightOccupied = docHeight - initialLeftZoneHeight;
+		rightZoneHeightOccupied = docHeight - initialRightZoneHeight;
+		document.body.style.overflow = 'hidden';
+		updateContentHeight();
+	}
+
+	window.onresize = updateContentHeight;
+	-->
+	</script>
+
+<?php
+	/*
+	==============================================================================
+	  FOOTER
+	==============================================================================
+	*/
+	//Display::display_footer();
+}
+//restore global setting
+$_setting['show_navigation_menu'] = $save_setting;
+?>

+ 175 - 175
main/newscorm/lp_view_item.php

@@ -1,209 +1,209 @@
-<?php
-/*
+<?php
+/*
 ==============================================================================
-	Dokeos - elearning and course management software
+	Dokeos - elearning and course management software
 
-	Copyright (c) 2004-2009 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Patrick Cool
-	Copyright (c) Denes Nagy
-	Copyright (c) Yannick Warnier
+	Copyright (c) 2004-2009 Dokeos SPRL
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Patrick Cool
+	Copyright (c) Denes Nagy
+	Copyright (c) Yannick Warnier
 
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
+	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.
+	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.
+	See the GNU General Public License for more details.
 
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
 ==============================================================================
-*/
-/**
+*/
+/**
 ==============================================================================
-* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
-*
-* @author Patrick Cool
-* @author Denes Nagy
-* @author Roan Embrechts, refactoring and code cleaning
-* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
-* @package dokeos.learnpath
+* This is a learning path creation and player tool in Dokeos - previously learnpath_handler.php
+*
+* @author Patrick Cool
+* @author Denes Nagy
+* @author Roan Embrechts, refactoring and code cleaning
+* @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
+* @package dokeos.learnpath
 ==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
 */
-$_SESSION['whereami'] = 'lp/build';
-if(isset($_SESSION['oLP']) && isset($_GET['id']))
-{
-	$_SESSION['oLP'] -> current = intval($_GET['id']);
-}
-$this_section=SECTION_COURSES;
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
 */
-//the main_api.lib.php, database.lib.php and display.lib.php
-//libraries are included by default
-
-include('learnpath_functions.inc.php');
-//include('../resourcelinker/resourcelinker.inc.php');
-include('resourcelinker.inc.php');
-//rewrite the language file, sadly overwritten by resourcelinker.inc.php
+$_SESSION['whereami'] = 'lp/build';
+if(isset($_SESSION['oLP']) && isset($_GET['id']))
+{
+	$_SESSION['oLP'] -> current = intval($_GET['id']);
+}
+$this_section=SECTION_COURSES;
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+//the main_api.lib.php, database.lib.php and display.lib.php
+//libraries are included by default
+
+include('learnpath_functions.inc.php');
+//include('../resourcelinker/resourcelinker.inc.php');
+include('resourcelinker.inc.php');
+//rewrite the language file, sadly overwritten by resourcelinker.inc.php
 // name of the language file that needs to be included
-$language_file = "learnpath";
-
-/*
------------------------------------------------------------
-	Header and action code
------------------------------------------------------------
+$language_file = "learnpath";
+
+/*
+-----------------------------------------------------------
+	Header and action code
+-----------------------------------------------------------
 */
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
 */
-$is_allowed_to_edit = api_is_allowed_to_edit();
-
-$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
-
-$isStudentView  = (empty($_REQUEST['isStudentView'])?0:(int) $_REQUEST['isStudentView']);
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-/*
-$chapter_id     = $_GET['chapter_id'];
-$title          = $_POST['title'];
-$description   = $_POST['description'];
-$Submititem     = $_POST['Submititem'];
-$action         = $_REQUEST['action'];
-$id             = (int) $_REQUEST['id'];
-$type           = $_REQUEST['type'];
-$direction      = $_REQUEST['direction'];
-$moduleid       = $_REQUEST['moduleid'];
-$prereq         = $_REQUEST['prereq'];
-$type           = $_REQUEST['type'];
-*/
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-// using the resource linker as a tool for adding resources to the learning path
-if ($action=="add" and $type=="learnpathitem")
-{
-	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
-}
-if ( (! $is_allowed_to_edit) or ($isStudentView) )
-{
-	error_log('New LP - User not authorized in lp_view_item.php');
-	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
-}
-//from here on, we are admin because of the previous condition, so don't check anymore
-
+$is_allowed_to_edit = api_is_allowed_to_edit();
+
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+$tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
+
+$isStudentView  = (empty($_REQUEST['isStudentView'])?0:(int) $_REQUEST['isStudentView']);
+$learnpath_id   = (int) $_REQUEST['lp_id'];
+/*
+$chapter_id     = $_GET['chapter_id'];
+$title          = $_POST['title'];
+$description   = $_POST['description'];
+$Submititem     = $_POST['Submititem'];
+$action         = $_REQUEST['action'];
+$id             = (int) $_REQUEST['id'];
+$type           = $_REQUEST['type'];
+$direction      = $_REQUEST['direction'];
+$moduleid       = $_REQUEST['moduleid'];
+$prereq         = $_REQUEST['prereq'];
+$type           = $_REQUEST['type'];
+*/
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+// using the resource linker as a tool for adding resources to the learning path
+if ($action=="add" and $type=="learnpathitem")
+{
+	 $htmlHeadXtra[] = "<script language='JavaScript' type='text/javascript'> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
+}
+if ( (! $is_allowed_to_edit) or ($isStudentView) )
+{
+	error_log('New LP - User not authorized in lp_view_item.php');
+	header('location:lp_controller.php?action=view&lp_id='.$learnpath_id);
+}
+//from here on, we are admin because of the previous condition, so don't check anymore
+
 $sql_query = "SELECT * FROM $tbl_lp WHERE id = $learnpath_id";
-$result=Database::query($sql_query);
+$result=Database::query($sql_query);
 $therow=Database::fetch_array($result);
-
-//$admin_output = '';
-/*
------------------------------------------------------------
-	Course admin section
-	- all the functions not available for students - always available in this case (page only shown to admin)
------------------------------------------------------------
+
+//$admin_output = '';
+/*
+-----------------------------------------------------------
+	Course admin section
+	- all the functions not available for students - always available in this case (page only shown to admin)
+-----------------------------------------------------------
 */
-/*==================================================
-			SHOWING THE ADMIN TOOLS
- ==================================================*/
-
-
-
-/*==================================================
-	prerequisites setting end
+/*==================================================
+			SHOWING THE ADMIN TOOLS
  ==================================================*/
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+
+
+
+/*==================================================
+	prerequisites setting end
+ ==================================================*/
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
-$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
-
-//Theme calls
-$show_learn_path=true;
-$lp_theme_css=$_SESSION['oLP']->get_theme();
-
-Display::display_header(null,'Path');
-//api_display_tool_title($therow['name']);
-
-$suredel = trim(get_lang('AreYouSureToDelete'));
-//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
-?>
-<script type='text/javascript'>
-/* <![CDATA[ */
-
-function stripslashes(str) {
-	str=str.replace(/\\'/g,'\'');
-	str=str.replace(/\\"/g,'"');
-	str=str.replace(/\\\\/g,'\\');
-	str=str.replace(/\\0/g,'\0');
-	return str;
-}
-function confirmation(name) {
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+$interbreadcrumb[]= array ("url"=>"lp_controller.php?action=list", "name"=> get_lang("_learning_path"));
+$interbreadcrumb[]= array ("url"=>api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
+
+//Theme calls
+$show_learn_path=true;
+$lp_theme_css=$_SESSION['oLP']->get_theme();
+
+Display::display_header(null,'Path');
+//api_display_tool_title($therow['name']);
+
+$suredel = trim(get_lang('AreYouSureToDelete'));
+//$suredelstep = trim(get_lang('AreYouSureToDeleteSteps'));
+?>
+<script type='text/javascript'>
+/* <![CDATA[ */
+
+function stripslashes(str) {
+	str=str.replace(/\\'/g,'\'');
+	str=str.replace(/\\"/g,'"');
+	str=str.replace(/\\\\/g,'\\');
+	str=str.replace(/\\0/g,'\0');
+	return str;
+}
+function confirmation(name) {
 	name=stripslashes(name);
-	if (confirm("<?php echo $suredel; ?> " + name + " ?")) {
-		return true;
-	} else {
-		return false;
+	if (confirm("<?php echo $suredel; ?> " + name + " ?")) {
+		return true;
+	} else {
+		return false;
 	}
-}
-</script>
-<?php
-
-//echo $admin_output;
-
-/*
------------------------------------------------------------
-	DISPLAY SECTION
------------------------------------------------------------
-*/
-
+}
+</script>
+<?php
+
+//echo $admin_output;
+
+/*
+-----------------------------------------------------------
+	DISPLAY SECTION
+-----------------------------------------------------------
+*/
+
 echo $_SESSION['oLP']->build_action_menu();
-echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
+echo '<table cellpadding="0" cellspacing="0" class="lp_build">';
 	echo '<tr>';
 		echo '<td class="tree">';
 			echo '<div class="lp_tree">';
-				//build the tree with the menu items in it
+				//build the tree with the menu items in it
 				echo $_SESSION['oLP']->build_tree();
 			echo '</div>';
-		echo '</td>';
+		echo '</td>';
 		echo '<td class="workspace">';
 			echo $_SESSION['oLP']->display_item((isset($new_item_id)) ? $new_item_id : $_GET['id']);
 		echo '</td>';
 	echo '</tr>';
-echo '</table>';
-
-/*
-==============================================================================
+echo '</table>';
+
+/*
+==============================================================================
 		FOOTER
-==============================================================================
+==============================================================================
 */
-Display::display_footer();
+Display::display_footer();
 ?>

+ 128 - 128
main/newscorm/openoffice_document.class.php

@@ -1,154 +1,154 @@
-<?php //$id:$
-/**
- * Defines the OpenofficeDocument class, which is meant as a mother class
- * to help in the conversion of Office documents to learning paths
- * @package dokeos.learnpath
- * @author	Eric Marguin <eric.marguin@dokeos.com>
- * @license	GNU/GPL - See Dokeos license directory for details
- */
-/**
- * Defines the "OpenofficeDocument" child of class "learnpath"
- * @package dokeos.learnpath.aicc
- */
-
-abstract class OpenofficeDocument extends learnpath {
-
-
-	public $first_item = 0;
-    public $original_charset = 'utf-8';
-    public $original_locale = 'en_US.UTF-8';
-
-	/**
-	 * Class constructor. Based on the parent constructor.
-	 * @param	string	Course code
-	 * @param	integer	Learnpath ID in DB
-	 * @param	integer	User ID
-	 */
-    function OpenofficeDocument($course_code=null,$resource_id=null,$user_id=null) {
-    	if($this->debug>0){error_log('In OpenofficeDocument::OpenofficeDocument()',0);}
-    	if(!empty($course_code) and !empty($resource_id) and !empty($user_id))
-    	{
-    		parent::learnpath($course_code, $resource_id, $user_id);
-    	}else{
-    		//do nothing but still build the presentation object
-    	}
-    }
-
-    function convert_document($file, $action_after_conversion='make_lp'){
-
-    	global $_course, $_user, $_configuration;
-
-    	$this->file_name = (strrpos($file['name'],'.')>0 ? substr($file['name'], 0, strrpos($file['name'],'.')) : $file['name']);
-    	$this->file_name = remove_accents($this->file_name);
+<?php //$id:$
+/**
+ * Defines the OpenofficeDocument class, which is meant as a mother class
+ * to help in the conversion of Office documents to learning paths
+ * @package dokeos.learnpath
+ * @author	Eric Marguin <eric.marguin@dokeos.com>
+ * @license	GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * Defines the "OpenofficeDocument" child of class "learnpath"
+ * @package dokeos.learnpath.aicc
+ */
+
+abstract class OpenofficeDocument extends learnpath {
+
+
+	public $first_item = 0;
+    public $original_charset = 'utf-8';
+    public $original_locale = 'en_US.UTF-8';
+
+	/**
+	 * Class constructor. Based on the parent constructor.
+	 * @param	string	Course code
+	 * @param	integer	Learnpath ID in DB
+	 * @param	integer	User ID
+	 */
+    function OpenofficeDocument($course_code=null,$resource_id=null,$user_id=null) {
+    	if($this->debug>0){error_log('In OpenofficeDocument::OpenofficeDocument()',0);}
+    	if(!empty($course_code) and !empty($resource_id) and !empty($user_id))
+    	{
+    		parent::learnpath($course_code, $resource_id, $user_id);
+    	}else{
+    		//do nothing but still build the presentation object
+    	}
+    }
+
+    function convert_document($file, $action_after_conversion='make_lp'){
+
+    	global $_course, $_user, $_configuration;
+
+    	$this->file_name = (strrpos($file['name'],'.')>0 ? substr($file['name'], 0, strrpos($file['name'],'.')) : $file['name']);
+    	$this->file_name = remove_accents($this->file_name);
 		$this->file_name = replace_dangerous_char($this->file_name,'strict');
-		$this->file_name = strtolower($this->file_name);
-
-		$visio_dir = ($action_after_conversion=='add_docs_to_visio')?VIDEOCONF_UPLOAD_PATH:'';
+		$this->file_name = strtolower($this->file_name);
 
-		$this->file_path = $visio_dir.'/'.$this->file_name.'.'.pathinfo($file['name'],PATHINFO_EXTENSION);
-
-		$dir_name = $visio_dir.'/'.$this->file_name;
+		$visio_dir = ($action_after_conversion=='add_docs_to_visio')?VIDEOCONF_UPLOAD_PATH:'';
+
+		$this->file_path = $visio_dir.'/'.$this->file_name.'.'.pathinfo($file['name'],PATHINFO_EXTENSION);
+
+		$dir_name = $visio_dir.'/'.$this->file_name;
 
 
 		//create the directory
-		$this->base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-
-
-		$this->created_dir = create_unexisting_directory($_course,$_user['user_id'],0,0,$this->base_work_dir,$dir_name);
-
-		move_uploaded_file($file['tmp_name'],$this->base_work_dir.'/'.$this->file_path);
-
-
-		$perm = api_get_setting('permissions_for_new_files');
-
-		/*
-		$classpath = '-cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar';
-		if(isset($_ENV['OS']) && strpos($_ENV['OS'],'Windows') !== false)
-		{
-			$classpath = str_replace(':',';',$classpath);
-		}
-		if(isset($_ENV['OS']) && strpos($_ENV['OS'],'Windows') !== false)
-		{
-			$cmd = 'cd '.str_replace('/','\\',api_get_path(SYS_PATH).'main/inc/lib/ppt2png ').$classpath.' DokeosConverter';
-		}
-		else
-		{
-			$cmd = 'cd '.api_get_path(SYS_PATH).'main/inc/lib/ppt2png && java '.$classpath.' DokeosConverter';
-		}
-		$cmd .=  ' -p '.api_get_setting('service_ppt2lp','port');
-		*/
-		if (IS_WINDOWS_OS) // IS_WINDOWS_OS has been defined in main_api.lib.php
-		{
+		$this->base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
+
+
+		$this->created_dir = create_unexisting_directory($_course,$_user['user_id'],0,0,$this->base_work_dir,$dir_name);
+
+		move_uploaded_file($file['tmp_name'],$this->base_work_dir.'/'.$this->file_path);
+
+
+		$perm = api_get_setting('permissions_for_new_files');
+
+		/*
+		$classpath = '-cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar';
+		if(isset($_ENV['OS']) && strpos($_ENV['OS'],'Windows') !== false)
+		{
+			$classpath = str_replace(':',';',$classpath);
+		}
+		if(isset($_ENV['OS']) && strpos($_ENV['OS'],'Windows') !== false)
+		{
+			$cmd = 'cd '.str_replace('/','\\',api_get_path(SYS_PATH).'main/inc/lib/ppt2png ').$classpath.' DokeosConverter';
+		}
+		else
+		{
+			$cmd = 'cd '.api_get_path(SYS_PATH).'main/inc/lib/ppt2png && java '.$classpath.' DokeosConverter';
+		}
+		$cmd .=  ' -p '.api_get_setting('service_ppt2lp','port');
+		*/
+		if (IS_WINDOWS_OS) // IS_WINDOWS_OS has been defined in main_api.lib.php
+		{
 			$converter_path = str_replace('/','\\',api_get_path(SYS_PATH).'main/inc/lib/ppt2png');
 			$class_path = $converter_path.';'.$converter_path.'/jodconverter-2.2.1.jar;'.$converter_path.'/jodconverter-cli-2.2.1.jar';
-
-			//$cmd = 'java -cp "'.$class_path.'" DokeosConverter';
-			$cmd = 'java -Dfile.encoding=UTF-8 -cp "'.$class_path.'" DokeosConverter';
-		}
-		else
-		{
-			$converter_path = api_get_path(SYS_PATH).'main/inc/lib/ppt2png';
-
-			//$class_path = '-cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar';
-			$class_path = ' -Dfile.encoding=UTF-8 -cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar';
-
-			$cmd = 'cd '.$converter_path.' && java '.$class_path.' DokeosConverter';
-		}
+
+			//$cmd = 'java -cp "'.$class_path.'" DokeosConverter';
+			$cmd = 'java -Dfile.encoding=UTF-8 -cp "'.$class_path.'" DokeosConverter';
+		}
+		else
+		{
+			$converter_path = api_get_path(SYS_PATH).'main/inc/lib/ppt2png';
+
+			//$class_path = '-cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar';
+			$class_path = ' -Dfile.encoding=UTF-8 -cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar';
+
+			$cmd = 'cd '.$converter_path.' && java '.$class_path.' DokeosConverter';
+		}
 		$cmd .=  ' -p '.api_get_setting('service_ppt2lp','port');
 
-		// call to the function implemented by child
+		// call to the function implemented by child
 		$cmd .= $this -> add_command_parameters();
-
-		// to allow openoffice to manipulate docs.
-		@chmod ($this->base_work_dir.$this->created_dir,0777);
-		@chmod ($this->base_work_dir.$this->file_path,0777);
-
-		$locale = $this->original_locale; // TODO : improve it because we're not sure this locale is present everywhere
-		putenv('LC_ALL='.$locale);
-		$files = array(); $return = 0;
-		$shell = exec($cmd, $files, $return);
-		if($return != 0) { //if the java application returns an error code
-			switch($return)
-			{
-				// can't connect to openoffice
-				case 1 : $this->error = get_lang('CannotConnectToOpenOffice');break;
-
-				// conversion failed in openoffice
-				case 2 : $this->error = get_lang('OogieConversionFailed');break;
-
-				// conversion can't be launch because command failed
-				case 255 : $this->error = get_lang('OogieUnknownError');break;
-			}
+
+		// to allow openoffice to manipulate docs.
+		@chmod ($this->base_work_dir.$this->created_dir,0777);
+		@chmod ($this->base_work_dir.$this->file_path,0777);
+
+		$locale = $this->original_locale; // TODO : improve it because we're not sure this locale is present everywhere
+		putenv('LC_ALL='.$locale);
+		$files = array(); $return = 0;
+		$shell = exec($cmd, $files, $return);
+		if($return != 0) { //if the java application returns an error code
+			switch($return)
+			{
+				// can't connect to openoffice
+				case 1 : $this->error = get_lang('CannotConnectToOpenOffice');break;
+
+				// conversion failed in openoffice
+				case 2 : $this->error = get_lang('OogieConversionFailed');break;
+
+				// conversion can't be launch because command failed
+				case 255 : $this->error = get_lang('OogieUnknownError');break;
+			}
 
 			DocumentManager::delete_document($_course, $dir_name, $this->base_work_dir);
 			return false;
 
-	    }
+	    }
 
-		// create lp
-		$this->lp_id = learnpath::add_lp($_course['id'], ucfirst(pathinfo($file['name'], PATHINFO_FILENAME)),'','guess','manual');
+		// create lp
+		$this->lp_id = learnpath::add_lp($_course['id'], ucfirst(pathinfo($file['name'], PATHINFO_FILENAME)),'','guess','manual');
 
-		// call to the function implemented by child following action_after_conversion parameter
-		switch ($action_after_conversion)
-		{
+		// call to the function implemented by child following action_after_conversion parameter
+		switch ($action_after_conversion)
+		{
 			case 'make_lp':$this -> make_lp($files);
 			break;
 			case 'add_docs_to_visio':$this -> add_docs_to_visio($files);
 			break;
-		}
+		}
 
-	    $perm = api_get_setting('permissions_for_new_directories');
-		$perm = octdec(!empty($perm)?$perm:0770);
-		chmod ($this->base_work_dir.$this->created_dir,$perm);
+	    $perm = api_get_setting('permissions_for_new_directories');
+		$perm = octdec(!empty($perm)?$perm:0770);
+		chmod ($this->base_work_dir.$this->created_dir,$perm);
 	    return $this->first_item;
 
-    }
-
+    }
+
 
-    abstract function make_lp();
-    abstract function add_docs_to_visio();
-    abstract function add_command_parameters();
+    abstract function make_lp();
+    abstract function add_docs_to_visio();
+    abstract function add_command_parameters();
 
 
-}
-?>
+}
+?>

+ 210 - 210
main/newscorm/openoffice_presentation.class.php

@@ -1,220 +1,220 @@
-<?php //$id:$
-/**
- * Defines the OpenofficeDocument class, which is meant as a conversion
- * tool from Office presentations (.ppt, .sxi, .odp, .pptx) to
- * learning paths
- * @package dokeos.learnpath
- * @author  Eric Marguin <eric.marguin@dokeos.com>
- * @license GNU/GPL - See Dokeos license directory for details
- */
-/**
- * Defines the "OpenofficePresentation" child of class "OpenofficeDocument"
- * @package dokeos.learnpath.OpenofficeDocument
- */
-require_once('openoffice_document.class.php');
-if (api_get_setting('search_enabled')=='true') {
-	require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
-	require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
-	require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
-}
-
-class OpenofficePresentation extends OpenofficeDocument {
-
-	public $take_slide_name;
-
-	function OpenofficePresentation($take_slide_name=false, $course_code=null, $resource_id=null,$user_id=null) {
-
-		$this -> take_slide_name = $take_slide_name;
-		parent::OpenofficeDocument($course_code, $resource_id, $user_id);
-
-	}
-
-
-    function make_lp($files=array()) {
-
-    	global $_course;
-
-		$previous = 0;
-		$i = 0;
-
-		if(!is_dir($this->base_work_dir.$this->created_dir))
-			return false;
-
-
-		foreach($files as $file){
-
-			list($slide_name,$file_name,$slide_body) = explode('||',$file); // '||' is used as separator between fields: slide name (with accents) || file name (without accents) || all slide text (to be indexed)
-
-			//filename is utf8 encoded, but when we decode, some chars are not translated (like quote &rsquo;).
-			//so we remove these chars by translating it in htmlentities and the reconvert it in want charset
-			$slide_name = api_htmlentities($slide_name,ENT_COMPAT,$this->original_charset);
-			$slide_name = str_replace('&rsquo;','\'',$slide_name);
-			$slide_name = api_convert_encoding($slide_name, api_get_setting('platform_charset'), $this->original_charset);
-			$slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_setting('platform_charset'));
-
-			if($this->take_slide_name === true)
-			{
-				$slide_name = str_replace('_',' ',$slide_name);
-				$slide_name = api_ucfirst($slide_name);
-			}
-			else
-			{
-				$slide_name = 'slide'.str_repeat('0',2-strlen($i)).$i;
-			}
+<?php //$id:$
+/**
+ * Defines the OpenofficeDocument class, which is meant as a conversion
+ * tool from Office presentations (.ppt, .sxi, .odp, .pptx) to
+ * learning paths
+ * @package dokeos.learnpath
+ * @author  Eric Marguin <eric.marguin@dokeos.com>
+ * @license GNU/GPL - See Dokeos license directory for details
+ */
+/**
+ * Defines the "OpenofficePresentation" child of class "OpenofficeDocument"
+ * @package dokeos.learnpath.OpenofficeDocument
+ */
+require_once('openoffice_document.class.php');
+if (api_get_setting('search_enabled')=='true') {
+	require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
+	require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
+	require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
+}
+
+class OpenofficePresentation extends OpenofficeDocument {
+
+	public $take_slide_name;
+
+	function OpenofficePresentation($take_slide_name=false, $course_code=null, $resource_id=null,$user_id=null) {
+
+		$this -> take_slide_name = $take_slide_name;
+		parent::OpenofficeDocument($course_code, $resource_id, $user_id);
+
+	}
+
+
+    function make_lp($files=array()) {
+
+    	global $_course;
+
+		$previous = 0;
+		$i = 0;
+
+		if(!is_dir($this->base_work_dir.$this->created_dir))
+			return false;
+
+
+		foreach($files as $file){
+
+			list($slide_name,$file_name,$slide_body) = explode('||',$file); // '||' is used as separator between fields: slide name (with accents) || file name (without accents) || all slide text (to be indexed)
+
+			//filename is utf8 encoded, but when we decode, some chars are not translated (like quote &rsquo;).
+			//so we remove these chars by translating it in htmlentities and the reconvert it in want charset
+			$slide_name = api_htmlentities($slide_name,ENT_COMPAT,$this->original_charset);
+			$slide_name = str_replace('&rsquo;','\'',$slide_name);
+			$slide_name = api_convert_encoding($slide_name, api_get_setting('platform_charset'), $this->original_charset);
+			$slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_setting('platform_charset'));
+
+			if($this->take_slide_name === true)
+			{
+				$slide_name = str_replace('_',' ',$slide_name);
+				$slide_name = api_ucfirst($slide_name);
+			}
+			else
+			{
+				$slide_name = 'slide'.str_repeat('0',2-strlen($i)).$i;
+			}
 
 			$i++;
-			// add the png to documents
-			$document_id = add_document($_course,$this->created_dir.'/'.urlencode($file_name),'file',filesize($this->base_work_dir.$this->created_dir.'/'.$file_name),$slide_name);
-			api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',api_get_user_id(),0,0);
-
-
-            // Generating the thumbnail
-            $image = $this->base_work_dir.$this->created_dir .'/'. $file_name;
-
-            $pattern = '/(\w+)\.png$/';
-            $replacement = '${1}_thumb.png';
-            $thumb_name = preg_replace($pattern, $replacement, $file_name);
-            // calculate thumbnail size
-            list($width, $height) = getimagesize($image);
-            $thumb_width = 300;
-            $thumb_height = floor( $height * ($thumb_width / $width ) );
-            // load
-            $thumb = imagecreatetruecolor($thumb_width, $thumb_height);
-            $source = imagecreatefrompng($image);
-            // resize
-            imagecopyresized($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
-            // output
-            imagepng($thumb, $this->base_work_dir.$this->created_dir .'/'. $thumb_name);
-            /*
-            // new resizing method usign imagemagick
-            $im = new Imagick( $image );
-            $im->thumbnailImage($thumb_width, $thumb_height);
-            //file_put_contents($this->base_work_dir.$this->created_dir .'/'. $thumb_name,$im);
-            $im->writeImage($this->base_work_dir.$this->created_dir .'/'. $thumb_name);
-             */
-
-            // adding the thumbnail to documents
-            $document_id_thumb = add_document($_course, $this->created_dir.'/'.urlencode($thumb_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$thumb_name), $slide_name);
-            api_item_property_update($_course, TOOL_THUMBNAIL, $document_id_thumb,'DocumentAdded',api_get_user_id(),0,0);
-
-			// create an html file
-			$html_file = $file_name.'.html';
-			$fp = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file, 'w+');
-
-			$slide_src = api_get_path(REL_COURSE_PATH).$_course['path'].'/document/'.$this->created_dir.'/'.utf8_encode($file_name);
-			$slide_src = str_replace('//', '/', $slide_src);
-			fwrite($fp,
-'<html>
-	<head>
-	</head>
-	<body>
-		<img src="'.$slide_src.'" />
-	</body>
-</html>');  // This indentation is to make the generated html files to look well.
-
-			fclose($fp);
-			$document_id = add_document($_course,$this->created_dir.'/'.urlencode($html_file),'file',filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),$slide_name);
+			// add the png to documents
+			$document_id = add_document($_course,$this->created_dir.'/'.urlencode($file_name),'file',filesize($this->base_work_dir.$this->created_dir.'/'.$file_name),$slide_name);
+			api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',api_get_user_id(),0,0);
+
+
+            // Generating the thumbnail
+            $image = $this->base_work_dir.$this->created_dir .'/'. $file_name;
+
+            $pattern = '/(\w+)\.png$/';
+            $replacement = '${1}_thumb.png';
+            $thumb_name = preg_replace($pattern, $replacement, $file_name);
+            // calculate thumbnail size
+            list($width, $height) = getimagesize($image);
+            $thumb_width = 300;
+            $thumb_height = floor( $height * ($thumb_width / $width ) );
+            // load
+            $thumb = imagecreatetruecolor($thumb_width, $thumb_height);
+            $source = imagecreatefrompng($image);
+            // resize
+            imagecopyresized($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
+            // output
+            imagepng($thumb, $this->base_work_dir.$this->created_dir .'/'. $thumb_name);
+            /*
+            // new resizing method usign imagemagick
+            $im = new Imagick( $image );
+            $im->thumbnailImage($thumb_width, $thumb_height);
+            //file_put_contents($this->base_work_dir.$this->created_dir .'/'. $thumb_name,$im);
+            $im->writeImage($this->base_work_dir.$this->created_dir .'/'. $thumb_name);
+             */
+
+            // adding the thumbnail to documents
+            $document_id_thumb = add_document($_course, $this->created_dir.'/'.urlencode($thumb_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$thumb_name), $slide_name);
+            api_item_property_update($_course, TOOL_THUMBNAIL, $document_id_thumb,'DocumentAdded',api_get_user_id(),0,0);
+
+			// create an html file
+			$html_file = $file_name.'.html';
+			$fp = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file, 'w+');
+
+			$slide_src = api_get_path(REL_COURSE_PATH).$_course['path'].'/document/'.$this->created_dir.'/'.utf8_encode($file_name);
+			$slide_src = str_replace('//', '/', $slide_src);
+			fwrite($fp,
+'<html>
+	<head>
+	</head>
+	<body>
+		<img src="'.$slide_src.'" />
+	</body>
+</html>');  // This indentation is to make the generated html files to look well.
+
+			fclose($fp);
+			$document_id = add_document($_course,$this->created_dir.'/'.urlencode($html_file),'file',filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),$slide_name);
 			if ($document_id){
 
-				//put the document in item_property update
-				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',api_get_user_id(),0,0);
-
-				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
-				if($this->first_item == 0){
-					$this->first_item = $previous;
-				}
-			}
-            // code for text indexing
-            if (api_get_setting('search_enabled')=='true') {
-
-	            if (isset($_POST['index_document']) && $_POST['index_document']) {
-	              //Display::display_normal_message(print_r($_POST));
-	              $di = new DokeosIndexer();
-	              isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
-	              $di->connectDb(NULL, NULL, $lang);
-	              $ic_slide = new IndexableChunk();
-	              $ic_slide->addValue("title", $slide_name);
-	              $specific_fields = get_specific_field_list();
-	              $all_specific_terms = '';
-	              foreach ($specific_fields as $specific_field) {
-	              	if (isset($_REQUEST[$specific_field['code']])) {
-	              		$sterms = trim($_REQUEST[$specific_field['code']]);
-	              		$all_specific_terms .= ' '. $sterms;
-	              		if (!empty($sterms)) {
-	              			$sterms = explode(',', $sterms);
-	              			foreach ($sterms as $sterm) {
-	              				$ic_slide->addTerm(trim($sterm), $specific_field['code']);
-	              			}
-	              		}
-	              	}
-	              }
-	              $slide_body = $all_specific_terms .' '. $slide_body;
-	              $ic_slide->addValue("content", $slide_body);
-	              /* FIXME:  cidReq:lp_id:doc_id al indexar  */
-	              //       add a comment to say terms separated by commas
-	              $courseid=api_get_course_id();
-	              $ic_slide->addCourseId($courseid);
-	              $ic_slide->addToolId(TOOL_LEARNPATH);
-	              $lp_id = $this->lp_id;
-	              $xapian_data = array(
-	              	SE_COURSE_ID => $courseid,
-	              	SE_TOOL_ID => TOOL_LEARNPATH,
-	              	SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => $document_id),
-	              	SE_USER => (int)api_get_user_id(),
-	              );
-	              $ic_slide->xapian_data = serialize($xapian_data);
-	              $di->addChunk($ic_slide);
-	              //index and return search engine document id
-	              $did = $di->index();
-	              if ($did) {
-	                // save it to db
-	                $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
-	                $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
-	                        VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
-	                $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
-	                Database::query($sql,__FILE__,__LINE__);
-	              }
-	            }
-            }
-		}
-    }
-
-    function add_command_parameters(){
-
-    	if(empty($this->slide_width) || empty($this->slide_height))
-    		list($this->slide_width, $this->slide_height) = explode('x',api_get_setting('service_ppt2lp','size'));
-    	return ' -w '.$this->slide_width.' -h '.$this->slide_height.' -d oogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'.html"';
-
-    }
-
-    function set_slide_size($width,$height)
-    {
-    	$this->slide_width = $width;
-    	$this->slide_height = $height;
-    }
-
-    function add_docs_to_visio ($files=array()){
-
-    	global $_course;
-    	/* Add Files */
-
-
-		foreach($files as $file){
-
-			list($slide_name,$file_name) = explode('||',$file); // '||' is used as separator between slide name (with accents) and file name (without accents)
+				//put the document in item_property update
+				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',api_get_user_id(),0,0);
+
+				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
+				if($this->first_item == 0){
+					$this->first_item = $previous;
+				}
+			}
+            // code for text indexing
+            if (api_get_setting('search_enabled')=='true') {
+
+	            if (isset($_POST['index_document']) && $_POST['index_document']) {
+	              //Display::display_normal_message(print_r($_POST));
+	              $di = new DokeosIndexer();
+	              isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
+	              $di->connectDb(NULL, NULL, $lang);
+	              $ic_slide = new IndexableChunk();
+	              $ic_slide->addValue("title", $slide_name);
+	              $specific_fields = get_specific_field_list();
+	              $all_specific_terms = '';
+	              foreach ($specific_fields as $specific_field) {
+	              	if (isset($_REQUEST[$specific_field['code']])) {
+	              		$sterms = trim($_REQUEST[$specific_field['code']]);
+	              		$all_specific_terms .= ' '. $sterms;
+	              		if (!empty($sterms)) {
+	              			$sterms = explode(',', $sterms);
+	              			foreach ($sterms as $sterm) {
+	              				$ic_slide->addTerm(trim($sterm), $specific_field['code']);
+	              			}
+	              		}
+	              	}
+	              }
+	              $slide_body = $all_specific_terms .' '. $slide_body;
+	              $ic_slide->addValue("content", $slide_body);
+	              /* FIXME:  cidReq:lp_id:doc_id al indexar  */
+	              //       add a comment to say terms separated by commas
+	              $courseid=api_get_course_id();
+	              $ic_slide->addCourseId($courseid);
+	              $ic_slide->addToolId(TOOL_LEARNPATH);
+	              $lp_id = $this->lp_id;
+	              $xapian_data = array(
+	              	SE_COURSE_ID => $courseid,
+	              	SE_TOOL_ID => TOOL_LEARNPATH,
+	              	SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => $document_id),
+	              	SE_USER => (int)api_get_user_id(),
+	              );
+	              $ic_slide->xapian_data = serialize($xapian_data);
+	              $di->addChunk($ic_slide);
+	              //index and return search engine document id
+	              $did = $di->index();
+	              if ($did) {
+	                // save it to db
+	                $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
+	                $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
+	                        VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
+	                $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
+	                Database::query($sql,__FILE__,__LINE__);
+	              }
+	            }
+            }
+		}
+    }
+
+    function add_command_parameters(){
+
+    	if(empty($this->slide_width) || empty($this->slide_height))
+    		list($this->slide_width, $this->slide_height) = explode('x',api_get_setting('service_ppt2lp','size'));
+    	return ' -w '.$this->slide_width.' -h '.$this->slide_height.' -d oogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'.html"';
+
+    }
+
+    function set_slide_size($width,$height)
+    {
+    	$this->slide_width = $width;
+    	$this->slide_height = $height;
+    }
+
+    function add_docs_to_visio ($files=array()){
+
+    	global $_course;
+    	/* Add Files */
+
+
+		foreach($files as $file){
+
+			list($slide_name,$file_name) = explode('||',$file); // '||' is used as separator between slide name (with accents) and file name (without accents)
 			$slide_name = api_htmlentities($slide_name,ENT_COMPAT,$this->original_charset);
-			$slide_name = str_replace('&rsquo;','\'',$slide_name);
-			$slide_name = api_convert_encoding($slide_name, api_get_setting('platform_charset'), $this->original_charset);
-			$slide_name = api_html_entity_decode($slide_name,ENT_COMPAT,api_get_setting('platform_charset'));
+			$slide_name = str_replace('&rsquo;','\'',$slide_name);
+			$slide_name = api_convert_encoding($slide_name, api_get_setting('platform_charset'), $this->original_charset);
+			$slide_name = api_html_entity_decode($slide_name,ENT_COMPAT,api_get_setting('platform_charset'));
 
-			$did = add_document($_course, $this->created_dir.'/'.urlencode($file_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$file_name), $slide_name);
-			if ($did)
-				api_item_property_update($_course, TOOL_DOCUMENT, $did, 'DocumentAdded', $_SESSION['_uid'], 0, NULL);
+			$did = add_document($_course, $this->created_dir.'/'.urlencode($file_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$file_name), $slide_name);
+			if ($did)
+				api_item_property_update($_course, TOOL_DOCUMENT, $did, 'DocumentAdded', $_SESSION['_uid'], 0, NULL);
 
-		}
+		}
 
-    }
+    }
 
 
-}
-?>
+}
+?>

+ 308 - 308
main/newscorm/openoffice_text.class.php

@@ -1,352 +1,352 @@
-<?php //$id:$
-/**
- * Defines the OpenofficeDocument class, which is meant as a conversion
- * tool from Office text documents (.doc, .sxw, .odt, .docx) to
- * learning paths
- * @package dokeos.learnpath
- * @author  Eric Marguin <eric.marguin@dokeos.com>
- * @license GNU/GPL - See Doke
-/**
- * Defines the "OpenofficeText" child of class "learnpath"
- * @package dokeos.learnpath.OpenofficeDocument
- */
-require_once('openoffice_document.class.php');
-if (api_get_setting('search_enabled')=='true') {
-	require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
-	require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
-	require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
-}
-
-class OpenofficeText extends OpenofficeDocument {
-
-
-	public $split_steps;
-
-	/**
-	 * Class constructor. Calls the parent class and initialises the local attribute split_steps
-	 * @param	boolean	Whether to split steps (true) or make one large page (false)
-	 * @param	string	Course code
-	 * @param	integer	Resource ID
-	 * @param	integer Creator user id
-	 * @return	void
-	 */
-	function OpenofficeText($split_steps=false, $course_code=null, $resource_id=null,$user_id=null)
-	{
-
-		$this -> split_steps = $split_steps;
-		parent::OpenofficeDocument($course_code, $resource_id, $user_id);
-
-	}
-
-    /**
-     * Gets html pages and compose them into a learning path
-     * @param	array	The files that will compose the generated learning path. Unused so far.
-     * @return	boolean	False if file does not exit. Nothing otherwise.
-     */
-    function make_lp($files=array())
+<?php //$id:$
+/**
+ * Defines the OpenofficeDocument class, which is meant as a conversion
+ * tool from Office text documents (.doc, .sxw, .odt, .docx) to
+ * learning paths
+ * @package dokeos.learnpath
+ * @author  Eric Marguin <eric.marguin@dokeos.com>
+ * @license GNU/GPL - See Doke
+/**
+ * Defines the "OpenofficeText" child of class "learnpath"
+ * @package dokeos.learnpath.OpenofficeDocument
+ */
+require_once('openoffice_document.class.php');
+if (api_get_setting('search_enabled')=='true') {
+	require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
+	require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
+	require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
+}
+
+class OpenofficeText extends OpenofficeDocument {
+
+
+	public $split_steps;
+
+	/**
+	 * Class constructor. Calls the parent class and initialises the local attribute split_steps
+	 * @param	boolean	Whether to split steps (true) or make one large page (false)
+	 * @param	string	Course code
+	 * @param	integer	Resource ID
+	 * @param	integer Creator user id
+	 * @return	void
+	 */
+	function OpenofficeText($split_steps=false, $course_code=null, $resource_id=null,$user_id=null)
+	{
+
+		$this -> split_steps = $split_steps;
+		parent::OpenofficeDocument($course_code, $resource_id, $user_id);
+
+	}
+
+    /**
+     * Gets html pages and compose them into a learning path
+     * @param	array	The files that will compose the generated learning path. Unused so far.
+     * @return	boolean	False if file does not exit. Nothing otherwise.
+     */
+    function make_lp($files=array())
     {
-		global $_course;
-		// we get a content where ||page_break|| indicates where the page is broken
-		if(!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')){return false;}
+		global $_course;
+		// we get a content where ||page_break|| indicates where the page is broken
+		if(!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')){return false;}
 		$content = file_get_contents($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');
 
 
-		unlink($this->base_work_dir.'/'.$this->file_path);
-		unlink($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');
+		unlink($this->base_work_dir.'/'.$this->file_path);
+		unlink($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');
 
 		// the file is utf8 encoded and it seems to make problems with special quotes.
-		// then we htmlentities that, we replace these quotes and html_entity_decode that in good charset
-		$charset = api_get_setting('platform_charset');
+		// then we htmlentities that, we replace these quotes and html_entity_decode that in good charset
+		$charset = api_get_setting('platform_charset');
 		$content = api_htmlentities($content,ENT_COMPAT,$this->original_charset);
-		$content = str_replace('&rsquo;','\'',$content);
-		$content = api_convert_encoding($content, $charset, $this->original_charset);
-		$content = str_replace($this->original_charset,$charset,$content);
-		$content = api_html_entity_decode($content, ENT_COMPAT, $charset);
+		$content = str_replace('&rsquo;','\'',$content);
+		$content = api_convert_encoding($content, $charset, $this->original_charset);
+		$content = str_replace($this->original_charset,$charset,$content);
+		$content = api_html_entity_decode($content, ENT_COMPAT, $charset);
 
-		// set the path to pictures to absolute (so that it can be modified in fckeditor)
-		$content = preg_replace("|src=\"([^\"]*)|i", "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1", $content);
+		// set the path to pictures to absolute (so that it can be modified in fckeditor)
+		$content = preg_replace("|src=\"([^\"]*)|i", "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1", $content);
+
+		list($header, $body) = explode('<BODY',$content);
 
-		list($header, $body) = explode('<BODY',$content);
-
 		$body = '<BODY'.$body;
-
-		// remove font-family styles
-		$header = preg_replace("|font\-family[^;]*;|i", "",$header);
-
-		// dokeos styles
-		$my_style = api_get_setting('stylesheets');
-		if(empty($my_style)){$my_style = 'dokeos_classic';}
-		$style_to_import = "<style type=\"text/css\">\r\n";
-		$style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";
-		$style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/course.css";'."\n";
+
+		// remove font-family styles
+		$header = preg_replace("|font\-family[^;]*;|i", "",$header);
+
+		// dokeos styles
+		$my_style = api_get_setting('stylesheets');
+		if(empty($my_style)){$my_style = 'dokeos_classic';}
+		$style_to_import = "<style type=\"text/css\">\r\n";
+		$style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";
+		$style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/course.css";'."\n";
 		$style_to_import .= "</style>\r\n";
-		$header = preg_replace("|</head>|i", "\r\n$style_to_import\r\n\\0",$header);
+		$header = preg_replace("|</head>|i", "\r\n$style_to_import\r\n\\0",$header);
 
-		// line break before and after picture
-		$header = str_replace('p {','p {clear:both;',$header);
+		// line break before and after picture
+		$header = str_replace('p {','p {clear:both;',$header);
 
-		$header = str_replace('absolute','relative',$header);
+		$header = str_replace('absolute','relative',$header);
 
-		switch($this->split_steps)
-		{
-			case 'per_page' : $this -> dealPerPage($header,$body); break;
-			case 'per_chapter' : $this -> dealPerChapter($header,$body); break;
-		}
+		switch($this->split_steps)
+		{
+			case 'per_page' : $this -> dealPerPage($header,$body); break;
+			case 'per_chapter' : $this -> dealPerChapter($header,$body); break;
+		}
 
-    }
+    }
 
-    /**
-     * Manages chapter splitting
-     * @param	string	Chapter header
-     * @param	string	Content
-     * @return	void
-     */
-    function dealPerChapter($header, $content)
-    {
+    /**
+     * Manages chapter splitting
+     * @param	string	Chapter header
+     * @param	string	Content
+     * @return	void
+     */
+    function dealPerChapter($header, $content)
+    {
 
-		global $_course;
+		global $_course;
 
-		$content = str_replace('||page_break||','',$content);
+		$content = str_replace('||page_break||','',$content);
 
-		// get all the h1
-		preg_match_all("|<h1[^>]*>([^(h1)+]*)</h1>|is",$content,$matches_temp);
+		// get all the h1
+		preg_match_all("|<h1[^>]*>([^(h1)+]*)</h1>|is",$content,$matches_temp);
 
 
-		//empty the fake chapters
-		$new_index = 0;
-		for ($i=0 ; $i<count($matches_temp[0]) ; $i++) {
-
-			if(trim($matches_temp[1][$i])!=='')
-			{
-				$matches[0][$new_index] = $matches_temp[0][$i];
-				$matches[1][$new_index] = $matches_temp[1][$i];
-				$new_index++;
-			}
+		//empty the fake chapters
+		$new_index = 0;
+		for ($i=0 ; $i<count($matches_temp[0]) ; $i++) {
 
-		}
+			if(trim($matches_temp[1][$i])!=='')
+			{
+				$matches[0][$new_index] = $matches_temp[0][$i];
+				$matches[1][$new_index] = $matches_temp[1][$i];
+				$new_index++;
+			}
 
-		// add intro item
-		$intro_content = substr($content, 0, strpos($content, $matches[0][0]));
-		$items_to_create[get_lang('Introduction')] = $intro_content;
-
+		}
+
+		// add intro item
+		$intro_content = substr($content, 0, strpos($content, $matches[0][0]));
+		$items_to_create[get_lang('Introduction')] = $intro_content;
 
-		for ($i=0 ; $i<count($matches[0]) ; $i++) {
 
-			if(empty($matches[1][$i]))
-				continue;
+		for ($i=0 ; $i<count($matches[0]) ; $i++) {
 
-			$content = strstr($content,$matches[0][$i]);
-			if($i+1!==count($matches[0]))
-			{
-				$chapter_content = substr($content, 0, strpos($content, $matches[0][$i+1]));
-			}
-			else
-			{
-				$chapter_content = $content;
-			}
-			$items_to_create[$matches[1][$i]] = $chapter_content;
+			if(empty($matches[1][$i]))
+				continue;
 
-		}
+			$content = strstr($content,$matches[0][$i]);
+			if($i+1!==count($matches[0]))
+			{
+				$chapter_content = substr($content, 0, strpos($content, $matches[0][$i+1]));
+			}
+			else
+			{
+				$chapter_content = $content;
+			}
+			$items_to_create[$matches[1][$i]] = $chapter_content;
+
+		}
 
-		$i = 0;
-		foreach($items_to_create as $item_title=>$item_content)
-		{
-			$i++;
-			$page_content = $this->format_page_content($header, $item_content);
+		$i = 0;
+		foreach($items_to_create as $item_title=>$item_content)
+		{
+			$i++;
+			$page_content = $this->format_page_content($header, $item_content);
 
-			$html_file = $this->created_dir.'-'.$i.'.html';
-			$handle = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file,'w+');
-			fwrite($handle, $page_content);
-			fclose($handle);
+			$html_file = $this->created_dir.'-'.$i.'.html';
+			$handle = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file,'w+');
+			fwrite($handle, $page_content);
+			fclose($handle);
 
-			$document_id = add_document($_course,$this->created_dir.'/'.$html_file,'file',filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),$html_file);
+			$document_id = add_document($_course,$this->created_dir.'/'.$html_file,'file',filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),$html_file);
 
 			if ($document_id){
 
-				//put the document in item_property update
-				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$_SESSION['_uid'],0,0);
-
-				$infos = pathinfo($this->filepath);
-				$slide_name = strip_tags(nl2br($item_title));
-				$slide_name = str_replace(array("\r\n", "\r", "\n"), "", $slide_name);
-				$slide_name = html_entity_decode($slide_name);
-				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
-				if($this->first_item == 0){
-					$this->first_item = $previous;
-				}
-			}
-		}
-
-	}
-
-    /**
-     * Manages page splitting
-     * @param	string	Page header
-     * @param	string	Page body
-     * @return	void
-     */
-    function dealPerPage($header,$body)
-    {
-		global $_course;
-		// split document to pages
+				//put the document in item_property update
+				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$_SESSION['_uid'],0,0);
+
+				$infos = pathinfo($this->filepath);
+				$slide_name = strip_tags(nl2br($item_title));
+				$slide_name = str_replace(array("\r\n", "\r", "\n"), "", $slide_name);
+				$slide_name = html_entity_decode($slide_name);
+				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
+				if($this->first_item == 0){
+					$this->first_item = $previous;
+				}
+			}
+		}
+
+	}
+
+    /**
+     * Manages page splitting
+     * @param	string	Page header
+     * @param	string	Page body
+     * @return	void
+     */
+    function dealPerPage($header,$body)
+    {
+		global $_course;
+		// split document to pages
 		$pages = explode('||page_break||',$body);
 
-		$first_item = 0;
+		$first_item = 0;
 
-		foreach($pages as $key=>$page_content)
-		{ // for every pages, we create a new file
+		foreach($pages as $key=>$page_content)
+		{ // for every pages, we create a new file
 
-			$key +=1;
+			$key +=1;
 
-			$page_content = $this->format_page_content($header, $page_content, $this->base_work_dir.$this->created_dir);
-			$html_file = $this->created_dir.'-'.$key.'.html';
-			$handle = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file,'w+');
-			fwrite($handle, $page_content);
-			fclose($handle);
+			$page_content = $this->format_page_content($header, $page_content, $this->base_work_dir.$this->created_dir);
+			$html_file = $this->created_dir.'-'.$key.'.html';
+			$handle = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file,'w+');
+			fwrite($handle, $page_content);
+			fclose($handle);
 
-			$document_id = add_document($_course,$this->created_dir.$html_file,'file',filesize($this->base_work_dir.$this->created_dir.$html_file),$html_file);
+			$document_id = add_document($_course,$this->created_dir.$html_file,'file',filesize($this->base_work_dir.$this->created_dir.$html_file),$html_file);
+
+			$slide_name = '';
 
-			$slide_name = '';
-
 			if ($document_id) {
 
-				//put the document in item_property update
-				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$_SESSION['_uid'],0,0);
-
-				$infos = pathinfo($this->filepath);
-				$slide_name = 'Page '.str_repeat('0',2-strlen($key)).$key;
-				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
-				if($this->first_item == 0) {
-					$this->first_item = $previous;
-				}
-				// code for text indexing
-				if (api_get_setting('search_enabled')=='true') {
-					if (isset($_POST['index_document']) && $_POST['index_document']) {
-						//Display::display_normal_message(print_r($_POST));
-						$di = new DokeosIndexer();
-						isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
-						$di->connectDb(NULL, NULL, $lang);
-						$ic_slide = new IndexableChunk();
-						$ic_slide->addValue("title", $slide_name);
-						$specific_fields = get_specific_field_list();
-						$all_specific_terms = '';
-						foreach ($specific_fields as $specific_field) {
-							if (isset($_REQUEST[$specific_field['code']])) {
-								$sterms = trim($_REQUEST[$specific_field['code']]);
-								$all_specific_terms .= ' '. $sterms;
-								if (!empty($sterms)) {
-									$sterms = explode(',', $sterms);
-									foreach ($sterms as $sterm) {
-										$ic_slide->addTerm(trim($sterm), $specific_field['code']);
-									}
-								}
-							}
-						}
-						$page_content = $all_specific_terms .' '. $page_content;
-						$ic_slide->addValue("content", $page_content);
-						//       add a comment to say terms separated by commas
-						$courseid=api_get_course_id();
-						$ic_slide->addCourseId($courseid);
-						$ic_slide->addToolId(TOOL_LEARNPATH);
-						$lp_id = $this->lp_id;
-						$xapian_data = array(
-							SE_COURSE_ID => $courseid,
-							SE_TOOL_ID => TOOL_LEARNPATH,
-							SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => $document_id),
-							SE_USER => (int)api_get_user_id(),
-						);
-						$ic_slide->xapian_data = serialize($xapian_data);
-						$di->addChunk($ic_slide);
-						//index and return search engine document id
-						$did = $di->index();
-						if ($did) {
-							// save it to db
-							$tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
-							$sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
-	                                VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
-							$sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
-							Database::query($sql,__FILE__,__LINE__);
-						}
-					}
-				}
-			}
+				//put the document in item_property update
+				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$_SESSION['_uid'],0,0);
+
+				$infos = pathinfo($this->filepath);
+				$slide_name = 'Page '.str_repeat('0',2-strlen($key)).$key;
+				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
+				if($this->first_item == 0) {
+					$this->first_item = $previous;
+				}
+				// code for text indexing
+				if (api_get_setting('search_enabled')=='true') {
+					if (isset($_POST['index_document']) && $_POST['index_document']) {
+						//Display::display_normal_message(print_r($_POST));
+						$di = new DokeosIndexer();
+						isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
+						$di->connectDb(NULL, NULL, $lang);
+						$ic_slide = new IndexableChunk();
+						$ic_slide->addValue("title", $slide_name);
+						$specific_fields = get_specific_field_list();
+						$all_specific_terms = '';
+						foreach ($specific_fields as $specific_field) {
+							if (isset($_REQUEST[$specific_field['code']])) {
+								$sterms = trim($_REQUEST[$specific_field['code']]);
+								$all_specific_terms .= ' '. $sterms;
+								if (!empty($sterms)) {
+									$sterms = explode(',', $sterms);
+									foreach ($sterms as $sterm) {
+										$ic_slide->addTerm(trim($sterm), $specific_field['code']);
+									}
+								}
+							}
+						}
+						$page_content = $all_specific_terms .' '. $page_content;
+						$ic_slide->addValue("content", $page_content);
+						//       add a comment to say terms separated by commas
+						$courseid=api_get_course_id();
+						$ic_slide->addCourseId($courseid);
+						$ic_slide->addToolId(TOOL_LEARNPATH);
+						$lp_id = $this->lp_id;
+						$xapian_data = array(
+							SE_COURSE_ID => $courseid,
+							SE_TOOL_ID => TOOL_LEARNPATH,
+							SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => $document_id),
+							SE_USER => (int)api_get_user_id(),
+						);
+						$ic_slide->xapian_data = serialize($xapian_data);
+						$di->addChunk($ic_slide);
+						//index and return search engine document id
+						$did = $di->index();
+						if ($did) {
+							// save it to db
+							$tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
+							$sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
+	                                VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
+							$sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
+							Database::query($sql,__FILE__,__LINE__);
+						}
+					}
+				}
+			}
 		}
-    }
-
-    /**
-     * Returns additional Java command parameters
-     * @return	string	The additional parameters to be used in the Java call
-     */
-    function add_command_parameters(){
-    	return ' -d woogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'/'.$this->file_name.'.html"';
-    }
-
-    /**
-     * Formats a page content by reorganising the HTML code a little
-     * @param	string	Page header
-     * @param	string	Page content
+    }
+
+    /**
+     * Returns additional Java command parameters
+     * @return	string	The additional parameters to be used in the Java call
+     */
+    function add_command_parameters(){
+    	return ' -d woogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'/'.$this->file_name.'.html"';
+    }
+
+    /**
+     * Formats a page content by reorganising the HTML code a little
+     * @param	string	Page header
+     * @param	string	Page content
      * @return	string	Formatted page content
-     */
-    function format_page_content($header, $content)
-    {
-
-
-		// limit the width of the doc
-		list($max_width, $max_height) = explode('x',api_get_setting('service_ppt2lp','size'));
-
-		$content = preg_replace("|<body[^>]*>|i","\\0\r\n<div style=\"width:".$max_width."\">",$content, -1,$count);
-		if($count < 1)
-		{
-			$content = '<body><div style="width:'.$max_width.'">'.$content;
-		}
-
-		$content = preg_replace('|</body>|i','</div>\\0',$content, -1, $count);
-		if($count < 1)
-		{
-			$content = $content.'</div></body>';
-		}
-
-		// add the headers
-		$content = $header.$content;
-
-
-		// resize all the picture to the max_width-10
-		preg_match_all("|<img[^src]*src=\"([^\"]*)\"[^>]*>|i",$content,$images);
-
-		foreach ($images[1] as $key => $image)
-		{
-			// check if the <img tag soon has a width attribute
-			$defined_width = preg_match("|width=([^\s]*)|i",$images[0][$key], $img_width);
-			$img_width = $img_width[1];
-			if(!$defined_width)
-			{
-
-				list($img_width, $img_height, $type) = getimagesize($this->base_work_dir.$this->created_dir.'/'.$image);
-
-				$new_width = $max_width-10;
-				if($img_width > $new_width)
-				{
-					$picture_resized = str_ireplace('<img','<img width="'.$new_width.'" ',$images[0][$key]);
-					$content = str_replace($images[0][$key],$picture_resized,$content);
-				}
-
-			}
-			else if($img_width > $max_width-10)
-			{
-				$picture_resized = str_ireplace('width='.$img_width,'width="'.($max_width-10).'"',$images[0][$key]);
-				$content = str_replace($images[0][$key],$picture_resized,$content);
-			}
-		}
-
-
-    	return $content;
-
-    }
-    /**
-     * Add documents to the visioconference (to be implemented)
-     */
-    function add_docs_to_visio (){
-
-    }
-}
-?>
+     */
+    function format_page_content($header, $content)
+    {
+
+
+		// limit the width of the doc
+		list($max_width, $max_height) = explode('x',api_get_setting('service_ppt2lp','size'));
+
+		$content = preg_replace("|<body[^>]*>|i","\\0\r\n<div style=\"width:".$max_width."\">",$content, -1,$count);
+		if($count < 1)
+		{
+			$content = '<body><div style="width:'.$max_width.'">'.$content;
+		}
+
+		$content = preg_replace('|</body>|i','</div>\\0',$content, -1, $count);
+		if($count < 1)
+		{
+			$content = $content.'</div></body>';
+		}
+
+		// add the headers
+		$content = $header.$content;
+
+
+		// resize all the picture to the max_width-10
+		preg_match_all("|<img[^src]*src=\"([^\"]*)\"[^>]*>|i",$content,$images);
+
+		foreach ($images[1] as $key => $image)
+		{
+			// check if the <img tag soon has a width attribute
+			$defined_width = preg_match("|width=([^\s]*)|i",$images[0][$key], $img_width);
+			$img_width = $img_width[1];
+			if(!$defined_width)
+			{
+
+				list($img_width, $img_height, $type) = getimagesize($this->base_work_dir.$this->created_dir.'/'.$image);
+
+				$new_width = $max_width-10;
+				if($img_width > $new_width)
+				{
+					$picture_resized = str_ireplace('<img','<img width="'.$new_width.'" ',$images[0][$key]);
+					$content = str_replace($images[0][$key],$picture_resized,$content);
+				}
+
+			}
+			else if($img_width > $max_width-10)
+			{
+				$picture_resized = str_ireplace('width='.$img_width,'width="'.($max_width-10).'"',$images[0][$key]);
+				$content = str_replace($images[0][$key],$picture_resized,$content);
+			}
+		}
+
+
+    	return $content;
+
+    }
+    /**
+     * Add documents to the visioconference (to be implemented)
+     */
+    function add_docs_to_visio (){
+
+    }
+}
+?>

+ 311 - 311
main/newscorm/openoffice_text_document.class.php

@@ -1,350 +1,350 @@
-<?php //$id:$
-/**
- * Defines the OpenOfficeDocument class, which is meant as a conversion
- * tool from Office text documents (.doc, .sxw, .odt, .docx) to
- * learning paths
- * @package dokeos.learnpath
- * @author  Eric Marguin <eric.marguin@dokeos.com>
- * @license GNU/GPL - See Doke
-/**
- * Defines the "OpenOfficeTextDocument" child of class "learnpath"
- * @package dokeos.learnpath.openofficedocument
- */
-require_once('openoffice_document.class.php');
-require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
-require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
-
-class OpenOfficeTextDocument extends OpenofficeDocument {
-
-
-	public $split_steps;
-
-	/**
-	 * Class constructor. Calls the parent class and initialises the local attribute split_steps
-	 * @param	boolean	Whether to split steps (true) or make one large page (false)
-	 * @param	string	Course code
-	 * @param	integer	Resource ID
-	 * @param	integer Creator user id
-	 * @return	void
-	 */
-	function OpenofficeTextDocument($split_steps=false, $course_code=null, $resource_id=null,$user_id=null)
-	{
-
-		$this -> split_steps = $split_steps;
-		parent::OpenofficeDocument($course_code, $resource_id, $user_id);
-
-	}
-
-    /**
-     * Gets html pages and compose them into a learning path
-     * @param	array	The files that will compose the generated learning path. Unused so far.
-     * @return	boolean	False if file does not exit. Nothing otherwise.
-     */
-    function make_lp($files=array())
-    {
-
-		global $_course;
-		// we get a content where ||page_break|| indicates where the page is broken
-		if(!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')){return false;}
+<?php //$id:$
+/**
+ * Defines the OpenOfficeDocument class, which is meant as a conversion
+ * tool from Office text documents (.doc, .sxw, .odt, .docx) to
+ * learning paths
+ * @package dokeos.learnpath
+ * @author  Eric Marguin <eric.marguin@dokeos.com>
+ * @license GNU/GPL - See Doke
+/**
+ * Defines the "OpenOfficeTextDocument" child of class "learnpath"
+ * @package dokeos.learnpath.openofficedocument
+ */
+require_once('openoffice_document.class.php');
+require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
+require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
+require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
+
+class OpenOfficeTextDocument extends OpenofficeDocument {
+
+
+	public $split_steps;
+
+	/**
+	 * Class constructor. Calls the parent class and initialises the local attribute split_steps
+	 * @param	boolean	Whether to split steps (true) or make one large page (false)
+	 * @param	string	Course code
+	 * @param	integer	Resource ID
+	 * @param	integer Creator user id
+	 * @return	void
+	 */
+	function OpenofficeTextDocument($split_steps=false, $course_code=null, $resource_id=null,$user_id=null)
+	{
+
+		$this -> split_steps = $split_steps;
+		parent::OpenofficeDocument($course_code, $resource_id, $user_id);
+
+	}
+
+    /**
+     * Gets html pages and compose them into a learning path
+     * @param	array	The files that will compose the generated learning path. Unused so far.
+     * @return	boolean	False if file does not exit. Nothing otherwise.
+     */
+    function make_lp($files=array())
+    {
+
+		global $_course;
+		// we get a content where ||page_break|| indicates where the page is broken
+		if(!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')){return false;}
 		$content = file_get_contents($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');
 
 
-		unlink($this->base_work_dir.'/'.$this->file_path);
-		unlink($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');
+		unlink($this->base_work_dir.'/'.$this->file_path);
+		unlink($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');
 
 		// the file is utf8 encoded and it seems to make problems with special quotes.
-		// then we htmlentities that, we replace these quotes and html_entity_decode that in good charset
-		$charset = api_get_setting('platform_charset');
-		$content = api_htmlentities($content,ENT_COMPAT,$this->original_charset);
-		$content = str_replace('&rsquo;','\'',$content);
-		$content = api_convert_encoding($content, $charset, $this->original_charset);
-		$content = str_replace($this->original_charset,$charset,$content);
-		$content = api_html_entity_decode($content, ENT_COMPAT, $charset);
-
-		// set the path to pictures to absolute (so that it can be modified in fckeditor)
-		$content = preg_replace("|src=\"([^\"]*)|i", "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1", $content);
-
-		list($header, $body) = explode('<BODY',$content);
-
+		// then we htmlentities that, we replace these quotes and html_entity_decode that in good charset
+		$charset = api_get_setting('platform_charset');
+		$content = api_htmlentities($content,ENT_COMPAT,$this->original_charset);
+		$content = str_replace('&rsquo;','\'',$content);
+		$content = api_convert_encoding($content, $charset, $this->original_charset);
+		$content = str_replace($this->original_charset,$charset,$content);
+		$content = api_html_entity_decode($content, ENT_COMPAT, $charset);
+
+		// set the path to pictures to absolute (so that it can be modified in fckeditor)
+		$content = preg_replace("|src=\"([^\"]*)|i", "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1", $content);
+
+		list($header, $body) = explode('<BODY',$content);
+
 		$body = '<BODY'.$body;
-
-		// remove font-family styles
-		$header = preg_replace("|font\-family[^;]*;|i", "",$header);
-
-		// dokeos styles
-		$my_style = api_get_setting('stylesheets');
-		if(empty($my_style)){$my_style = 'dokeos_classic';}
-		$style_to_import = "<style type=\"text/css\">\r\n";
-		$style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";
-		$style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/course.css";'."\n";
+
+		// remove font-family styles
+		$header = preg_replace("|font\-family[^;]*;|i", "",$header);
+
+		// dokeos styles
+		$my_style = api_get_setting('stylesheets');
+		if(empty($my_style)){$my_style = 'dokeos_classic';}
+		$style_to_import = "<style type=\"text/css\">\r\n";
+		$style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";
+		$style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/course.css";'."\n";
 		$style_to_import .= "</style>\r\n";
-		$header = preg_replace("|</head>|i", "\r\n$style_to_import\r\n\\0",$header);
+		$header = preg_replace("|</head>|i", "\r\n$style_to_import\r\n\\0",$header);
+
+		// line break before and after picture
+		$header = str_replace('p {','p {clear:both;',$header);
 
-		// line break before and after picture
-		$header = str_replace('p {','p {clear:both;',$header);
+		$header = str_replace('absolute','relative',$header);
 
-		$header = str_replace('absolute','relative',$header);
+		switch($this->split_steps)
+		{
+			case 'per_page' : $this -> dealPerPage($header,$body); break;
+			case 'per_chapter' : $this -> dealPerChapter($header,$body); break;
+		}
 
-		switch($this->split_steps)
-		{
-			case 'per_page' : $this -> dealPerPage($header,$body); break;
-			case 'per_chapter' : $this -> dealPerChapter($header,$body); break;
-		}
+    }
 
-    }
+    /**
+     * Manages chapter splitting
+     * @param	string	Chapter header
+     * @param	string	Content
+     * @return	void
+     */
+    function dealPerChapter($header, $content)
+    {
 
-    /**
-     * Manages chapter splitting
-     * @param	string	Chapter header
-     * @param	string	Content
-     * @return	void
-     */
-    function dealPerChapter($header, $content)
-    {
+		global $_course;
 
-		global $_course;
+		$content = str_replace('||page_break||','',$content);
 
-		$content = str_replace('||page_break||','',$content);
+		// get all the h1
+		preg_match_all("|<h1[^>]*>([^(h1)+]*)</h1>|is",$content,$matches_temp);
 
-		// get all the h1
-		preg_match_all("|<h1[^>]*>([^(h1)+]*)</h1>|is",$content,$matches_temp);
 
+		//empty the fake chapters
+		$new_index = 0;
+		for ($i=0 ; $i<count($matches_temp[0]) ; $i++) {
 
-		//empty the fake chapters
-		$new_index = 0;
-		for ($i=0 ; $i<count($matches_temp[0]) ; $i++) {
-
-			if(trim($matches_temp[1][$i])!=='')
-			{
-				$matches[0][$new_index] = $matches_temp[0][$i];
-				$matches[1][$new_index] = $matches_temp[1][$i];
-				$new_index++;
-			}
+			if(trim($matches_temp[1][$i])!=='')
+			{
+				$matches[0][$new_index] = $matches_temp[0][$i];
+				$matches[1][$new_index] = $matches_temp[1][$i];
+				$new_index++;
+			}
 
-		}
+		}
 
-		// add intro item
-		$intro_content = api_substr($content, 0, api_strpos($content, $matches[0][0]));
-		$items_to_create[get_lang('Introduction')] = $intro_content;
-
+		// add intro item
+		$intro_content = api_substr($content, 0, api_strpos($content, $matches[0][0]));
+		$items_to_create[get_lang('Introduction')] = $intro_content;
 
-		for ($i=0 ; $i<count($matches[0]) ; $i++) {
 
-			if(empty($matches[1][$i]))
-				continue;
+		for ($i=0 ; $i<count($matches[0]) ; $i++) {
 
-			$content = api_strstr($content, $matches[0][$i]);
-			if($i+1!==count($matches[0]))
-			{
-				$chapter_content = api_substr($content, 0, api_strpos($content, $matches[0][$i+1]));
-			}
-			else
-			{
-				$chapter_content = $content;
-			}
-			$items_to_create[$matches[1][$i]] = $chapter_content;
+			if(empty($matches[1][$i]))
+				continue;
 
-		}
+			$content = api_strstr($content, $matches[0][$i]);
+			if($i+1!==count($matches[0]))
+			{
+				$chapter_content = api_substr($content, 0, api_strpos($content, $matches[0][$i+1]));
+			}
+			else
+			{
+				$chapter_content = $content;
+			}
+			$items_to_create[$matches[1][$i]] = $chapter_content;
 
-		$i = 0;
-		foreach($items_to_create as $item_title=>$item_content)
-		{
-			$i++;
-			$page_content = $this->format_page_content($header, $item_content);
+		}
 
-			$html_file = $this->created_dir.'-'.$i.'.html';
-			$handle = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file,'w+');
-			fwrite($handle, $page_content);
-			fclose($handle);
+		$i = 0;
+		foreach($items_to_create as $item_title=>$item_content)
+		{
+			$i++;
+			$page_content = $this->format_page_content($header, $item_content);
 
-			$document_id = add_document($_course,$this->created_dir.'/'.$html_file,'file',filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),$html_file);
+			$html_file = $this->created_dir.'-'.$i.'.html';
+			$handle = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file,'w+');
+			fwrite($handle, $page_content);
+			fclose($handle);
+
+			$document_id = add_document($_course,$this->created_dir.'/'.$html_file,'file',filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),$html_file);
 
 			if ($document_id){
 
-				//put the document in item_property update
-				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$_SESSION['_uid'],0,0);
-
-				$infos = pathinfo($this->filepath);
-				$slide_name = strip_tags(nl2br($item_title));
-				$slide_name = str_replace(array("\r\n", "\r", "\n"), "", $slide_name);
-				$slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding());
-				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
-				if($this->first_item == 0){
-					$this->first_item = $previous;
-				}
-			}
-		}
-
-	}
-
-    /**
-     * Manages page splitting
-     * @param	string	Page header
-     * @param	string	Page body
-     * @return	void
-     */
-    function dealPerPage($header,$body)
-    {
-		global $_course;
-		// split document to pages
+				//put the document in item_property update
+				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$_SESSION['_uid'],0,0);
+
+				$infos = pathinfo($this->filepath);
+				$slide_name = strip_tags(nl2br($item_title));
+				$slide_name = str_replace(array("\r\n", "\r", "\n"), "", $slide_name);
+				$slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding());
+				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
+				if($this->first_item == 0){
+					$this->first_item = $previous;
+				}
+			}
+		}
+
+	}
+
+    /**
+     * Manages page splitting
+     * @param	string	Page header
+     * @param	string	Page body
+     * @return	void
+     */
+    function dealPerPage($header,$body)
+    {
+		global $_course;
+		// split document to pages
 		$pages = explode('||page_break||',$body);
 
-		$first_item = 0;
+		$first_item = 0;
+
+		foreach($pages as $key=>$page_content)
+		{ // for every pages, we create a new file
 
-		foreach($pages as $key=>$page_content)
-		{ // for every pages, we create a new file
+			$key +=1;
 
-			$key +=1;
+			$page_content = $this->format_page_content($header, $page_content, $this->base_work_dir.$this->created_dir);
+			$html_file = $this->created_dir.'-'.$key.'.html';
+			$handle = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file,'w+');
+			fwrite($handle, $page_content);
+			fclose($handle);
 
-			$page_content = $this->format_page_content($header, $page_content, $this->base_work_dir.$this->created_dir);
-			$html_file = $this->created_dir.'-'.$key.'.html';
-			$handle = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file,'w+');
-			fwrite($handle, $page_content);
-			fclose($handle);
+			$document_id = add_document($_course,$this->created_dir.$html_file,'file',filesize($this->base_work_dir.$this->created_dir.$html_file),$html_file);
 
-			$document_id = add_document($_course,$this->created_dir.$html_file,'file',filesize($this->base_work_dir.$this->created_dir.$html_file),$html_file);
+			$slide_name = '';
 
-			$slide_name = '';
-
 			if ($document_id){
 
-				//put the document in item_property update
-				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$_SESSION['_uid'],0,0);
-
-				$infos = pathinfo($this->filepath);
-				$slide_name = 'Page '.str_repeat('0',2-strlen($key)).$key;
-				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
-				if($this->first_item == 0){
-					$this->first_item = $previous;
-				}
-				// code for text indexing
-				if (isset($_POST['index_document']) && $_POST['index_document']) {
-					//Display::display_normal_message(print_r($_POST));
-					$di = new DokeosIndexer();
-					isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
-					$di->connectDb(NULL, NULL, $lang);
-					$ic_slide = new IndexableChunk();
-					$ic_slide->addValue("title", $slide_name);
-					$specific_fields = get_specific_field_list();
-					$all_specific_terms = '';
-					foreach ($specific_fields as $specific_field) {
-						if (isset($_REQUEST[$specific_field['code']])) {
-							$sterms = trim($_REQUEST[$specific_field['code']]);
-							$all_specific_terms .= ' '. $sterms;
-							if (!empty($sterms)) {
-								$sterms = explode(',', $sterms);
-								foreach ($sterms as $sterm) {
-									$ic_slide->addTerm(trim($sterm), $specific_field['code']);
-								}
-							}
-						}
-					}
-					$page_content = $all_specific_terms .' '. $page_content;
-					$ic_slide->addValue("content", $page_content);
-					//       add a comment to say terms separated by commas
-					$courseid=api_get_course_id();
-					$ic_slide->addCourseId($courseid);
-					$ic_slide->addToolId(TOOL_LEARNPATH);
-					$lp_id = $this->lp_id;
-					$xapian_data = array(
-						SE_COURSE_ID => $courseid,
-						SE_TOOL_ID => TOOL_LEARNPATH,
-						SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => $document_id),
-						SE_USER => (int)api_get_user_id(),
-					);
-					$ic_slide->xapian_data = serialize($xapian_data);
-					$di->addChunk($ic_slide);
-					//index and return search engine document id
-					$did = $di->index();
-					if ($did) {
-						// save it to db
-						$tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
-						$sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
-                                VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
-						$sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
-						Database::query($sql,__FILE__,__LINE__);
-					}
-				}
-			}
-		}
-
-    }
-
-    /**
-     * Returns additional Java command parameters
-     * @return	string	The additional parameters to be used in the Java call
-     */
-    function add_command_parameters(){
-    	return ' -d woogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'/'.$this->file_name.'.html"';
-    }
-
-    /**
-     * Formats a page content by reorganising the HTML code a little
-     * @param	string	Page header
-     * @param	string	Page content
+				//put the document in item_property update
+				api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$_SESSION['_uid'],0,0);
+
+				$infos = pathinfo($this->filepath);
+				$slide_name = 'Page '.str_repeat('0',2-strlen($key)).$key;
+				$previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
+				if($this->first_item == 0){
+					$this->first_item = $previous;
+				}
+				// code for text indexing
+				if (isset($_POST['index_document']) && $_POST['index_document']) {
+					//Display::display_normal_message(print_r($_POST));
+					$di = new DokeosIndexer();
+					isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
+					$di->connectDb(NULL, NULL, $lang);
+					$ic_slide = new IndexableChunk();
+					$ic_slide->addValue("title", $slide_name);
+					$specific_fields = get_specific_field_list();
+					$all_specific_terms = '';
+					foreach ($specific_fields as $specific_field) {
+						if (isset($_REQUEST[$specific_field['code']])) {
+							$sterms = trim($_REQUEST[$specific_field['code']]);
+							$all_specific_terms .= ' '. $sterms;
+							if (!empty($sterms)) {
+								$sterms = explode(',', $sterms);
+								foreach ($sterms as $sterm) {
+									$ic_slide->addTerm(trim($sterm), $specific_field['code']);
+								}
+							}
+						}
+					}
+					$page_content = $all_specific_terms .' '. $page_content;
+					$ic_slide->addValue("content", $page_content);
+					//       add a comment to say terms separated by commas
+					$courseid=api_get_course_id();
+					$ic_slide->addCourseId($courseid);
+					$ic_slide->addToolId(TOOL_LEARNPATH);
+					$lp_id = $this->lp_id;
+					$xapian_data = array(
+						SE_COURSE_ID => $courseid,
+						SE_TOOL_ID => TOOL_LEARNPATH,
+						SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => $document_id),
+						SE_USER => (int)api_get_user_id(),
+					);
+					$ic_slide->xapian_data = serialize($xapian_data);
+					$di->addChunk($ic_slide);
+					//index and return search engine document id
+					$did = $di->index();
+					if ($did) {
+						// save it to db
+						$tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
+						$sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
+                                VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
+						$sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
+						Database::query($sql,__FILE__,__LINE__);
+					}
+				}
+			}
+		}
+
+    }
+
+    /**
+     * Returns additional Java command parameters
+     * @return	string	The additional parameters to be used in the Java call
+     */
+    function add_command_parameters(){
+    	return ' -d woogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'/'.$this->file_name.'.html"';
+    }
+
+    /**
+     * Formats a page content by reorganising the HTML code a little
+     * @param	string	Page header
+     * @param	string	Page content
      * @return	string	Formatted page content
-     */
-    function format_page_content($header, $content)
-    {
-
-
-		// limit the width of the doc
-		list($max_width, $max_height) = explode('x',api_get_setting('service_ppt2lp','size'));
-
-		$content = preg_replace("|<body[^>]*>|i","\\0\r\n<div style=\"width:".$max_width."\">",$content, -1,$count);
-		if($count < 1)
-		{
-			$content = '<body><div style="width:'.$max_width.'">'.$content;
-		}
-
-		$content = preg_replace('|</body>|i','</div>\\0',$content, -1, $count);
-		if($count < 1)
-		{
-			$content = $content.'</div></body>';
-		}
-
-		// add the headers
-		$content = $header.$content;
-
-
-		// resize all the picture to the max_width-10
-		preg_match_all("|<img[^src]*src=\"([^\"]*)\"[^>]*>|i",$content,$images);
-
-		foreach ($images[1] as $key => $image)
-		{
-			// check if the <img tag soon has a width attribute
-			$defined_width = preg_match("|width=([^\s]*)|i",$images[0][$key], $img_width);
-			$img_width = $img_width[1];
-			if(!$defined_width)
-			{
-
-				list($img_width, $img_height, $type) = api_getimagesize($this->base_work_dir.$this->created_dir.'/'.$image);
-
-				$new_width = $max_width-10;
-				if($img_width > $new_width)
-				{
-					$picture_resized = str_ireplace('<img','<img width="'.$new_width.'" ',$images[0][$key]);
-					$content = str_replace($images[0][$key],$picture_resized,$content);
-				}
-
-			}
-			else if($img_width > $max_width-10)
-			{
-				$picture_resized = str_ireplace('width='.$img_width,'width="'.($max_width-10).'"',$images[0][$key]);
-				$content = str_replace($images[0][$key],$picture_resized,$content);
-			}
-		}
-
-
-    	return $content;
-
-    }
-    /**
-     * Add documents to the visioconference (to be implemented)
-     */
-    function add_docs_to_visio (){
-
-    }
-}
-?>
+     */
+    function format_page_content($header, $content)
+    {
+
+
+		// limit the width of the doc
+		list($max_width, $max_height) = explode('x',api_get_setting('service_ppt2lp','size'));
+
+		$content = preg_replace("|<body[^>]*>|i","\\0\r\n<div style=\"width:".$max_width."\">",$content, -1,$count);
+		if($count < 1)
+		{
+			$content = '<body><div style="width:'.$max_width.'">'.$content;
+		}
+
+		$content = preg_replace('|</body>|i','</div>\\0',$content, -1, $count);
+		if($count < 1)
+		{
+			$content = $content.'</div></body>';
+		}
+
+		// add the headers
+		$content = $header.$content;
+
+
+		// resize all the picture to the max_width-10
+		preg_match_all("|<img[^src]*src=\"([^\"]*)\"[^>]*>|i",$content,$images);
+
+		foreach ($images[1] as $key => $image)
+		{
+			// check if the <img tag soon has a width attribute
+			$defined_width = preg_match("|width=([^\s]*)|i",$images[0][$key], $img_width);
+			$img_width = $img_width[1];
+			if(!$defined_width)
+			{
+
+				list($img_width, $img_height, $type) = api_getimagesize($this->base_work_dir.$this->created_dir.'/'.$image);
+
+				$new_width = $max_width-10;
+				if($img_width > $new_width)
+				{
+					$picture_resized = str_ireplace('<img','<img width="'.$new_width.'" ',$images[0][$key]);
+					$content = str_replace($images[0][$key],$picture_resized,$content);
+				}
+
+			}
+			else if($img_width > $max_width-10)
+			{
+				$picture_resized = str_ireplace('width='.$img_width,'width="'.($max_width-10).'"',$images[0][$key]);
+				$content = str_replace($images[0][$key],$picture_resized,$content);
+			}
+		}
+
+
+    	return $content;
+
+    }
+    /**
+     * Add documents to the visioconference (to be implemented)
+     */
+    function add_docs_to_visio (){
+
+    }
+}
+?>

+ 1117 - 1117
main/newscorm/resourcelinker.php

@@ -1,1146 +1,1146 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2005 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Patrick Cool (patrick.cool@ugent.be)
-	Copyright (c) Denes Nagy
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-* @author Patrick Cool, original code
-* @author Denes Nagy - many bugfixes and improvements, adjusted for learning path
-* @author Roan Embrechts - refactoring, code cleaning
-* @package dokeos.resourcelinker
-* @todo reorganise code,
-* use Database API instead of creating table names locally.
-==============================================================================
-*/
-
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2005 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Patrick Cool (patrick.cool@ugent.be)
+	Copyright (c) Denes Nagy
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+* @author Patrick Cool, original code
+* @author Denes Nagy - many bugfixes and improvements, adjusted for learning path
+* @author Roan Embrechts - refactoring, code cleaning
+* @package dokeos.resourcelinker
+* @todo reorganise code,
+* use Database API instead of creating table names locally.
+==============================================================================
+*/
+
+/*
+==============================================================================
+		INIT SECTION
+==============================================================================
+*/
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
 // name of the language file that needs to be included
-$language_file = 'resourcelinker';
-require_once('back_compat.inc.php');
-$this_section=SECTION_COURSES;
-
-api_protect_course_script();
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
-*/
-include ('resourcelinker.inc.php');
-
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
-*/
-
-$link_table = Database :: get_course_table(TABLE_LINK);
-$item_property_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-
-//$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
-//$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-//$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-
-$action = $_REQUEST['action'];
-$add = $_REQUEST['add'];
-$chapter_id = $_REQUEST['parent_item_id'];
-$content = $_REQUEST['content'];
+$language_file = 'resourcelinker';
+require_once('back_compat.inc.php');
+$this_section=SECTION_COURSES;
+
+api_protect_course_script();
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
+*/
+include ('resourcelinker.inc.php');
+
+/*
+-----------------------------------------------------------
+	Constants and variables
+-----------------------------------------------------------
+*/
+
+$link_table = Database :: get_course_table(TABLE_LINK);
+$item_property_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+
+//$tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN);
+//$tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+//$tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+
+$action = $_REQUEST['action'];
+$add = $_REQUEST['add'];
+$chapter_id = $_REQUEST['parent_item_id'];
+$content = $_REQUEST['content'];
 // Note by Patrick Cool: this has been solved belowd. This piece of code hacking produced too much errors.
-/*
-if(empty($content)){
-	//adds a default to the item-type selection
-	$content = 'Document';
-}
-*/
-$folder = $_REQUEST['folder'];
-$id = $_REQUEST['id'];
-$learnpath_id = $_REQUEST['lp_id'];
-$originalresource = $_REQUEST['originalresource'];
-$show_resources = $_REQUEST['show_resources'];
-$source_forum = $_REQUEST['source_forum'];
-$source_id = $_REQUEST['source_id'];
-$target = $_REQUEST['target'];
-$external_link = $_REQUEST['external_link'];
-
-$from_learnpath = $_SESSION['from_learnpath'];
-
-// this variable controls wether the link to add a chapter in a module or
-// another chapter is shown. This allows to create multi-level learnpaths,
-// but export features are not ready for this, yet, so use at your own risks
-// default : false -> do not display link
-// This setting should be moved to the platform configuration page in time...
-$multi_level_learnpath = true;
-
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
-if ($from_learnpath == 'yes')
-{
-	//start from clear every time in LearnPath Builder
-	$_SESSION['addedresource'] = null;
-	$_SESSION['addedresourceid'] = null;
-	$_SESSION['addedresourceassigned'] = null;
-	unset ($_SESSION['addedresource']);
-	unset ($_SESSION['addedresourceid']);
-	unset ($_SESSION['addedresourceassigned']);
-}
-
-// Process a new chapter?
-if (!empty ($_POST['add_chapter']) && !empty ($_POST['title']))
-{
-	$title = $_POST['title'];
-	$description = '';
-	/*if (!empty ($_POST['description']))
-	{
-		$description = $_POST['description'];
-	}*/
-
-	// get max display_order so far in this parent chapter
-	$sql = "SELECT MAX(display_order) as maxi FROM $tbl_lp_item " .
-			"WHERE lp_id = $learnpath_id ".
-			" AND parent_item_id = $chapter_id";
-	$res = Database::query($sql, __FILE__, __LINE__);
-	$row = mysql_fetch_array($res);
-	$lastorder_item = $row['maxi'];
-	if(empty($lastorder_item)){
-		$lastorder_item = 0;
-		$previous = 0;
-	}else{
-		$sql = "SELECT id FROM $tbl_lp_item " .
-				"WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id AND display_order = $lastorder_item";
-		$result = Database::query($sql, __FILE__, __LINE__);
+/*
+if(empty($content)){
+	//adds a default to the item-type selection
+	$content = 'Document';
+}
+*/
+$folder = $_REQUEST['folder'];
+$id = $_REQUEST['id'];
+$learnpath_id = $_REQUEST['lp_id'];
+$originalresource = $_REQUEST['originalresource'];
+$show_resources = $_REQUEST['show_resources'];
+$source_forum = $_REQUEST['source_forum'];
+$source_id = $_REQUEST['source_id'];
+$target = $_REQUEST['target'];
+$external_link = $_REQUEST['external_link'];
+
+$from_learnpath = $_SESSION['from_learnpath'];
+
+// this variable controls wether the link to add a chapter in a module or
+// another chapter is shown. This allows to create multi-level learnpaths,
+// but export features are not ready for this, yet, so use at your own risks
+// default : false -> do not display link
+// This setting should be moved to the platform configuration page in time...
+$multi_level_learnpath = true;
+
+/*
+==============================================================================
+		MAIN CODE
+==============================================================================
+*/
+if ($from_learnpath == 'yes')
+{
+	//start from clear every time in LearnPath Builder
+	$_SESSION['addedresource'] = null;
+	$_SESSION['addedresourceid'] = null;
+	$_SESSION['addedresourceassigned'] = null;
+	unset ($_SESSION['addedresource']);
+	unset ($_SESSION['addedresourceid']);
+	unset ($_SESSION['addedresourceassigned']);
+}
+
+// Process a new chapter?
+if (!empty ($_POST['add_chapter']) && !empty ($_POST['title']))
+{
+	$title = $_POST['title'];
+	$description = '';
+	/*if (!empty ($_POST['description']))
+	{
+		$description = $_POST['description'];
+	}*/
+
+	// get max display_order so far in this parent chapter
+	$sql = "SELECT MAX(display_order) as maxi FROM $tbl_lp_item " .
+			"WHERE lp_id = $learnpath_id ".
+			" AND parent_item_id = $chapter_id";
+	$res = Database::query($sql, __FILE__, __LINE__);
+	$row = mysql_fetch_array($res);
+	$lastorder_item = $row['maxi'];
+	if(empty($lastorder_item)){
+		$lastorder_item = 0;
+		$previous = 0;
+	}else{
+		$sql = "SELECT id FROM $tbl_lp_item " .
+				"WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id AND display_order = $lastorder_item";
+		$result = Database::query($sql, __FILE__, __LINE__);
 		$row = Database::fetch_array($result);
-		$previous = $row['id'];
+		$previous = $row['id'];
 	}
-	$order = $lastorder_item+1;
-
-	$sql = "INSERT INTO $tbl_lp_item "."(lp_id,item_type,title,parent_item_id,previous_item_id, next_item_id, display_order) " .
-			"VALUES "."($learnpath_id,'dokeos_chapter','$title', $chapter_id, $previous, 0, $order )";
-	//error_log('New LP - Inserting new resource: '.$sql,0);
-	$res = Database::query($sql, __FILE__, __LINE__);
-	$my_id = Database::get_last_insert_id($res);
-	if($previous>0){
-		$sql = "UPDATE $tbl_lp_item SET next_item_id = $my_id WHERE id=$previous";
-		$res = Database::query($sql,__FILE__,__LINE__);
-	}
-	if ($res !== false)
-	{
-		$title = '';
-		$description = '';
-	}
-	$resource_added = true;
-}
-
-// This if when a external link is submitted
-if (!empty ($_POST['external_link_submit']))
-{
-	if ($external_link == "" || $external_link == "http://")
-	  $InvalidURL = 1;
-	else
-	{
-	$add = true;
-	if ($add_2_links != "niet toevoegen")
-	{
-		// add external link to the links table.
-		$pos = strpos($external_link, 'ttp:');
-		if ($pos == '')
-		{
-			$external_link = 'http://'.$external_link;
-		}
-
-		$sql = "INSERT INTO $link_table (url, title, category_id) VALUES ('$external_link','$external_link','$add_2_links')";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		$addedresource[] = "Link";
-		$addedresourceid[] = mysql_insert_id();
-		$_SESSION['addedresource'] = $addedresource;
-		$_SESSION['addedresourceid'] = $addedresourceid;
-	}
-	else
-	{
-		// do not add external link to the links table
-		$addedresource[] = "Externallink";
-		$addedresourceid[] = $external_link;
-		$_SESSION['addedresource'] = $addedresource;
-		$_SESSION['addedresourceid'] = $addedresourceid;
-	}
-	}
-}
-
-// loading the session variables into local array
-$addedresource = $_SESSION['addedresource'];
-$addedresourceid = $_SESSION['addedresourceid'];
-
-// This is when a resource was added to the session
-if ($add)
-{
-	// adding the new variable to the local array
-	if (empty ($_POST['external_link_submit']))
-	{
-		//that case is already arranged, see upwards
-		$addedresource[] = $content;
-		$addedresourceid[] = $add;
-	}
-	$addedresourceassigned[] = 0;
-
-	// loading the local array into the session variable
-	$_SESSION['addedresource'] = $addedresource;
-	$_SESSION['addedresourceid'] = $addedresourceid;
-
-	//---------------------------------------
-	//we assign to chapters immediately !
-	//---------------------------------------
-	$resource_added = false;
-	if ($from_learnpath == 'yes')
-	{
-		$i = 0;
-		//calculating the last order of the items of this chapter
-		$sql = "SELECT MAX(display_order) as maxi FROM $tbl_lp_item " .
-				"WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id";
-		$result = Database::query($sql, __FILE__, __LINE__);
+	$order = $lastorder_item+1;
+
+	$sql = "INSERT INTO $tbl_lp_item "."(lp_id,item_type,title,parent_item_id,previous_item_id, next_item_id, display_order) " .
+			"VALUES "."($learnpath_id,'dokeos_chapter','$title', $chapter_id, $previous, 0, $order )";
+	//error_log('New LP - Inserting new resource: '.$sql,0);
+	$res = Database::query($sql, __FILE__, __LINE__);
+	$my_id = Database::get_last_insert_id($res);
+	if($previous>0){
+		$sql = "UPDATE $tbl_lp_item SET next_item_id = $my_id WHERE id=$previous";
+		$res = Database::query($sql,__FILE__,__LINE__);
+	}
+	if ($res !== false)
+	{
+		$title = '';
+		$description = '';
+	}
+	$resource_added = true;
+}
+
+// This if when a external link is submitted
+if (!empty ($_POST['external_link_submit']))
+{
+	if ($external_link == "" || $external_link == "http://")
+	  $InvalidURL = 1;
+	else
+	{
+	$add = true;
+	if ($add_2_links != "niet toevoegen")
+	{
+		// add external link to the links table.
+		$pos = strpos($external_link, 'ttp:');
+		if ($pos == '')
+		{
+			$external_link = 'http://'.$external_link;
+		}
+
+		$sql = "INSERT INTO $link_table (url, title, category_id) VALUES ('$external_link','$external_link','$add_2_links')";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		$addedresource[] = "Link";
+		$addedresourceid[] = mysql_insert_id();
+		$_SESSION['addedresource'] = $addedresource;
+		$_SESSION['addedresourceid'] = $addedresourceid;
+	}
+	else
+	{
+		// do not add external link to the links table
+		$addedresource[] = "Externallink";
+		$addedresourceid[] = $external_link;
+		$_SESSION['addedresource'] = $addedresource;
+		$_SESSION['addedresourceid'] = $addedresourceid;
+	}
+	}
+}
+
+// loading the session variables into local array
+$addedresource = $_SESSION['addedresource'];
+$addedresourceid = $_SESSION['addedresourceid'];
+
+// This is when a resource was added to the session
+if ($add)
+{
+	// adding the new variable to the local array
+	if (empty ($_POST['external_link_submit']))
+	{
+		//that case is already arranged, see upwards
+		$addedresource[] = $content;
+		$addedresourceid[] = $add;
+	}
+	$addedresourceassigned[] = 0;
+
+	// loading the local array into the session variable
+	$_SESSION['addedresource'] = $addedresource;
+	$_SESSION['addedresourceid'] = $addedresourceid;
+
+	//---------------------------------------
+	//we assign to chapters immediately !
+	//---------------------------------------
+	$resource_added = false;
+	if ($from_learnpath == 'yes')
+	{
+		$i = 0;
+		//calculating the last order of the items of this chapter
+		$sql = "SELECT MAX(display_order) as maxi FROM $tbl_lp_item " .
+				"WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id";
+		$result = Database::query($sql, __FILE__, __LINE__);
 		$row = Database::fetch_array($result);
-		$lastorder_item = $row['maxi'];
-		if(empty($lastorder_item)){
-			$lastorder_item = 0;
-			$previous = 0;
-		}else{
-			$sql = "SELECT id FROM $tbl_lp_item " .
-					"WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id AND display_order = $lastorder_item";
-			//error_log('New LP - resourcelinker.php - '.$sql,0);
-			$result = Database::query($sql, __FILE__, __LINE__);
+		$lastorder_item = $row['maxi'];
+		if(empty($lastorder_item)){
+			$lastorder_item = 0;
+			$previous = 0;
+		}else{
+			$sql = "SELECT id FROM $tbl_lp_item " .
+					"WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id AND display_order = $lastorder_item";
+			//error_log('New LP - resourcelinker.php - '.$sql,0);
+			$result = Database::query($sql, __FILE__, __LINE__);
 			$row = Database::fetch_array($result);
-			$previous = $row['id'];
+			$previous = $row['id'];
 		}
-		$lastorder = $lastorder_item+1;
-		foreach ($addedresource as $addedresource_item)
-		{
-			// in the case we added a chapter, add this into the chapters list with the correct parent_id
-			if ($addedresource_item == "Chap")
-			{
-				$sql = "INSERT INTO $tbl_lp_item " .
-						"(lp_id,item_type,title,parent_item_id,previous_item_id,next_item_id,display_order) " .
-						"VALUES (".$learnpath_id.",'dokeos_chapter','".$learnpath_chapter_name."',".$chapter_id.",$previous,0,".$lastorder.")";
-				//error_log('New LP - Inserting new resource: '.$sql,0);
-				$res = Database::query($sql, __FILE__, __LINE__);
-				$my_id = Database::get_last_insert_id($res);
-				if($previous>0){
-					$sql = "UPDATE $tbl_lp_item SET next_item_id = $my_id WHERE id=$previous";
-					$res = Database::query($sql,__FILE__,__LINE__);
-				}
-			}
-
-			if (!$addedresourceassigned[$i])
-			{
-				//not to assign it twice
-				switch($addedresource_item){
-					case 'Assignment':
-					case 'Ass':
-						//set tool type
-						$addedresource_item = "Assignments";
-						$title = get_lang('Assignments');
-						break;
-					case 'Drop':
-						//$addedresource_item = "Dropbox";
-						$addedresource_item = TOOL_DROPBOX;
-						$title = get_lang('dropbox');
-						break;
-					case 'Intro':
-						$addedresource_item = "Introduction_text";
-						//$addedresource_item = TOOL_INTRO;
-						$title = get_lang('IntroductionText');
-						break;
-					case 'Course_desc':
-						//$addedresource_item = "Course_description";
-						$addedresource_item = TOOL_COURSE_DESCRIPTION;
-						$title = get_lang('CourseDescription');
-						break;
-					case 'Group':
-						//$addedresource_item = "Groups";
-						$addedresource_item = TOOL_GROUP;
-						$title = get_lang('Groups');
-						break;
-					case 'User':
-						//$addedresource_item = "Users";
-						$addedresource_item = TOOL_USER;
-						$title = get_lang('Users');
-						break;
-					case 'Link':
-						/*
-						if ($target == '')
-						{
-							$target = '_self';
-						}
-						*/
-						//$addedresource_item .= ' '.$target;
-						//error_log('New LP - resourcelinker.php - In Link addition: '.$external_link);
-						$addedresource_item = TOOL_LINK;
-						$title = $external_link;
-						break;
-					case 'Document':
-						$addedresource_item = TOOL_DOCUMENT;
-						//get title from tool-type table
-						$tooltable = Database::get_course_table(TABLE_DOCUMENT);
-						$result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i],__FILE__,__LINE__);
-						$myrow=mysql_fetch_array($result);
-						$title = $myrow['title'];
-						break;
-					case 'Exercise':
-						$addedresource_item = TOOL_QUIZ;
-						//get title from tool-type table
-						$tooltable = Database::get_course_table(TABLE_QUIZ_TEST);
-						$result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i],__FILE__,__LINE__);
-						$myrow=mysql_fetch_array($result);
-						$title = $myrow['title'];
-						break;
-					case 'Forum':
-						$addedresource_item = TOOL_FORUM;
-						//TODO
-						break;
-					case 'Agenda':
-						$addedresource_item = TOOL_CALENDAR_EVENT;
-						//get title from tool-type table
-						$tooltable = Database::get_course_table(TABLE_AGENDA);
-						$result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i],__FILE__,__LINE__);
-						$myrow=mysql_fetch_array($result);
+		$lastorder = $lastorder_item+1;
+		foreach ($addedresource as $addedresource_item)
+		{
+			// in the case we added a chapter, add this into the chapters list with the correct parent_id
+			if ($addedresource_item == "Chap")
+			{
+				$sql = "INSERT INTO $tbl_lp_item " .
+						"(lp_id,item_type,title,parent_item_id,previous_item_id,next_item_id,display_order) " .
+						"VALUES (".$learnpath_id.",'dokeos_chapter','".$learnpath_chapter_name."',".$chapter_id.",$previous,0,".$lastorder.")";
+				//error_log('New LP - Inserting new resource: '.$sql,0);
+				$res = Database::query($sql, __FILE__, __LINE__);
+				$my_id = Database::get_last_insert_id($res);
+				if($previous>0){
+					$sql = "UPDATE $tbl_lp_item SET next_item_id = $my_id WHERE id=$previous";
+					$res = Database::query($sql,__FILE__,__LINE__);
+				}
+			}
+
+			if (!$addedresourceassigned[$i])
+			{
+				//not to assign it twice
+				switch($addedresource_item){
+					case 'Assignment':
+					case 'Ass':
+						//set tool type
+						$addedresource_item = "Assignments";
+						$title = get_lang('Assignments');
+						break;
+					case 'Drop':
+						//$addedresource_item = "Dropbox";
+						$addedresource_item = TOOL_DROPBOX;
+						$title = get_lang('dropbox');
+						break;
+					case 'Intro':
+						$addedresource_item = "Introduction_text";
+						//$addedresource_item = TOOL_INTRO;
+						$title = get_lang('IntroductionText');
+						break;
+					case 'Course_desc':
+						//$addedresource_item = "Course_description";
+						$addedresource_item = TOOL_COURSE_DESCRIPTION;
+						$title = get_lang('CourseDescription');
+						break;
+					case 'Group':
+						//$addedresource_item = "Groups";
+						$addedresource_item = TOOL_GROUP;
+						$title = get_lang('Groups');
+						break;
+					case 'User':
+						//$addedresource_item = "Users";
+						$addedresource_item = TOOL_USER;
+						$title = get_lang('Users');
+						break;
+					case 'Link':
+						/*
+						if ($target == '')
+						{
+							$target = '_self';
+						}
+						*/
+						//$addedresource_item .= ' '.$target;
+						//error_log('New LP - resourcelinker.php - In Link addition: '.$external_link);
+						$addedresource_item = TOOL_LINK;
+						$title = $external_link;
+						break;
+					case 'Document':
+						$addedresource_item = TOOL_DOCUMENT;
+						//get title from tool-type table
+						$tooltable = Database::get_course_table(TABLE_DOCUMENT);
+						$result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i],__FILE__,__LINE__);
+						$myrow=mysql_fetch_array($result);
+						$title = $myrow['title'];
+						break;
+					case 'Exercise':
+						$addedresource_item = TOOL_QUIZ;
+						//get title from tool-type table
+						$tooltable = Database::get_course_table(TABLE_QUIZ_TEST);
+						$result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i],__FILE__,__LINE__);
+						$myrow=mysql_fetch_array($result);
 						$title = $myrow['title'];
-						break;
-					case 'Ad_Valvas':
-						$addedresource_item = TOOL_ANNOUNCEMENT;
-						//get title from tool-type table
-						$tooltable = Database::get_course_table(TABLE_ANNOUNCEMENT);
-						$result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i],__FILE__,__LINE__);
-						$myrow=mysql_fetch_array($result);
+						break;
+					case 'Forum':
+						$addedresource_item = TOOL_FORUM;
+						//TODO
+						break;
+					case 'Agenda':
+						$addedresource_item = TOOL_CALENDAR_EVENT;
+						//get title from tool-type table
+						$tooltable = Database::get_course_table(TABLE_AGENDA);
+						$result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i],__FILE__,__LINE__);
+						$myrow=mysql_fetch_array($result);
 						$title = $myrow['title'];
-						break;
-
-				}
-				$sql = "INSERT INTO $tbl_lp_item (lp_id, title, parent_item_id, item_type, ref, previous_item_id, next_item_id, display_order) " .
-						"VALUES ($learnpath_id, '$title','$chapter_id', '$addedresource_item','$addedresourceid[$i]',$previous,0,'".$lastorder."')";
-				//error_log('New LP - Inserting new resource: '.$sql,0);
-				$result = Database::query($sql, __FILE__, __LINE__);
-				$my_id = Database::get_last_insert_id($result);
-				if($previous>0){
-					$sql = "UPDATE $tbl_lp_item SET next_item_id = $my_id WHERE id = $previous";
-					//error_log($sql,0);
-					$res = Database::query($sql,__FILE__,__LINE__);
-				}
-				$addedresourceassigned[$i] = 1;
-				$resource_added = true;
-			}
-			$i ++;
-			$lastorder ++;
-		}
-		//$_SESSION['addedresource']=null;
-		//$_SESSION['addedresourceid']=null;
-		// cleaning up the session once again
-		$_SESSION['addedresource'] = null;
-   		$_SESSION['addedresourceid'] = null;
-   		$_SESSION['addedresourceassigned'] = null;
-   		unset ($_SESSION['addedresource']);
-   		unset ($_SESSION['addedresourceid']);
+						break;
+					case 'Ad_Valvas':
+						$addedresource_item = TOOL_ANNOUNCEMENT;
+						//get title from tool-type table
+						$tooltable = Database::get_course_table(TABLE_ANNOUNCEMENT);
+						$result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i],__FILE__,__LINE__);
+						$myrow=mysql_fetch_array($result);
+						$title = $myrow['title'];
+						break;
+
+				}
+				$sql = "INSERT INTO $tbl_lp_item (lp_id, title, parent_item_id, item_type, ref, previous_item_id, next_item_id, display_order) " .
+						"VALUES ($learnpath_id, '$title','$chapter_id', '$addedresource_item','$addedresourceid[$i]',$previous,0,'".$lastorder."')";
+				//error_log('New LP - Inserting new resource: '.$sql,0);
+				$result = Database::query($sql, __FILE__, __LINE__);
+				$my_id = Database::get_last_insert_id($result);
+				if($previous>0){
+					$sql = "UPDATE $tbl_lp_item SET next_item_id = $my_id WHERE id = $previous";
+					//error_log($sql,0);
+					$res = Database::query($sql,__FILE__,__LINE__);
+				}
+				$addedresourceassigned[$i] = 1;
+				$resource_added = true;
+			}
+			$i ++;
+			$lastorder ++;
+		}
+		//$_SESSION['addedresource']=null;
+		//$_SESSION['addedresourceid']=null;
+		// cleaning up the session once again
+		$_SESSION['addedresource'] = null;
+   		$_SESSION['addedresourceid'] = null;
+   		$_SESSION['addedresourceassigned'] = null;
+   		unset ($_SESSION['addedresource']);
+   		unset ($_SESSION['addedresourceid']);
    		unset ($_SESSION['addedresourceassigned']);
-	}
-}
-
-/*
-==============================================================================
-	BREADCRUMBS
-	This part is to allow going back to the tool where you came from
-	in a previous version I used the table tool_list, but since the forum can access the
-	resource_linker from two different pages (newtopic.php and editpost.php) and this is different
-	from the link field in tool_list, I decide to hardcode this stuff here.
-	By doing this, you can easily control which pages can access the toollinker and which not.
-==============================================================================
-*/
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
-}
-
+	}
+}
+
+/*
+==============================================================================
+	BREADCRUMBS
+	This part is to allow going back to the tool where you came from
+	in a previous version I used the table tool_list, but since the forum can access the
+	resource_linker from two different pages (newtopic.php and editpost.php) and this is different
+	from the link field in tool_list, I decide to hardcode this stuff here.
+	By doing this, you can easily control which pages can access the toollinker and which not.
+==============================================================================
+*/
+if (isset($_SESSION['gradebook'])){
+	$gradebook=	$_SESSION['gradebook'];
+}
+
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('Gradebook')
-		);
-}
-
-if ($_GET["source_id"])
-{
-	switch ($_GET["source_id"])
-	{
-		case "1" : // coming from Agenda
-			if ($action == "edit")
-			{
-				$url = "../calendar/agenda.php?action=edit&id=49&originalresource=$originalresource";
-			}
-			elseif ($action == "add")
-		{
-				$url = "../calendar/agenda.php?action=add&originalresource=$originalresource";
-			}
-			else
-			{
-				$url = "../calendar/agenda.php?action=add";
-			}
-			$originaltoolname = get_lang("Agenda");
-			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
-			session_unregister('from_learnpath');
-			unset ($from_learnpath);
-			break;
-		case "2" : // coming from forum: new topic
-			$url = "../phpbb/newtopic.php?forum=$source_forum&md5=$md5";
-			$originaltoolname = get_lang("ForumAddNewTopic");
-			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
-			session_unregister('from_learnpath');
-			unset ($from_learnpath);
-			break;
-		case "3" : // coming from forum: edit topic
-			$url = "../phpbb/editpost.php?post_id=$post_id&topic=$topic&forum=$forum&md5=$md5&originalresource=no";
-			$originaltoolname = get_lang("ForumEditTopic");
-			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
-			session_unregister('from_learnpath');
-			unset ($from_learnpath);
-			break;
-		case "4" : // coming from exercises: edit topic
-			$url = "../exercice/admin.php?modifyAnswers=$modifyAnswers";
-			$originaltoolname = get_lang("ExerciseAnswers");
-			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
-			session_unregister('from_learnpath');
-			unset ($from_learnpath);
-			break;
-		case "5" : // coming from learning path
-			$from_learnpath = 'yes';
-			api_session_register('from_learnpath');
-			break;
-		case "6" : // coming from forum: reply
-			$url = "../phpbb/reply.php?topic=$topic&forum=$forum&parentid=$parentid";
+	$interbreadcrumb[]= array (
+			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+}
+
+if ($_GET["source_id"])
+{
+	switch ($_GET["source_id"])
+	{
+		case "1" : // coming from Agenda
+			if ($action == "edit")
+			{
+				$url = "../calendar/agenda.php?action=edit&id=49&originalresource=$originalresource";
+			}
+			elseif ($action == "add")
+		{
+				$url = "../calendar/agenda.php?action=add&originalresource=$originalresource";
+			}
+			else
+			{
+				$url = "../calendar/agenda.php?action=add";
+			}
+			$originaltoolname = get_lang("Agenda");
+			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
+			session_unregister('from_learnpath');
+			unset ($from_learnpath);
+			break;
+		case "2" : // coming from forum: new topic
+			$url = "../phpbb/newtopic.php?forum=$source_forum&md5=$md5";
+			$originaltoolname = get_lang("ForumAddNewTopic");
+			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
+			session_unregister('from_learnpath');
+			unset ($from_learnpath);
+			break;
+		case "3" : // coming from forum: edit topic
+			$url = "../phpbb/editpost.php?post_id=$post_id&topic=$topic&forum=$forum&md5=$md5&originalresource=no";
+			$originaltoolname = get_lang("ForumEditTopic");
+			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
+			session_unregister('from_learnpath');
+			unset ($from_learnpath);
+			break;
+		case "4" : // coming from exercises: edit topic
+			$url = "../exercice/admin.php?modifyAnswers=$modifyAnswers";
+			$originaltoolname = get_lang("ExerciseAnswers");
+			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
+			session_unregister('from_learnpath');
+			unset ($from_learnpath);
+			break;
+		case "5" : // coming from learning path
+			$from_learnpath = 'yes';
+			api_session_register('from_learnpath');
+			break;
+		case "6" : // coming from forum: reply
+			$url = "../phpbb/reply.php?topic=$topic&forum=$forum&parentid=$parentid";
 			$url = $_SESSION['origintoolurl'];
-			$originaltoolname = get_lang("ForumReply");
-			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
-			session_unregister('from_learnpath');
-			unset ($from_learnpath);
-			break;
-			/*************************************** add Frederik.Vermeire@pandora.be *************************************/
-
-		case "7" : // coming from Ad_Valvas
-			if ($action == "edit")
-			{
-				$url = "../announcements/announcements.php?action=edit&id=49&originalresource=$originalresource";
-			}
-			elseif ($action == "add")
-		{
-				$url = "../announcements/announcements.php?action=add&originalresource=$originalresource";
-			}
-			else
-			{
-				$url = "../announcements/announcements.php?action=add";
-			}
-			$originaltoolname = get_lang("AdValvas");
-			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
+			$originaltoolname = get_lang("ForumReply");
+			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
 			session_unregister('from_learnpath');
-			unset ($from_learnpath);
-			break;
-			/*************************************** end add Frederik.Vermeire@pandora.be *********************************/
-
-	}
+			unset ($from_learnpath);
+			break;
+			/*************************************** add Frederik.Vermeire@pandora.be *************************************/
+
+		case "7" : // coming from Ad_Valvas
+			if ($action == "edit")
+			{
+				$url = "../announcements/announcements.php?action=edit&id=49&originalresource=$originalresource";
+			}
+			elseif ($action == "add")
+		{
+				$url = "../announcements/announcements.php?action=add&originalresource=$originalresource";
+			}
+			else
+			{
+				$url = "../announcements/announcements.php?action=add";
+			}
+			$originaltoolname = get_lang("AdValvas");
+			$breadcrumbelement = array ("url" => $url, "name" => $originaltoolname);
+			session_unregister('from_learnpath');
+			unset ($from_learnpath);
+			break;
+			/*************************************** end add Frederik.Vermeire@pandora.be *********************************/
+
+	}
 	// We do not come from the learning path. We store the name of the tool & url in a session.
-	if ($from_learnpath != 'yes')
-	{
-		if (!$_SESSION["origintoolurl"] OR $_SESSION["origintoolurl"]<>$interbreadcrumb["url"])
-		{
-			$_SESSION["origintoolurl"] = $breadcrumbelement["url"];
-			$_SESSION["origintoolname"] = $breadcrumbelement["name"];
-			$interbreadcrumb = "";
-		}
-	}
-
-}
-
+	if ($from_learnpath != 'yes')
+	{
+		if (!$_SESSION["origintoolurl"] OR $_SESSION["origintoolurl"]<>$interbreadcrumb["url"])
+		{
+			$_SESSION["origintoolurl"] = $breadcrumbelement["url"];
+			$_SESSION["origintoolname"] = $breadcrumbelement["name"];
+			$interbreadcrumb = "";
+		}
+	}
+
+}
+
 // This part of the code is the actual breadcrumb mechanism. If we do not come from the learning path we use
 // the information from the session. Else we use the information of the learningpath itself.
-if ($from_learnpath != 'yes')
-{
-	$nameTools = get_lang('Attachment');
-	$interbreadcrumb[] = array ("url" => $_SESSION["origintoolurl"], "name" => $_SESSION["origintoolname"]);
-}
-else
-{
-	$learnpath_select_query = "	SELECT * FROM $tbl_lp
-		  								WHERE id=$learnpath_id";
-	$sql_result = Database::query($learnpath_select_query);
-	$therow = mysql_fetch_array($sql_result);
-
-	$learnpath_chapter_query = "	SELECT * FROM $tbl_lp_item
-		  								WHERE (lp_id = '$learnpath_id' and id = '$chapter_id')";
-	$sql_result = Database::query($learnpath_chapter_query);
-	$therow2 = mysql_fetch_array($sql_result);
-
-	$from_learnpath = 'yes';
-	session_register('from_learnpath');
-	$interbreadcrumb[] = array ("url" => "../newscorm/lp_controller.php?action=list", "name" => get_lang('LearningPath'));
-	$interbreadcrumb[] = array ("url" => "../newscorm/lp_controller.php?action=admin_view&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
-	$interbreadcrumb[] = array ("url" => api_get_self()."?action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no", "name" => "{$therow2['title']}");
-
-}
-
-$htmlHeadXtra[] = '<script type="text/javascript">
-/* <![CDATA[ */
-	function targetfunc(input)
-	{
-		window.location=window.location+"&amp;target="+document.learnpath_link.target.value;
-	}
-/* ]]> */
-</script>';
-
-Display :: display_header($nameTools);
-
-echo "<h3>".$nameTools;
-if ($from_learnpath == 'yes')
-{
-	echo get_lang("AddResource")." - {$therow2['title']}";
-}
-echo "</h3>";
-
+if ($from_learnpath != 'yes')
+{
+	$nameTools = get_lang('Attachment');
+	$interbreadcrumb[] = array ("url" => $_SESSION["origintoolurl"], "name" => $_SESSION["origintoolname"]);
+}
+else
+{
+	$learnpath_select_query = "	SELECT * FROM $tbl_lp
+		  								WHERE id=$learnpath_id";
+	$sql_result = Database::query($learnpath_select_query);
+	$therow = mysql_fetch_array($sql_result);
+
+	$learnpath_chapter_query = "	SELECT * FROM $tbl_lp_item
+		  								WHERE (lp_id = '$learnpath_id' and id = '$chapter_id')";
+	$sql_result = Database::query($learnpath_chapter_query);
+	$therow2 = mysql_fetch_array($sql_result);
+
+	$from_learnpath = 'yes';
+	session_register('from_learnpath');
+	$interbreadcrumb[] = array ("url" => "../newscorm/lp_controller.php?action=list", "name" => get_lang('LearningPath'));
+	$interbreadcrumb[] = array ("url" => "../newscorm/lp_controller.php?action=admin_view&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
+	$interbreadcrumb[] = array ("url" => api_get_self()."?action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no", "name" => "{$therow2['title']}");
+
+}
+
+$htmlHeadXtra[] = '<script type="text/javascript">
+/* <![CDATA[ */
+	function targetfunc(input)
+	{
+		window.location=window.location+"&amp;target="+document.learnpath_link.target.value;
+	}
+/* ]]> */
+</script>';
+
+Display :: display_header($nameTools);
+
+echo "<h3>".$nameTools;
+if ($from_learnpath == 'yes')
+{
+	echo get_lang("AddResource")." - {$therow2['title']}";
+}
+echo "</h3>";
+
 // we retrieve the tools that are active.
-// We use this to check which resources a student may add (only the modules that are active)
-// see http://www.dokeos.com/forum/viewtopic.php?t=4858
-$active_modules=array();
-$tool_table = Database::get_course_table(TABLE_TOOL_LIST);
-$sql_select_active="SELECT * FROM $tool_table WHERE visibility='1'";
-$result_select_active=Database::query($sql_select_active);
-while ($row=mysql_fetch_array($result_select_active))
-{
-	$active_modules[]=$row['name'];
-}
-
-
-?>
-
-<table width="100%" border="0" cellspacing="0" cellpadding="0">
-  <tr>
-    <td width="300" valign="top" style='padding-right:15px;'>
-      <table width="300" border="0" cellspacing="0" cellpadding="0" style='border-right:1px solid grey;'>
-<?php if ($from_learnpath != 'yes') { ?>
-		<tr>
-          <td width="26%"><b><?php echo get_lang('CourseResources'); ?></b></td>
-        </tr>
+// We use this to check which resources a student may add (only the modules that are active)
+// see http://www.dokeos.com/forum/viewtopic.php?t=4858
+$active_modules=array();
+$tool_table = Database::get_course_table(TABLE_TOOL_LIST);
+$sql_select_active="SELECT * FROM $tool_table WHERE visibility='1'";
+$result_select_active=Database::query($sql_select_active);
+while ($row=mysql_fetch_array($result_select_active))
+{
+	$active_modules[]=$row['name'];
+}
+
+
+?>
+
+<table width="100%" border="0" cellspacing="0" cellpadding="0">
+  <tr>
+    <td width="300" valign="top" style='padding-right:15px;'>
+      <table width="300" border="0" cellspacing="0" cellpadding="0" style='border-right:1px solid grey;'>
+<?php if ($from_learnpath != 'yes') { ?>
+		<tr>
+          <td width="26%"><b><?php echo get_lang('CourseResources'); ?></b></td>
+        </tr>
         <?php
-        if (is_allowed_to_edit() OR in_array(TOOL_DOCUMENT,$active_modules))
-        {
-        ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Document&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Document')."</a>"; ?></td>
-        </tr>
+        if (is_allowed_to_edit() OR in_array(TOOL_DOCUMENT,$active_modules))
+        {
+        ?>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Document&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Document')."</a>"; ?></td>
+        </tr>
         <?php
         }
-        if (is_allowed_to_edit() OR in_array(TOOL_CALENDAR_EVENT,$active_modules))
-        {
-        ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Agenda&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Agenda')."</a>"; ?></td>
-        </tr>
+        if (is_allowed_to_edit() OR in_array(TOOL_CALENDAR_EVENT,$active_modules))
+        {
+        ?>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Agenda&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Agenda')."</a>"; ?></td>
+        </tr>
         <?php
         }
-        if (is_allowed_to_edit() OR in_array(TOOL_ANNOUNCEMENT,$active_modules))
-        {
-        ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Ad_Valvas&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('AdValvas')."</a>"; ?></td>
-        </tr>
+        if (is_allowed_to_edit() OR in_array(TOOL_ANNOUNCEMENT,$active_modules))
+        {
+        ?>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Ad_Valvas&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('AdValvas')."</a>"; ?></td>
+        </tr>
         <?php
         }
-        if (is_allowed_to_edit() OR in_array(TOOL_BB_FORUM,$active_modules))
-        {
-        ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Forum&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Forum')."</a>"; ?></td>
-        </tr>
+        if (is_allowed_to_edit() OR in_array(TOOL_BB_FORUM,$active_modules))
+        {
+        ?>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Forum&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Forum')."</a>"; ?></td>
+        </tr>
         <?php
-        }
-        if (is_allowed_to_edit() OR in_array(TOOL_LINK,$active_modules))
-        {
-        ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Link&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Link')."</a>"; ?></td>
-        </tr>
+        }
+        if (is_allowed_to_edit() OR in_array(TOOL_LINK,$active_modules))
+        {
+        ?>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Link&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Link')."</a>"; ?></td>
+        </tr>
         <?php
-        }
-        if (is_allowed_to_edit() OR in_array(TOOL_QUIZ,$active_modules))
-        {
-        ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Exercise&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Exercise')."</a>"; ?></td>
-        </tr>
-
-		<?php
-        }
-
-}
-else
-{
-?>
-
-
-
-		<!--tr>
-          <td width="26%"><b><?php echo get_lang('ExportableCourseResources'); ?></b></td>
-        </tr-->
-<?php if ($multi_level_learnpath === true ) { ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=chapter&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Chapter')."</a>"; ?></td>
-        </tr>
-<?php } ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Document&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Document')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Exercise&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Exercise')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Link&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Link')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Forum&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Forum')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Agenda&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Agenda')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Ad_Valvas&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('AdValvas')."</a>"; ?></td>
-        </tr>
-        <!--tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Course_description&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('CourseDescription')."</a>"; ?></td>
-        </tr-->
-        <!--tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Introduction_text&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('IntroductionText')."</a>"; ?></td>
-        </tr-->
-		<!--tr>
-          <td>&nbsp;</td>
-        </tr-->
-		<!--tr>
-          <td width="26%"><b><?php echo get_lang('DokeosRelatedCourseMaterial'); ?></b></td>
-        </tr-->
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Dropbox&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Dropbox')."</a>"; ?></td>
-        </tr>
-		<tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Assignment&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Assignments')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Groups&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Groups')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Users&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Users')."</a>"; ?></td>
-        </tr>
-
-		<?php
-
-}
-?>
-
-
-
-		<!--tr>
-          <td>&nbsp;</td>
-        </tr-->
-        <!--tr>
-          <td><b><?php echo get_lang("ExternalResources"); ?></b></td>
-        </tr-->
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Externallink&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('ExternalLink')."</a>"; ?></td>
-        </tr>
-		<?php
-
-if ($from_learnpath != 'yes')
-{
-	echo "<tr><td>&nbsp;</td></tr>";
-	echo "<tr><td><b>".get_lang('ResourcesAdded')." (";
-	echo count($addedresource);
-	echo ")</b></td></tr>";
-	echo "<tr><td nowrap><a href=\"".api_get_self()."?showresources=true&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('ShowDelete')."</a>";
-	echo "</td></tr>";
-}
-?>
-        <tr>
-          <td>&nbsp;</td>
-        </tr>
-        <!--<tr>
-          <td><b><?php echo get_lang('BackTo'); ?></b></td>
-        </tr>//-->
-        <tr>
-          <td>
-
-		  <?php
-
-if ($from_learnpath != 'yes')
-{
-	echo "<form method=\"post\" action=\"{$_SESSION['origintoolurl']}\" style=\"margin: 0px;\"><input type=\"submit\" value=\"".'  '.get_lang('Ok').'  '."\"></form>";
-}
-else
-{
-	echo "<form method=\"get\" action=\"lp_controller.php\" style=\"margin: 0px;\"><input type=\"hidden\" name=\"lp_id\" value=\"".htmlentities($learnpath_id)."\"><input type=\"hidden\" name=\"action\" value=\"admin_view\"><input type=\"submit\" value=\"".'  '.get_lang('Ok').'  '."\"></form>";
-}
-?>
-
-          </td>
-        </tr>
-        <tr>
-          <td>&nbsp;</td>
-        </tr>
-      </table>
-    </td>
-    <td valign="top">
-      <?php
-
-if ($resource_added)
-{
-	Display :: display_normal_message(get_lang("ResourceAdded"));
-}
-if ($InvalidURL)
-{
-    Display :: display_normal_message(get_lang("GiveURL"));
-}
-
-if ($from_learnpath != 'yes')
-{
-	echo count($addedresource)." ".strtolower(get_lang('ResourcesAdded'))."<br/>";
-}
-//echo "<hr>";
-
-// Agenda items -->
-if ($content == "Agenda")
-{
-	include (api_get_path(LIBRARY_PATH)."text.lib.php");
-	$TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
-	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        }
+        if (is_allowed_to_edit() OR in_array(TOOL_QUIZ,$active_modules))
+        {
+        ?>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Exercise&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Exercise')."</a>"; ?></td>
+        </tr>
+
+		<?php
+        }
+
+}
+else
+{
+?>
+
+
+
+		<!--tr>
+          <td width="26%"><b><?php echo get_lang('ExportableCourseResources'); ?></b></td>
+        </tr-->
+<?php if ($multi_level_learnpath === true ) { ?>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=chapter&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Chapter')."</a>"; ?></td>
+        </tr>
+<?php } ?>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Document&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Document')."</a>"; ?></td>
+        </tr>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Exercise&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Exercise')."</a>"; ?></td>
+        </tr>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Link&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Link')."</a>"; ?></td>
+        </tr>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Forum&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Forum')."</a>"; ?></td>
+        </tr>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Agenda&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Agenda')."</a>"; ?></td>
+        </tr>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Ad_Valvas&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('AdValvas')."</a>"; ?></td>
+        </tr>
+        <!--tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Course_description&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('CourseDescription')."</a>"; ?></td>
+        </tr-->
+        <!--tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Introduction_text&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('IntroductionText')."</a>"; ?></td>
+        </tr-->
+		<!--tr>
+          <td>&nbsp;</td>
+        </tr-->
+		<!--tr>
+          <td width="26%"><b><?php echo get_lang('DokeosRelatedCourseMaterial'); ?></b></td>
+        </tr-->
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Dropbox&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Dropbox')."</a>"; ?></td>
+        </tr>
+		<tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Assignment&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Assignments')."</a>"; ?></td>
+        </tr>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Groups&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Groups')."</a>"; ?></td>
+        </tr>
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Users&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Users')."</a>"; ?></td>
+        </tr>
+
+		<?php
+
+}
+?>
+
+
+
+		<!--tr>
+          <td>&nbsp;</td>
+        </tr-->
+        <!--tr>
+          <td><b><?php echo get_lang("ExternalResources"); ?></b></td>
+        </tr-->
+        <tr>
+          <td><?php echo "<a href=\"".api_get_self()."?content=Externallink&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('ExternalLink')."</a>"; ?></td>
+        </tr>
+		<?php
+
+if ($from_learnpath != 'yes')
+{
+	echo "<tr><td>&nbsp;</td></tr>";
+	echo "<tr><td><b>".get_lang('ResourcesAdded')." (";
+	echo count($addedresource);
+	echo ")</b></td></tr>";
+	echo "<tr><td nowrap><a href=\"".api_get_self()."?showresources=true&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('ShowDelete')."</a>";
+	echo "</td></tr>";
+}
+?>
+        <tr>
+          <td>&nbsp;</td>
+        </tr>
+        <!--<tr>
+          <td><b><?php echo get_lang('BackTo'); ?></b></td>
+        </tr>//-->
+        <tr>
+          <td>
+
+		  <?php
+
+if ($from_learnpath != 'yes')
+{
+	echo "<form method=\"post\" action=\"{$_SESSION['origintoolurl']}\" style=\"margin: 0px;\"><input type=\"submit\" value=\"".'  '.get_lang('Ok').'  '."\"></form>";
+}
+else
+{
+	echo "<form method=\"get\" action=\"lp_controller.php\" style=\"margin: 0px;\"><input type=\"hidden\" name=\"lp_id\" value=\"".htmlentities($learnpath_id)."\"><input type=\"hidden\" name=\"action\" value=\"admin_view\"><input type=\"submit\" value=\"".'  '.get_lang('Ok').'  '."\"></form>";
+}
+?>
+
+          </td>
+        </tr>
+        <tr>
+          <td>&nbsp;</td>
+        </tr>
+      </table>
+    </td>
+    <td valign="top">
+      <?php
+
+if ($resource_added)
+{
+	Display :: display_normal_message(get_lang("ResourceAdded"));
+}
+if ($InvalidURL)
+{
+    Display :: display_normal_message(get_lang("GiveURL"));
+}
+
+if ($from_learnpath != 'yes')
+{
+	echo count($addedresource)." ".strtolower(get_lang('ResourcesAdded'))."<br/>";
+}
+//echo "<hr>";
+
+// Agenda items -->
+if ($content == "Agenda")
+{
+	include (api_get_path(LIBRARY_PATH)."text.lib.php");
+	$TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
+	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
 
 	$sql="SELECT agenda.*, toolitemproperties.*
 					FROM ".$TABLEAGENDA." agenda, ".$TABLE_ITEM_PROPERTY." toolitemproperties
-					WHERE `agenda`.`id` = `toolitemproperties`.`ref`
-					AND `toolitemproperties`.`tool`='".TOOL_CALENDAR_EVENT."'
-					AND `toolitemproperties`.`to_group_id`='0'
-					AND `toolitemproperties`.`visibility`='1'";
-
-	$result = Database::query($sql);
-
-	while ($myrow = mysql_fetch_array($result))
-	{
-		echo "<table width=\"100%\"><tr><td bgcolor=\"#E6E6E6\">";
-		echo "<img src='../img/agenda.gif' alt='agenda'>";
-		echo api_ucfirst(format_locale_date($dateFormatLong, strtotime($myrow["start_date"])))."&nbsp;";
-		echo api_ucfirst(strftime($timeNoSecFormat, strtotime($myrow["start_date"])))."<br />";
-		echo "<b>".$myrow["title"]."</b></td></tr><tr><td>";
-		echo $myrow["content"]."<br />";
-		showorhide_addresourcelink($content, $myrow["id"]);
-		echo "</td></tr></table><br />";
-	}
-} // end if ($_GET["resource"]=="Agenda")
-
-/*
------------------------------------------------------------
-	chapter
------------------------------------------------------------
-*/
-if ($content == "chapter")
-{
-	echo '<table><form name="add_chapter" action="'.'" method="POST">'."\n";
-	echo '  <tr><td>'.get_lang('Title').'</td><td><input type="text" name="title" value="'.$title.'"></input></td></tr>'."\n";
-	echo '  <tr><td>'.get_lang('Description').'</td><td><input type="text" name="description" value="'.$description.'"></input></td></tr>'."\n";
-	echo '  <tr><td></td><td><input type="submit" name="add_chapter" value="'.get_lang('AddIt').'"/></td></tr>'."\n";
-	echo '</form></table>'."\n";
-	//echo "<hr>";
-}
-
-/*
------------------------------------------------------------
-	Documents
------------------------------------------------------------
-*/
-// We show the documents in the following cases
-// 1. the link to add documenets in the resource linker was clicked
-// 2. we come to the resource linker for the first time (documents = default). In this case it can only be shown if
-//  			a. one is a teacher (documents can be shown even if the tool is inactive)
-//				b. one is a student AND the documents tool is active. Student cannot add documents if the documents tool is inactive (teacher can do this)
-if ($content == "Document" OR (empty($content) AND (is_allowed_to_edit() OR in_array(TOOL_DOCUMENT,$active_modules))) AND !$_GET['showresources'])
-{
-	// setting variables for file locations
-	$baseServDir = $_configuration['root_sys'];
-	$courseDir = $_course['path']."/document";
-	$baseWorkDir = $baseServDir.$courseDir;
-	// showing the link to move one folder up (when not in the root folder)
-	show_folder_up();
-	// showing the blue bar with the path in it when we are not in the root
-	if (get_levels($folder))
-	{
-		echo "<table width=\"100%\"><tr><td bgcolor=\"#4171B5\">";
-		echo "<img src=\"../img/opendir.gif\" alt='directory'><font color=\"#ffffff\"><b>";
-		echo $folder."</b></font></td></tr></table>";
-	}
-
-	// showing the documents and subfolders of the folder we are in.
-	show_documents($folder);
-	//echo "<hr>";
-}
-
-/*
------------------------------------------------------------
-	Ad Valvas
------------------------------------------------------------
-*/
-if ($content == "Ad_Valvas")
-{
-	include (api_get_path(LIBRARY_PATH)."text.lib.php");
-	$tbl_announcement = Database :: get_course_table(TABLE_ANNOUNCEMENT);
-	$sql = "SELECT * FROM ".$tbl_announcement." a, ".$item_property_table." i  WHERE i.tool = '".TOOL_ANNOUNCEMENT."' AND a.id=i.ref AND i.visibility='1' AND i.to_group_id = 0 AND i.to_user_id IS NULL ORDER BY a.display_order ASC";
-	//error_log($sql,0);
-	$result = Database::query($sql,__FILE__,__LINE__);
-	while ($myrow = mysql_fetch_array($result))
-	{
-		echo "<table width=\"100%\"><tr><td>";
-		echo "<img src='../img/valves.gif' alt='advalvas'>";
-		echo api_ucfirst(format_locale_date($dateFormatLong, strtotime($myrow["end_date"])));
-		echo "</td></tr><tr><td>";
-		echo $myrow["title"]."<br />";
-		showorhide_addresourcelink($content, $myrow["id"]);
-		echo "</td></tr></table>";
-	}
-}
-
-/*
------------------------------------------------------------
-	Forums
------------------------------------------------------------
-*/
-if ($content == "Forum")
-{
-	$TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
-	$TBL_CATAGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
-	$TBL_FORUMTOPICS = Database::get_course_table(TABLE_FORUM_THREAD);
-	$tbl_posts = Database::get_course_table(TABLE_FORUM_POST);
-
-	echo "<table width='100%'>";
-
-	// displaying the categories and the forums
-	if (!$forum and !$thread)
-	{
-		$sql = "SELECT * FROM ".$TBL_FORUMS." forums, ".$TBL_CATAGORIES." categories WHERE forums.forum_category=categories.cat_id ORDER BY forums.forum_category DESC";
-		//error_log($sql,0);
-		$result = Database::query($sql, __FILE__, __LINE__);
-		while ($myrow = mysql_fetch_array($result))
-		{
-			if ($myrow["cat_title"] !== $old_cat_title)
-			{
-				echo "<tr><td bgcolor='#4171B5' colspan='2'><font color='white'><b>".$myrow["cat_title"]."</b></font></td></tr>";
-			}
-			$old_cat_title = $myrow["cat_title"];
-			echo "<tr><td><img src='../img/forum.gif'><a href='".api_get_self()."?content=Forum&category=".$myrow["cat_id"]."&forum=".$myrow["forum_id"]."&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".$myrow["forum_name"]."</td><td>";
-			showorhide_addresourcelink("Forum", $myrow["forum_id"]);
-			echo "</td></tr>";
-		}
-	}
-	//displaying all the threads of one forum
-	if ($forum)
-	{
-		// displaying the category title
-		$sql = "SELECT * FROM ".$TBL_CATAGORIES." WHERE cat_id=$category";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		$myrow = mysql_fetch_array($result);
-		echo "<tr><td bgcolor='#4171B5' colspan='2'><font color='white'><b>".$myrow["cat_title"]."</b></font></td></tr>";
-
-		// displaying the forum title
-		$sql = "SELECT * FROM ".$TBL_FORUMS." forums, ".$TBL_FORUMTOPICS." topics WHERE forums.forum_id=topics.forum_id";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		$myrow = mysql_fetch_array($result);
-		echo "<tr><td bgcolor='#cccccc' colspan='2'><b>".$myrow["forum_name"]."</b></td></tr>";
-
-		if (!$thread)
-		{
-			// displaying all the threads of this forum
-			$sql = "SELECT * FROM ".$TBL_FORUMTOPICS." WHERE forum_id=$forum";
-			$result = Database::query($sql, __FILE__, __LINE__);
-			while ($myrow = mysql_fetch_array($result))
-			{
-				echo "<tr><td><a href='".api_get_self()."?content=Forum&category=$category&forum=1&thread=".$myrow["topic_id"]."&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".$myrow["topic_title"]."</a>  (".$myrow["prenom"]." ".$myrow["nom"].")</td><td>";
-				showorhide_addresourcelink("Thread", $myrow["topic_id"]);
-				echo "</td></tr>";
-			}
-		}
-		else
-		{
-			// displaying all the replies
-			$sql = "SELECT * FROM ".$tbl_posts." post WHERE post.topic_id=$thread ORDER BY post.post_id ASC";
-			$result = Database::query($sql, __FILE__, __LINE__);
-			while ($myrow = mysql_fetch_array($result))
-			{
-				echo "<tr><td><b>".$myrow["post_title"]."</b><br>";
-				echo $myrow["post_text"]."</td>";
-				echo "<td>";
-				showorhide_addresourcelink("Post", $myrow["post_id"]);
-				echo "</td></tr><tr><td colspan='2'><hr noshade></td></tr>";
-			}
-
-		}
-	}
-	echo "</table>";
-}
-
-/*
------------------------------------------------------------
-	Links
------------------------------------------------------------
-*/
-if ($content == "Link")
-{
-	// including the links language file
-	include ("../lang/$language/link.inc.php");
-
-	// including the links functions file
-	include ("../link/linkfunctions.php");
-
-	$tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
-	if (($learnpath_id != '') and ($content == 'Link'))
-	{
-		echo "<form name='learnpath_link'><table>";
-		echo "<tr></td><td align='left'>".get_lang('LinkTarget')." :</td><td align='left'><select name='target' onchange='targetfunc()'><option value='_self' ";
-		if ($target == '_self')
-		{
-			echo "selected";
-		}
-		echo ">".get_lang('SameWindow')."</option><option value='_blank'";
-		if ($target == '_blank')
-		{
-			echo "selected";
-		}
-		echo ">".get_lang('NewWindow')."</option></select></td></tr></table></form>";
-	}
-
-	// showing the links that are in the root (having no category)
-	$sql = "SELECT * FROM ".$link_table.", ".$item_property_table." WHERE (category_id=0 or category_id IS NULL) AND tool = '".TOOL_LINK."' AND id=ref AND visibility='1'";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	if (mysql_num_rows($result) > 0)
-	{
-		echo "<table width=\"100%\"><tr><td bgcolor=\"#E6E6E6\"><i>".get_lang('NoCategory')."</i></td></tr></table>";
-		while ($myrow = mysql_fetch_array($result))
-		{
-			echo "<img src='../img/links.gif'>".$myrow["title"];
-			echo "<br>";
-			showorhide_addresourcelink($content, $myrow["id"]);
-			echo "<br><br>";
-		}
-	}
-
-	// showing the categories and the links in it.
-	$sqlcategories = "SELECT * FROM ".$tbl_categories." ORDER by display_order DESC";
-	$resultcategories = Database::query($sqlcategories) or die;
-	while ($myrow = @ mysql_fetch_array($resultcategories))
-	{
-		$sql_links = "SELECT * FROM ".$link_table.", ".$item_property_table." WHERE category_id='".$myrow["id"]."' AND tool = '".TOOL_LINK."' AND id=ref AND visibility='1' ORDER BY display_order DESC";
-		echo "<table width=\"100%\"><tr><td bgcolor=\"#E6E6E6\"><i>".$myrow["category_title"]."</i></td></tr></table>";
-		$result_links = Database::query($sql_links, __FILE__, __LINE__);
-		while ($myrow = mysql_fetch_array($result_links))
-		{
-			echo "<img src='../img/links.gif' />".$myrow["title"];
-			echo "<br>";
-			showorhide_addresourcelink($content, $myrow["id"]);
-			echo "<br><br>";
-		}
-	}
-}
-
-/*
------------------------------------------------------------
-	Exercise
------------------------------------------------------------
-*/
-if (($content == "Exercise") or ($content == "HotPotatoes"))
-{
-	$TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
-	$result = Database::query("SELECT * FROM ".$TBL_EXERCICES." WHERE active='1' ORDER BY id ASC");
-	while ($myrow = mysql_fetch_array($result))
-	{
-		echo "<img src='../img/quiz.gif'>".$myrow["title"]."<br>";
-		showorhide_addresourcelink($content, $myrow["id"]);
-		echo "<br><br>";
-	}
-
-	if ($from_learnpath == 'yes')
-	{
-		$uploadPath = "/HotPotatoes_files";
-		$TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
-		$documentPath = api_get_path('SYS_COURSE_PATH').$_course['path'].'/document';
-		$sql = "SELECT * FROM ".$TBL_DOCUMENT." WHERE (path LIKE '%htm%' OR path LIKE '%html%') AND path LIKE '".$uploadPath."/%/%' ORDER BY `id` ASC";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		while ($myrow = mysql_fetch_array($result))
-		{
-			$path = $myrow["path"];
-			echo "<img src='../img/jqz.jpg'>".GetQuizName($path, $documentPath)."<br>";
-			showorhide_addresourcelink("HotPotatoes", $myrow["id"]);
-			echo "<br><br>";
-
-		}
-	}
-}
-
-/*
------------------------------------------------------------
-	External Links
------------------------------------------------------------
-*/
-if ($content == "Externallink")
-{
-?>
-  <form name="form1" method="post" action="">
-  <table width="80%" border="0" cellspacing="0" cellpadding="0">
-    <tr>
-      <td align="right"><?php echo get_lang('ExternalLink'); ?> : &nbsp;</td>
-      <td align="left"><input name="external_link" type="text" id="external_link" value="http://"></td>
-	  <?php
-
-	if ($learnpath_id != '')
-	{
-		echo "</tr><tr><td align='right'>".get_lang('LinkTarget')." :</td><td align='left'><select name='target'><option value='_self'>".get_lang('SameWindow')."</option><option value='_blank'>".get_lang('NewWindow')."</option></select></td>";
-	}
-?>
-	</tr>
-    <tr>
-      <td><?php if ($is_allowedToEdit) {echo get_lang('AddToLinks');} ?></td>
-      <td>
-  	  <?php if ($is_allowedToEdit){?>
-	  <select name="add_2_links" id="add_2_links">
-      <option value="niet toevoegen" selected="selected">-<?php echo get_lang('DontAdd'); ?>-</option>
-	  <option value="0"><?php echo get_lang('MainCategory'); ?></option>
-		<?php
-
-	$tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
-	$sql = "SELECT * FROM `$tbl_categories` ORDER BY display_order ASC";
-	echo $sql;
-	$result = Database::query($sql, __FILE__, __LINE__);
-	while ($row = mysql_fetch_array($result))
-	{
-		echo "<option value='".$row["id"]."'>".$row["category_title"]."</option>";
-	}
-?>
-
-      </select><?php } ?></td>
-    </tr>
-    <tr>
-      <td>&nbsp;</td>
-      <td><input name="external_link_submit" type="submit" id="external_link_submit" value="<?php echo get_lang('AddIt'); ?>"></td>
-    </tr>
-    <tr>
-      <td>&nbsp;</td>
-      <td>&nbsp;</td>
-    </tr>
-    <tr>
-      <td colspan="2">&nbsp;</td>
-    </tr>
-  </table>
-</form>
-	<?php
-
-}
-
-/*
------------------------------------------------------------
-	Assignments
------------------------------------------------------------
-*/
-if ($content == "Assignment")
-{
-	echo "<a href=".api_get_self()."?content=Ass&add=Ass&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no>".get_lang('AddAssignmentPage')."</a>";
-}
-
-/*
------------------------------------------------------------
-	Dropbox
------------------------------------------------------------
-*/
-if ($content == "Dropbox")
-{
-	echo "<a href='".api_get_self()."?content=Drop&add=Drop&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('DropboxAdd')."</a>";
-}
-
-/*
------------------------------------------------------------
-	Introduction text
------------------------------------------------------------
-*/
-if ($content == "Introduction_text")
-{
-	echo "<a href='".api_get_self()."?content=Intro&add=Intro&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('IntroductionTextAdd')."</a>";
-}
-
-/*
------------------------------------------------------------
-	Course description
------------------------------------------------------------
-*/
-if ($content == "Course_description")
-{
-	echo "<a href='".api_get_self()."?content=Course_desc&add=Course_desc&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('CourseDescriptionAdd')."</a>";
-}
-
-/*
------------------------------------------------------------
-	Groups
------------------------------------------------------------
-*/
-if ($content == "Groups")
-{
-	echo "<a href='".api_get_self()."?content=Group&add=Group&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('GroupsAdd')."</a>";
-}
-
-/*
------------------------------------------------------------
-	Users
------------------------------------------------------------
-*/
-if ($content == "Users")
-{
-	echo "<a href='".api_get_self()."?content=User&add=User&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('UsersAdd')."</a>";
-}
-
-if ($showresources)
-{
-	//echo "<h4>".get_lang('ResourceAdded')."</h4>";
-	display_resources(1);
-}
-
-echo "</td></tr></table>";
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-
-Display :: display_footer();
-?>
-
+					WHERE `agenda`.`id` = `toolitemproperties`.`ref`
+					AND `toolitemproperties`.`tool`='".TOOL_CALENDAR_EVENT."'
+					AND `toolitemproperties`.`to_group_id`='0'
+					AND `toolitemproperties`.`visibility`='1'";
+
+	$result = Database::query($sql);
+
+	while ($myrow = mysql_fetch_array($result))
+	{
+		echo "<table width=\"100%\"><tr><td bgcolor=\"#E6E6E6\">";
+		echo "<img src='../img/agenda.gif' alt='agenda'>";
+		echo api_ucfirst(format_locale_date($dateFormatLong, strtotime($myrow["start_date"])))."&nbsp;";
+		echo api_ucfirst(strftime($timeNoSecFormat, strtotime($myrow["start_date"])))."<br />";
+		echo "<b>".$myrow["title"]."</b></td></tr><tr><td>";
+		echo $myrow["content"]."<br />";
+		showorhide_addresourcelink($content, $myrow["id"]);
+		echo "</td></tr></table><br />";
+	}
+} // end if ($_GET["resource"]=="Agenda")
+
+/*
+-----------------------------------------------------------
+	chapter
+-----------------------------------------------------------
+*/
+if ($content == "chapter")
+{
+	echo '<table><form name="add_chapter" action="'.'" method="POST">'."\n";
+	echo '  <tr><td>'.get_lang('Title').'</td><td><input type="text" name="title" value="'.$title.'"></input></td></tr>'."\n";
+	echo '  <tr><td>'.get_lang('Description').'</td><td><input type="text" name="description" value="'.$description.'"></input></td></tr>'."\n";
+	echo '  <tr><td></td><td><input type="submit" name="add_chapter" value="'.get_lang('AddIt').'"/></td></tr>'."\n";
+	echo '</form></table>'."\n";
+	//echo "<hr>";
+}
+
+/*
+-----------------------------------------------------------
+	Documents
+-----------------------------------------------------------
+*/
+// We show the documents in the following cases
+// 1. the link to add documenets in the resource linker was clicked
+// 2. we come to the resource linker for the first time (documents = default). In this case it can only be shown if
+//  			a. one is a teacher (documents can be shown even if the tool is inactive)
+//				b. one is a student AND the documents tool is active. Student cannot add documents if the documents tool is inactive (teacher can do this)
+if ($content == "Document" OR (empty($content) AND (is_allowed_to_edit() OR in_array(TOOL_DOCUMENT,$active_modules))) AND !$_GET['showresources'])
+{
+	// setting variables for file locations
+	$baseServDir = $_configuration['root_sys'];
+	$courseDir = $_course['path']."/document";
+	$baseWorkDir = $baseServDir.$courseDir;
+	// showing the link to move one folder up (when not in the root folder)
+	show_folder_up();
+	// showing the blue bar with the path in it when we are not in the root
+	if (get_levels($folder))
+	{
+		echo "<table width=\"100%\"><tr><td bgcolor=\"#4171B5\">";
+		echo "<img src=\"../img/opendir.gif\" alt='directory'><font color=\"#ffffff\"><b>";
+		echo $folder."</b></font></td></tr></table>";
+	}
+
+	// showing the documents and subfolders of the folder we are in.
+	show_documents($folder);
+	//echo "<hr>";
+}
+
+/*
+-----------------------------------------------------------
+	Ad Valvas
+-----------------------------------------------------------
+*/
+if ($content == "Ad_Valvas")
+{
+	include (api_get_path(LIBRARY_PATH)."text.lib.php");
+	$tbl_announcement = Database :: get_course_table(TABLE_ANNOUNCEMENT);
+	$sql = "SELECT * FROM ".$tbl_announcement." a, ".$item_property_table." i  WHERE i.tool = '".TOOL_ANNOUNCEMENT."' AND a.id=i.ref AND i.visibility='1' AND i.to_group_id = 0 AND i.to_user_id IS NULL ORDER BY a.display_order ASC";
+	//error_log($sql,0);
+	$result = Database::query($sql,__FILE__,__LINE__);
+	while ($myrow = mysql_fetch_array($result))
+	{
+		echo "<table width=\"100%\"><tr><td>";
+		echo "<img src='../img/valves.gif' alt='advalvas'>";
+		echo api_ucfirst(format_locale_date($dateFormatLong, strtotime($myrow["end_date"])));
+		echo "</td></tr><tr><td>";
+		echo $myrow["title"]."<br />";
+		showorhide_addresourcelink($content, $myrow["id"]);
+		echo "</td></tr></table>";
+	}
+}
+
+/*
+-----------------------------------------------------------
+	Forums
+-----------------------------------------------------------
+*/
+if ($content == "Forum")
+{
+	$TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
+	$TBL_CATAGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
+	$TBL_FORUMTOPICS = Database::get_course_table(TABLE_FORUM_THREAD);
+	$tbl_posts = Database::get_course_table(TABLE_FORUM_POST);
+
+	echo "<table width='100%'>";
+
+	// displaying the categories and the forums
+	if (!$forum and !$thread)
+	{
+		$sql = "SELECT * FROM ".$TBL_FORUMS." forums, ".$TBL_CATAGORIES." categories WHERE forums.forum_category=categories.cat_id ORDER BY forums.forum_category DESC";
+		//error_log($sql,0);
+		$result = Database::query($sql, __FILE__, __LINE__);
+		while ($myrow = mysql_fetch_array($result))
+		{
+			if ($myrow["cat_title"] !== $old_cat_title)
+			{
+				echo "<tr><td bgcolor='#4171B5' colspan='2'><font color='white'><b>".$myrow["cat_title"]."</b></font></td></tr>";
+			}
+			$old_cat_title = $myrow["cat_title"];
+			echo "<tr><td><img src='../img/forum.gif'><a href='".api_get_self()."?content=Forum&category=".$myrow["cat_id"]."&forum=".$myrow["forum_id"]."&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".$myrow["forum_name"]."</td><td>";
+			showorhide_addresourcelink("Forum", $myrow["forum_id"]);
+			echo "</td></tr>";
+		}
+	}
+	//displaying all the threads of one forum
+	if ($forum)
+	{
+		// displaying the category title
+		$sql = "SELECT * FROM ".$TBL_CATAGORIES." WHERE cat_id=$category";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		$myrow = mysql_fetch_array($result);
+		echo "<tr><td bgcolor='#4171B5' colspan='2'><font color='white'><b>".$myrow["cat_title"]."</b></font></td></tr>";
+
+		// displaying the forum title
+		$sql = "SELECT * FROM ".$TBL_FORUMS." forums, ".$TBL_FORUMTOPICS." topics WHERE forums.forum_id=topics.forum_id";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		$myrow = mysql_fetch_array($result);
+		echo "<tr><td bgcolor='#cccccc' colspan='2'><b>".$myrow["forum_name"]."</b></td></tr>";
+
+		if (!$thread)
+		{
+			// displaying all the threads of this forum
+			$sql = "SELECT * FROM ".$TBL_FORUMTOPICS." WHERE forum_id=$forum";
+			$result = Database::query($sql, __FILE__, __LINE__);
+			while ($myrow = mysql_fetch_array($result))
+			{
+				echo "<tr><td><a href='".api_get_self()."?content=Forum&category=$category&forum=1&thread=".$myrow["topic_id"]."&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".$myrow["topic_title"]."</a>  (".$myrow["prenom"]." ".$myrow["nom"].")</td><td>";
+				showorhide_addresourcelink("Thread", $myrow["topic_id"]);
+				echo "</td></tr>";
+			}
+		}
+		else
+		{
+			// displaying all the replies
+			$sql = "SELECT * FROM ".$tbl_posts." post WHERE post.topic_id=$thread ORDER BY post.post_id ASC";
+			$result = Database::query($sql, __FILE__, __LINE__);
+			while ($myrow = mysql_fetch_array($result))
+			{
+				echo "<tr><td><b>".$myrow["post_title"]."</b><br>";
+				echo $myrow["post_text"]."</td>";
+				echo "<td>";
+				showorhide_addresourcelink("Post", $myrow["post_id"]);
+				echo "</td></tr><tr><td colspan='2'><hr noshade></td></tr>";
+			}
+
+		}
+	}
+	echo "</table>";
+}
+
+/*
+-----------------------------------------------------------
+	Links
+-----------------------------------------------------------
+*/
+if ($content == "Link")
+{
+	// including the links language file
+	include ("../lang/$language/link.inc.php");
+
+	// including the links functions file
+	include ("../link/linkfunctions.php");
+
+	$tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
+	if (($learnpath_id != '') and ($content == 'Link'))
+	{
+		echo "<form name='learnpath_link'><table>";
+		echo "<tr></td><td align='left'>".get_lang('LinkTarget')." :</td><td align='left'><select name='target' onchange='targetfunc()'><option value='_self' ";
+		if ($target == '_self')
+		{
+			echo "selected";
+		}
+		echo ">".get_lang('SameWindow')."</option><option value='_blank'";
+		if ($target == '_blank')
+		{
+			echo "selected";
+		}
+		echo ">".get_lang('NewWindow')."</option></select></td></tr></table></form>";
+	}
+
+	// showing the links that are in the root (having no category)
+	$sql = "SELECT * FROM ".$link_table.", ".$item_property_table." WHERE (category_id=0 or category_id IS NULL) AND tool = '".TOOL_LINK."' AND id=ref AND visibility='1'";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	if (mysql_num_rows($result) > 0)
+	{
+		echo "<table width=\"100%\"><tr><td bgcolor=\"#E6E6E6\"><i>".get_lang('NoCategory')."</i></td></tr></table>";
+		while ($myrow = mysql_fetch_array($result))
+		{
+			echo "<img src='../img/links.gif'>".$myrow["title"];
+			echo "<br>";
+			showorhide_addresourcelink($content, $myrow["id"]);
+			echo "<br><br>";
+		}
+	}
+
+	// showing the categories and the links in it.
+	$sqlcategories = "SELECT * FROM ".$tbl_categories." ORDER by display_order DESC";
+	$resultcategories = Database::query($sqlcategories) or die;
+	while ($myrow = @ mysql_fetch_array($resultcategories))
+	{
+		$sql_links = "SELECT * FROM ".$link_table.", ".$item_property_table." WHERE category_id='".$myrow["id"]."' AND tool = '".TOOL_LINK."' AND id=ref AND visibility='1' ORDER BY display_order DESC";
+		echo "<table width=\"100%\"><tr><td bgcolor=\"#E6E6E6\"><i>".$myrow["category_title"]."</i></td></tr></table>";
+		$result_links = Database::query($sql_links, __FILE__, __LINE__);
+		while ($myrow = mysql_fetch_array($result_links))
+		{
+			echo "<img src='../img/links.gif' />".$myrow["title"];
+			echo "<br>";
+			showorhide_addresourcelink($content, $myrow["id"]);
+			echo "<br><br>";
+		}
+	}
+}
+
+/*
+-----------------------------------------------------------
+	Exercise
+-----------------------------------------------------------
+*/
+if (($content == "Exercise") or ($content == "HotPotatoes"))
+{
+	$TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
+	$result = Database::query("SELECT * FROM ".$TBL_EXERCICES." WHERE active='1' ORDER BY id ASC");
+	while ($myrow = mysql_fetch_array($result))
+	{
+		echo "<img src='../img/quiz.gif'>".$myrow["title"]."<br>";
+		showorhide_addresourcelink($content, $myrow["id"]);
+		echo "<br><br>";
+	}
+
+	if ($from_learnpath == 'yes')
+	{
+		$uploadPath = "/HotPotatoes_files";
+		$TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
+		$documentPath = api_get_path('SYS_COURSE_PATH').$_course['path'].'/document';
+		$sql = "SELECT * FROM ".$TBL_DOCUMENT." WHERE (path LIKE '%htm%' OR path LIKE '%html%') AND path LIKE '".$uploadPath."/%/%' ORDER BY `id` ASC";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		while ($myrow = mysql_fetch_array($result))
+		{
+			$path = $myrow["path"];
+			echo "<img src='../img/jqz.jpg'>".GetQuizName($path, $documentPath)."<br>";
+			showorhide_addresourcelink("HotPotatoes", $myrow["id"]);
+			echo "<br><br>";
+
+		}
+	}
+}
+
+/*
+-----------------------------------------------------------
+	External Links
+-----------------------------------------------------------
+*/
+if ($content == "Externallink")
+{
+?>
+  <form name="form1" method="post" action="">
+  <table width="80%" border="0" cellspacing="0" cellpadding="0">
+    <tr>
+      <td align="right"><?php echo get_lang('ExternalLink'); ?> : &nbsp;</td>
+      <td align="left"><input name="external_link" type="text" id="external_link" value="http://"></td>
+	  <?php
+
+	if ($learnpath_id != '')
+	{
+		echo "</tr><tr><td align='right'>".get_lang('LinkTarget')." :</td><td align='left'><select name='target'><option value='_self'>".get_lang('SameWindow')."</option><option value='_blank'>".get_lang('NewWindow')."</option></select></td>";
+	}
+?>
+	</tr>
+    <tr>
+      <td><?php if ($is_allowedToEdit) {echo get_lang('AddToLinks');} ?></td>
+      <td>
+  	  <?php if ($is_allowedToEdit){?>
+	  <select name="add_2_links" id="add_2_links">
+      <option value="niet toevoegen" selected="selected">-<?php echo get_lang('DontAdd'); ?>-</option>
+	  <option value="0"><?php echo get_lang('MainCategory'); ?></option>
+		<?php
+
+	$tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
+	$sql = "SELECT * FROM `$tbl_categories` ORDER BY display_order ASC";
+	echo $sql;
+	$result = Database::query($sql, __FILE__, __LINE__);
+	while ($row = mysql_fetch_array($result))
+	{
+		echo "<option value='".$row["id"]."'>".$row["category_title"]."</option>";
+	}
+?>
+
+      </select><?php } ?></td>
+    </tr>
+    <tr>
+      <td>&nbsp;</td>
+      <td><input name="external_link_submit" type="submit" id="external_link_submit" value="<?php echo get_lang('AddIt'); ?>"></td>
+    </tr>
+    <tr>
+      <td>&nbsp;</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td colspan="2">&nbsp;</td>
+    </tr>
+  </table>
+</form>
+	<?php
+
+}
+
+/*
+-----------------------------------------------------------
+	Assignments
+-----------------------------------------------------------
+*/
+if ($content == "Assignment")
+{
+	echo "<a href=".api_get_self()."?content=Ass&add=Ass&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no>".get_lang('AddAssignmentPage')."</a>";
+}
+
+/*
+-----------------------------------------------------------
+	Dropbox
+-----------------------------------------------------------
+*/
+if ($content == "Dropbox")
+{
+	echo "<a href='".api_get_self()."?content=Drop&add=Drop&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('DropboxAdd')."</a>";
+}
+
+/*
+-----------------------------------------------------------
+	Introduction text
+-----------------------------------------------------------
+*/
+if ($content == "Introduction_text")
+{
+	echo "<a href='".api_get_self()."?content=Intro&add=Intro&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('IntroductionTextAdd')."</a>";
+}
+
+/*
+-----------------------------------------------------------
+	Course description
+-----------------------------------------------------------
+*/
+if ($content == "Course_description")
+{
+	echo "<a href='".api_get_self()."?content=Course_desc&add=Course_desc&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('CourseDescriptionAdd')."</a>";
+}
+
+/*
+-----------------------------------------------------------
+	Groups
+-----------------------------------------------------------
+*/
+if ($content == "Groups")
+{
+	echo "<a href='".api_get_self()."?content=Group&add=Group&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('GroupsAdd')."</a>";
+}
+
+/*
+-----------------------------------------------------------
+	Users
+-----------------------------------------------------------
+*/
+if ($content == "Users")
+{
+	echo "<a href='".api_get_self()."?content=User&add=User&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('UsersAdd')."</a>";
+}
+
+if ($showresources)
+{
+	//echo "<h4>".get_lang('ResourceAdded')."</h4>";
+	display_resources(1);
+}
+
+echo "</td></tr></table>";
+
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+
+Display :: display_footer();
+?>
+

+ 977 - 977
main/newscorm/scorm.class.php

@@ -1,1028 +1,1028 @@
-<?php
-/**
- * Defines the scorm class, which is meant to contain the scorm items (nuclear elements)
- * @package dokeos.learnpath.scorm
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Defines the "scorm" child of class "learnpath"
- * @package dokeos.learnpath
- */
-require_once('scormItem.class.php');
-require_once('scormMetadata.class.php');
-require_once('scormOrganization.class.php');
-require_once('scormResource.class.php');
-class scorm extends learnpath {
-	var $manifest = array();
-	var $resources = array();
-	var $resources_att = array();
-	var $organizations = array();
-	var $organizations_att = array();
-	var $metadata = array();
-	var $idrefs = array(); //will hold the references to resources for each item ID found
-	var $refurls = array(); //for each resource found, stores the file url/uri
-	var $subdir = ''; //path between the scorm/ directory and the imsmanifest.xml e.g. maritime_nav/maritime_nav. This is the path that will be used in the lp_path when importing a package
+<?php
+/**
+ * Defines the scorm class, which is meant to contain the scorm items (nuclear elements)
+ * @package dokeos.learnpath.scorm
+ * @author	Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Defines the "scorm" child of class "learnpath"
+ * @package dokeos.learnpath
+ */
+require_once('scormItem.class.php');
+require_once('scormMetadata.class.php');
+require_once('scormOrganization.class.php');
+require_once('scormResource.class.php');
+class scorm extends learnpath {
+	var $manifest = array();
+	var $resources = array();
+	var $resources_att = array();
+	var $organizations = array();
+	var $organizations_att = array();
+	var $metadata = array();
+	var $idrefs = array(); //will hold the references to resources for each item ID found
+	var $refurls = array(); //for each resource found, stores the file url/uri
+	var $subdir = ''; //path between the scorm/ directory and the imsmanifest.xml e.g. maritime_nav/maritime_nav. This is the path that will be used in the lp_path when importing a package
 	var $items = array();
-	var $zipname = ''; //keeps the zipfile safe for the object's life so that we can use it if no title avail
-	var $lastzipnameindex = 0; //keeps an index of the number of uses of the zipname so far
-	var $manifest_encoding = 'UTF-8';
-	var $debug = 0;
-	/**
-	 * Class constructor. Based on the parent constructor.
-	 * @param	string	Course code
-	 * @param	integer	Learnpath ID in DB
-	 * @param	integer	User ID
-	 */
-    function scorm($course_code=null,$resource_id=null,$user_id=null) {
-    	if($this->debug>0){error_log('New LP - scorm::scorm('.$course_code.','.$resource_id.','.$user_id.') - In scorm constructor',0);}
-    	if(!empty($course_code) and !empty($resource_id) and !empty($user_id))
-    	{
-    		parent::learnpath($course_code, $resource_id, $user_id);
-    	}else{
-    		//do nothing but still build the scorm object
-    	}
-    }
-    /**
-     * Opens a resource
-     * @param	integer	Database ID of the resource
-     */
-    function open($id)
-    {
-    	if($this->debug>0){error_log('New LP - scorm::open() - In scorm::open method',0);}
-    	// redefine parent method
-    }
-    /**
-     * Possible SCO status: see CAM doc 2.3.2.5.1: passed, completed, browsed, failed, not attempted, incomplete
-     */
-    /**
-     * Prerequisites: see CAM doc 2.3.2.5.1 for pseudo-code
-     */
-    /**
-     * Parses an imsmanifest.xml file and puts everything into the $manifest array
-     * @param	string	Path to the imsmanifest.xml file on the system. If not defined, uses the base path of the course's scorm dir
+	var $zipname = ''; //keeps the zipfile safe for the object's life so that we can use it if no title avail
+	var $lastzipnameindex = 0; //keeps an index of the number of uses of the zipname so far
+	var $manifest_encoding = 'UTF-8';
+	var $debug = 0;
+	/**
+	 * Class constructor. Based on the parent constructor.
+	 * @param	string	Course code
+	 * @param	integer	Learnpath ID in DB
+	 * @param	integer	User ID
+	 */
+    function scorm($course_code=null,$resource_id=null,$user_id=null) {
+    	if($this->debug>0){error_log('New LP - scorm::scorm('.$course_code.','.$resource_id.','.$user_id.') - In scorm constructor',0);}
+    	if(!empty($course_code) and !empty($resource_id) and !empty($user_id))
+    	{
+    		parent::learnpath($course_code, $resource_id, $user_id);
+    	}else{
+    		//do nothing but still build the scorm object
+    	}
+    }
+    /**
+     * Opens a resource
+     * @param	integer	Database ID of the resource
+     */
+    function open($id)
+    {
+    	if($this->debug>0){error_log('New LP - scorm::open() - In scorm::open method',0);}
+    	// redefine parent method
+    }
+    /**
+     * Possible SCO status: see CAM doc 2.3.2.5.1: passed, completed, browsed, failed, not attempted, incomplete
+     */
+    /**
+     * Prerequisites: see CAM doc 2.3.2.5.1 for pseudo-code
+     */
+    /**
+     * Parses an imsmanifest.xml file and puts everything into the $manifest array
+     * @param	string	Path to the imsmanifest.xml file on the system. If not defined, uses the base path of the course's scorm dir
 	 * @return	array	Structured array representing the imsmanifest's contents
-     */
-     function parse_manifest($file='')
-     {
-    	if($this->debug>0){error_log('In scorm::parse_manifest('.$file.')',0);}
-		if(empty($file)){
-     		//get the path of the imsmanifest file
-     	}
-     	if(is_file($file) and is_readable($file))
-     	{
-			$v = substr(phpversion(),0,1);
-			if($v == 4){
-		    	if($this->debug>0){error_log('In scorm::parse_manifest() - Parsing using PHP4 method',0);}
-	     		$var = file_get_contents($file);
-	     		//quick ugly hack to remove xml:id attributes from the file (break the system if xslt not installed)
-	     		$var = preg_replace('/xml:id=["\']id_\d{1,4}["\']/i','',$var);
-	     		$doc = xmldoc($var);
-	     		//error_reporting(E_ALL);
-	     		//$doc = xmldocfile($file);
-	     		if(!empty($doc->encoding)){
-	     			$this->manifest_encoding = strtoupper($doc->encoding);
-	     		}
-	     		if($this->debug>1){error_log('New LP - Called xmldoc() (encoding:'.strtoupper($doc->encoding).' - saved: '.$this->manifest_encoding.')',0);}
-	     		if(!$doc)
-	     		{
-		     		if($this->debug>1){error_log('New LP - File '.$file.' is not an XML file',0);}
-		     		//$this->set_error_msg("File $file is not an XML file");
-	     			return null;
-	     		}else{
-	     			if($this->debug>1){error_log('New LP - File '.$file.' is XML',0);}
-	     			$root = $doc->root();
-	     			$attributes = $root->attributes();
-	     			for($a=0; $a<sizeof($attributes);$a++)
-	     			{//<manifest> element attributes
-	     				if($attributes[$a]->type == XML_ATTRIBUTE_NODE){
-							$this->manifest[$attributes[$a]->name] = $attributes[$a]->value;
-	     				}
-	     			}
-	     			$this->manifest['name'] = $root->name;
-	     			$children = $root->children();
-	     			for($b=0; $b<sizeof($children);$b++)
-	     			{
-	     				//<manifest> element children (can be <metadata>, <organizations> or <resources> )
-	     				if($children[$b]->type == XML_ELEMENT_NODE){
-		     				switch($children[$b]->tagname){
-		     					case 'metadata':
-		     						//parse items from inside the <metadata> element
-		     						$this->metadata = new scormMetadata('manifest',$children[$b]);
-		     						break;
-		     					case 'organizations':
-		     						//contains the course structure - this element appears 1 and only 1 time in a package imsmanifest. It contains at least one 'organization' sub-element
-		     						$orgs_attribs = $children[$b]->attributes();
-		     						for($c=0; $c<sizeof($orgs_attribs);$c++)
-		     						{//attributes of the <organizations> element
-	     								if($orgs_attribs[$c]->type == XML_ATTRIBUTE_NODE){
-			     							$this->manifest['organizations'][$orgs_attribs[$c]->name] = $orgs_attribs[$c]->value;
-	     								}
-		     						}
-		     						$orgs_nodes = $children[$b]->children();
-		     						$i = 0;
-		     						$found_an_org = false;
-		     						foreach($orgs_nodes as $c => $dummy)
-		     						{
-		     							//<organization> elements - can contain <item>, <metadata> and <title>
-		     							//Here we are at the 'organization' level. There might be several organization tags but
-		     							//there is generally only one.
-		     							//There are generally three children nodes we are looking for inside and organization:
-		     							//-title
-		     							//-item (may contain other item tags or may appear several times inside organization)
-		     							//-metadata (relative to the organization)
-		     							$found_an_org = false;
-	     								$orgnode =& $orgs_nodes[$c];
-	     								switch($orgnode->type){
-		     								case XML_TEXT_NODE:
-		     									//ignore here
-		     									break;
-		     								case XML_ATTRIBUTE_NODE:
-		     									//just in case ther would be interesting attributes inside the organization tag. There shouldn't
-		     									//as this is a node-level, not a data level
-		     									//$manifest['organizations'][$i][$orgnode->name] = $orgnode->value;
-		     									//$found_an_org = true;
-		     									break;
-		     								case XML_ELEMENT_NODE:
-		     									//<item>,<metadata> or <title> (or attributes)
-			     								$organizations_attributes = $orgnode->attributes();
-			     								foreach($organizations_attributes as $d1 => $dummy)
-			     								{
-													//$manifest['organizations'][$i]['attributes'][$organizations_attributes[$d1]->name] = $organizations_attributes[$d1]->value;
-			     									//$found_an_org = true;
-			     									$this->organizations_att[$organizations_attributes[$d1]->name] = $organizations_attributes[$d1]->value;
-			     								}
-		     									$oOrganization = new scormOrganization('manifest',$orgnode,$this->manifest_encoding);
-		     									if($oOrganization->identifier != ''){
-		     										$name = $oOrganization->get_name();
-		     										if(empty($name)){
-		     											//if the org title is empty, use zip file name
-		     											$myname = $this->zipname;
-		     											if($this->lastzipnameindex != 0){
-		     												$myname = $myname + $this->lastzipnameindex;
-		     												$this->lastzipnameindex++;
-		     											}
-		     											$oOrganization->set_name($this->zipname);
-		     										}
-		     										$this->organizations[$oOrganization->identifier] = $oOrganization;
-		     									}
-		     									break;
-		     							}
-		     						}
-		     						break;
-		     					case 'resources':
-		     						$resources_attribs = $children[$b]->attributes();
-		     						for($c=0; $c<sizeof($resources_attribs);$c++)
-		     						{
-	     								if($resources_attribs[$c]->type == XML_ATTRIBUTE_NODE){
-			     							$this->manifest['resources'][$resources_attribs[$c]->name] = $resources_attribs[$c]->value;
-	     								}
-		     						}
-		     						$resources_nodes = $children[$b]->children();
-		     						$i = 0;
-		     						foreach($resources_nodes as $c => $dummy)
-		     						{
-			     						/*
-			     						$my_res = scorm::parse_items($resources_nodes[$c]);
-			     						scorm::parse_items_get_refurls($resources_nodes[$c],$refurls);
-			     						if(count($my_res)>0)
-			     						{
-			     							$manifest['resources'][$i] = $my_res;
-			     						}
-			     						*/
-		     							$oResource = new scormResource('manifest',$resources_nodes[$c]);
-			     						if($oResource->identifier != ''){
-											$this->resources[$oResource->identifier] = $oResource;
-			     							$i++;
-			     						}
-		     						}
-		     						//contains links to physical resources
-		     						break;
-		     					case 'manifest':
-		     						//only for sub-manifests
-		     						break;
-		     				}
-	     				}
-	     			}
-	     		}
-		     	unset($doc);
-	     	}elseif($v==5){
-		    	if($this->debug>0){error_log('In scorm::parse_manifest() - Parsing using PHP5 method',0);}
-	     		$doc = new DOMDocument();
-	     		$res = $doc->load($file);
-	     		if($res===false){
-	     			if($this->debug>0){error_log('New LP - In scorm::parse_manifest() - Exception thrown when loading '.$file.' in DOMDocument',0);}
-	     			//throw exception?
+     */
+     function parse_manifest($file='')
+     {
+    	if($this->debug>0){error_log('In scorm::parse_manifest('.$file.')',0);}
+		if(empty($file)){
+     		//get the path of the imsmanifest file
+     	}
+     	if(is_file($file) and is_readable($file))
+     	{
+			$v = substr(phpversion(),0,1);
+			if($v == 4){
+		    	if($this->debug>0){error_log('In scorm::parse_manifest() - Parsing using PHP4 method',0);}
+	     		$var = file_get_contents($file);
+	     		//quick ugly hack to remove xml:id attributes from the file (break the system if xslt not installed)
+	     		$var = preg_replace('/xml:id=["\']id_\d{1,4}["\']/i','',$var);
+	     		$doc = xmldoc($var);
+	     		//error_reporting(E_ALL);
+	     		//$doc = xmldocfile($file);
+	     		if(!empty($doc->encoding)){
+	     			$this->manifest_encoding = strtoupper($doc->encoding);
+	     		}
+	     		if($this->debug>1){error_log('New LP - Called xmldoc() (encoding:'.strtoupper($doc->encoding).' - saved: '.$this->manifest_encoding.')',0);}
+	     		if(!$doc)
+	     		{
+		     		if($this->debug>1){error_log('New LP - File '.$file.' is not an XML file',0);}
+		     		//$this->set_error_msg("File $file is not an XML file");
 	     			return null;
-	     		}
-
-	     		if(!empty($doc->xmlEncoding)){
-	     			$this->manifest_encoding = strtoupper($doc->xmlEncoding);
-	     		}
-	     		if($this->debug>1){error_log('New LP - Called  (encoding:'.$doc->xmlEncoding.' - saved: '.$this->manifest_encoding.')',0);}
+	     		}else{
+	     			if($this->debug>1){error_log('New LP - File '.$file.' is XML',0);}
+	     			$root = $doc->root();
+	     			$attributes = $root->attributes();
+	     			for($a=0; $a<sizeof($attributes);$a++)
+	     			{//<manifest> element attributes
+	     				if($attributes[$a]->type == XML_ATTRIBUTE_NODE){
+							$this->manifest[$attributes[$a]->name] = $attributes[$a]->value;
+	     				}
+	     			}
+	     			$this->manifest['name'] = $root->name;
+	     			$children = $root->children();
+	     			for($b=0; $b<sizeof($children);$b++)
+	     			{
+	     				//<manifest> element children (can be <metadata>, <organizations> or <resources> )
+	     				if($children[$b]->type == XML_ELEMENT_NODE){
+		     				switch($children[$b]->tagname){
+		     					case 'metadata':
+		     						//parse items from inside the <metadata> element
+		     						$this->metadata = new scormMetadata('manifest',$children[$b]);
+		     						break;
+		     					case 'organizations':
+		     						//contains the course structure - this element appears 1 and only 1 time in a package imsmanifest. It contains at least one 'organization' sub-element
+		     						$orgs_attribs = $children[$b]->attributes();
+		     						for($c=0; $c<sizeof($orgs_attribs);$c++)
+		     						{//attributes of the <organizations> element
+	     								if($orgs_attribs[$c]->type == XML_ATTRIBUTE_NODE){
+			     							$this->manifest['organizations'][$orgs_attribs[$c]->name] = $orgs_attribs[$c]->value;
+	     								}
+		     						}
+		     						$orgs_nodes = $children[$b]->children();
+		     						$i = 0;
+		     						$found_an_org = false;
+		     						foreach($orgs_nodes as $c => $dummy)
+		     						{
+		     							//<organization> elements - can contain <item>, <metadata> and <title>
+		     							//Here we are at the 'organization' level. There might be several organization tags but
+		     							//there is generally only one.
+		     							//There are generally three children nodes we are looking for inside and organization:
+		     							//-title
+		     							//-item (may contain other item tags or may appear several times inside organization)
+		     							//-metadata (relative to the organization)
+		     							$found_an_org = false;
+	     								$orgnode =& $orgs_nodes[$c];
+	     								switch($orgnode->type){
+		     								case XML_TEXT_NODE:
+		     									//ignore here
+		     									break;
+		     								case XML_ATTRIBUTE_NODE:
+		     									//just in case ther would be interesting attributes inside the organization tag. There shouldn't
+		     									//as this is a node-level, not a data level
+		     									//$manifest['organizations'][$i][$orgnode->name] = $orgnode->value;
+		     									//$found_an_org = true;
+		     									break;
+		     								case XML_ELEMENT_NODE:
+		     									//<item>,<metadata> or <title> (or attributes)
+			     								$organizations_attributes = $orgnode->attributes();
+			     								foreach($organizations_attributes as $d1 => $dummy)
+			     								{
+													//$manifest['organizations'][$i]['attributes'][$organizations_attributes[$d1]->name] = $organizations_attributes[$d1]->value;
+			     									//$found_an_org = true;
+			     									$this->organizations_att[$organizations_attributes[$d1]->name] = $organizations_attributes[$d1]->value;
+			     								}
+		     									$oOrganization = new scormOrganization('manifest',$orgnode,$this->manifest_encoding);
+		     									if($oOrganization->identifier != ''){
+		     										$name = $oOrganization->get_name();
+		     										if(empty($name)){
+		     											//if the org title is empty, use zip file name
+		     											$myname = $this->zipname;
+		     											if($this->lastzipnameindex != 0){
+		     												$myname = $myname + $this->lastzipnameindex;
+		     												$this->lastzipnameindex++;
+		     											}
+		     											$oOrganization->set_name($this->zipname);
+		     										}
+		     										$this->organizations[$oOrganization->identifier] = $oOrganization;
+		     									}
+		     									break;
+		     							}
+		     						}
+		     						break;
+		     					case 'resources':
+		     						$resources_attribs = $children[$b]->attributes();
+		     						for($c=0; $c<sizeof($resources_attribs);$c++)
+		     						{
+	     								if($resources_attribs[$c]->type == XML_ATTRIBUTE_NODE){
+			     							$this->manifest['resources'][$resources_attribs[$c]->name] = $resources_attribs[$c]->value;
+	     								}
+		     						}
+		     						$resources_nodes = $children[$b]->children();
+		     						$i = 0;
+		     						foreach($resources_nodes as $c => $dummy)
+		     						{
+			     						/*
+			     						$my_res = scorm::parse_items($resources_nodes[$c]);
+			     						scorm::parse_items_get_refurls($resources_nodes[$c],$refurls);
+			     						if(count($my_res)>0)
+			     						{
+			     							$manifest['resources'][$i] = $my_res;
+			     						}
+			     						*/
+		     							$oResource = new scormResource('manifest',$resources_nodes[$c]);
+			     						if($oResource->identifier != ''){
+											$this->resources[$oResource->identifier] = $oResource;
+			     							$i++;
+			     						}
+		     						}
+		     						//contains links to physical resources
+		     						break;
+		     					case 'manifest':
+		     						//only for sub-manifests
+		     						break;
+		     				}
+	     				}
+	     			}
+	     		}
+		     	unset($doc);
+	     	}elseif($v==5){
+		    	if($this->debug>0){error_log('In scorm::parse_manifest() - Parsing using PHP5 method',0);}
+	     		$doc = new DOMDocument();
+	     		$res = $doc->load($file);
+	     		if($res===false){
+	     			if($this->debug>0){error_log('New LP - In scorm::parse_manifest() - Exception thrown when loading '.$file.' in DOMDocument',0);}
+	     			//throw exception?
+	     			return null;
+	     		}
+
+	     		if(!empty($doc->xmlEncoding)){
+	     			$this->manifest_encoding = strtoupper($doc->xmlEncoding);
+	     		}
+	     		if($this->debug>1){error_log('New LP - Called  (encoding:'.$doc->xmlEncoding.' - saved: '.$this->manifest_encoding.')',0);}
 
-				$root = $doc->documentElement;
-				if($root->hasAttributes()){
-	     			$attributes = $root->attributes;
-	     			if($attributes->length !== 0){
-		     			foreach($attributes as $attrib)
-		     			{//<manifest> element attributes
-							$this->manifest[$attrib->name] = $attrib->value;
-		     			}
-	     			}
-				}
-     			$this->manifest['name'] = $root->tagName;
-				if($root->hasChildNodes()){
-	     			$children = $root->childNodes;
-	     			if($children->length !== 0){
-		     			foreach($children as $child)
-		     			{
-		     				//<manifest> element children (can be <metadata>, <organizations> or <resources> )
-		     				if($child->nodeType == XML_ELEMENT_NODE){
-			     				switch($child->tagName){
-			     					case 'metadata':
-			     						//parse items from inside the <metadata> element
-			     						$this->metadata = new scormMetadata('manifest',$child);
-			     						break;
-			     					case 'organizations':
-			     						//contains the course structure - this element appears 1 and only 1 time in a package imsmanifest. It contains at least one 'organization' sub-element
-			     						$orgs_attribs = $child->attributes;
-			     						foreach($orgs_attribs as $orgs_attrib)
-			     						{//attributes of the <organizations> element
-		     								if($orgs_attrib->nodeType == XML_ATTRIBUTE_NODE){
-				     							$this->manifest['organizations'][$orgs_attrib->name] = $orgs_attrib->value;
-		     								}
-			     						}
-			     						$orgs_nodes = $child->childNodes;
-			     						$i = 0;
-			     						$found_an_org = false;
-			     						foreach($orgs_nodes as $orgnode)
-			     						{
-			     							//<organization> elements - can contain <item>, <metadata> and <title>
-			     							//Here we are at the 'organization' level. There might be several organization tags but
-			     							//there is generally only one.
-			     							//There are generally three children nodes we are looking for inside and organization:
-			     							//-title
-			     							//-item (may contain other item tags or may appear several times inside organization)
-			     							//-metadata (relative to the organization)
-			     							$found_an_org = false;
-		     								switch($orgnode->nodeType){
-			     								case XML_TEXT_NODE:
-			     									//ignore here
-			     									break;
-			     								case XML_ATTRIBUTE_NODE:
-			     									//just in case there would be interesting attributes inside the organization tag. There shouldn't
-			     									//as this is a node-level, not a data level
-			     									//$manifest['organizations'][$i][$orgnode->name] = $orgnode->value;
-			     									//$found_an_org = true;
-			     									break;
-			     								case XML_ELEMENT_NODE:
-			     									//<item>,<metadata> or <title> (or attributes)
-				     								$organizations_attributes = $orgnode->attributes;
-				     								foreach($organizations_attributes as $orgs_attr)
-				     								{
-				     									$this->organizations_att[$orgs_attr->name] = $orgs_attr->value;
-				     								}
-			     									$oOrganization = new scormOrganization('manifest',$orgnode,$this->manifest_encoding);
-			     									if($oOrganization->identifier != ''){
-			     										$name = $oOrganization->get_name();
-			     										if(empty($name)){
-			     											//if the org title is empty, use zip file name
-			     											$myname = $this->zipname;
-			     											if($this->lastzipnameindex != 0){
-			     												$myname = $myname + $this->lastzipnameindex;
-			     												$this->lastzipnameindex++;
-			     											}
-			     											$oOrganization->set_name($this->zipname);
-			     										}
-			     										$this->organizations[$oOrganization->identifier] = $oOrganization;
-			     									}
-			     									break;
-			     							}
-			     						}
-			     						break;
-			     					case 'resources':
-			     						if($child->hasAttributes()){
-				     						$resources_attribs = $child->attributes;
-				     						foreach($resources_attribs as $res_attr)
-				     						{
-			     								if($res_attr->type == XML_ATTRIBUTE_NODE){
-					     							$this->manifest['resources'][$res_attr->name] = $res_attr->value;
-			     								}
-				     						}
-			     						}
-			     						if($child->hasChildNodes()){
-				     						$resources_nodes = $child->childNodes;
-				     						$i = 0;
-				     						foreach($resources_nodes as $res_node)
-				     						{
-				     							$oResource = new scormResource('manifest',$res_node);
-					     						if($oResource->identifier != ''){
-													$this->resources[$oResource->identifier] = $oResource;
-					     							$i++;
-					     						}
-				     						}
-			     						}
-			     						//contains links to physical resources
-			     						break;
-			     					case 'manifest':
-			     						//only for sub-manifests
-			     						break;
-			     				}
-		     				}
-			     		}
-	     			}
-				}
-		     	unset($doc);
-			}else{
-		    	if($this->debug>0){error_log('In scorm::parse_manifest() - PHP version is not 4 nor 5, cannot parse',0);}
-	     		$this->set_error_msg("Parsing impossible because PHP version is not 4 nor 5");
-		    	return null;
-			}
-     	}else{
-     		if($this->debug>1){error_log('New LP - Could not open/read file '.$file,0);}
-     		$this->set_error_msg("File $file could not be read");
-     		return null;
-     	}
-     	//TODO close the DOM handler
-     	return $this->manifest;
-     }
-     /**
-      * Import the scorm object (as a result from the parse_manifest function) into the database structure
+				$root = $doc->documentElement;
+				if($root->hasAttributes()){
+	     			$attributes = $root->attributes;
+	     			if($attributes->length !== 0){
+		     			foreach($attributes as $attrib)
+		     			{//<manifest> element attributes
+							$this->manifest[$attrib->name] = $attrib->value;
+		     			}
+	     			}
+				}
+     			$this->manifest['name'] = $root->tagName;
+				if($root->hasChildNodes()){
+	     			$children = $root->childNodes;
+	     			if($children->length !== 0){
+		     			foreach($children as $child)
+		     			{
+		     				//<manifest> element children (can be <metadata>, <organizations> or <resources> )
+		     				if($child->nodeType == XML_ELEMENT_NODE){
+			     				switch($child->tagName){
+			     					case 'metadata':
+			     						//parse items from inside the <metadata> element
+			     						$this->metadata = new scormMetadata('manifest',$child);
+			     						break;
+			     					case 'organizations':
+			     						//contains the course structure - this element appears 1 and only 1 time in a package imsmanifest. It contains at least one 'organization' sub-element
+			     						$orgs_attribs = $child->attributes;
+			     						foreach($orgs_attribs as $orgs_attrib)
+			     						{//attributes of the <organizations> element
+		     								if($orgs_attrib->nodeType == XML_ATTRIBUTE_NODE){
+				     							$this->manifest['organizations'][$orgs_attrib->name] = $orgs_attrib->value;
+		     								}
+			     						}
+			     						$orgs_nodes = $child->childNodes;
+			     						$i = 0;
+			     						$found_an_org = false;
+			     						foreach($orgs_nodes as $orgnode)
+			     						{
+			     							//<organization> elements - can contain <item>, <metadata> and <title>
+			     							//Here we are at the 'organization' level. There might be several organization tags but
+			     							//there is generally only one.
+			     							//There are generally three children nodes we are looking for inside and organization:
+			     							//-title
+			     							//-item (may contain other item tags or may appear several times inside organization)
+			     							//-metadata (relative to the organization)
+			     							$found_an_org = false;
+		     								switch($orgnode->nodeType){
+			     								case XML_TEXT_NODE:
+			     									//ignore here
+			     									break;
+			     								case XML_ATTRIBUTE_NODE:
+			     									//just in case there would be interesting attributes inside the organization tag. There shouldn't
+			     									//as this is a node-level, not a data level
+			     									//$manifest['organizations'][$i][$orgnode->name] = $orgnode->value;
+			     									//$found_an_org = true;
+			     									break;
+			     								case XML_ELEMENT_NODE:
+			     									//<item>,<metadata> or <title> (or attributes)
+				     								$organizations_attributes = $orgnode->attributes;
+				     								foreach($organizations_attributes as $orgs_attr)
+				     								{
+				     									$this->organizations_att[$orgs_attr->name] = $orgs_attr->value;
+				     								}
+			     									$oOrganization = new scormOrganization('manifest',$orgnode,$this->manifest_encoding);
+			     									if($oOrganization->identifier != ''){
+			     										$name = $oOrganization->get_name();
+			     										if(empty($name)){
+			     											//if the org title is empty, use zip file name
+			     											$myname = $this->zipname;
+			     											if($this->lastzipnameindex != 0){
+			     												$myname = $myname + $this->lastzipnameindex;
+			     												$this->lastzipnameindex++;
+			     											}
+			     											$oOrganization->set_name($this->zipname);
+			     										}
+			     										$this->organizations[$oOrganization->identifier] = $oOrganization;
+			     									}
+			     									break;
+			     							}
+			     						}
+			     						break;
+			     					case 'resources':
+			     						if($child->hasAttributes()){
+				     						$resources_attribs = $child->attributes;
+				     						foreach($resources_attribs as $res_attr)
+				     						{
+			     								if($res_attr->type == XML_ATTRIBUTE_NODE){
+					     							$this->manifest['resources'][$res_attr->name] = $res_attr->value;
+			     								}
+				     						}
+			     						}
+			     						if($child->hasChildNodes()){
+				     						$resources_nodes = $child->childNodes;
+				     						$i = 0;
+				     						foreach($resources_nodes as $res_node)
+				     						{
+				     							$oResource = new scormResource('manifest',$res_node);
+					     						if($oResource->identifier != ''){
+													$this->resources[$oResource->identifier] = $oResource;
+					     							$i++;
+					     						}
+				     						}
+			     						}
+			     						//contains links to physical resources
+			     						break;
+			     					case 'manifest':
+			     						//only for sub-manifests
+			     						break;
+			     				}
+		     				}
+			     		}
+	     			}
+				}
+		     	unset($doc);
+			}else{
+		    	if($this->debug>0){error_log('In scorm::parse_manifest() - PHP version is not 4 nor 5, cannot parse',0);}
+	     		$this->set_error_msg("Parsing impossible because PHP version is not 4 nor 5");
+		    	return null;
+			}
+     	}else{
+     		if($this->debug>1){error_log('New LP - Could not open/read file '.$file,0);}
+     		$this->set_error_msg("File $file could not be read");
+     		return null;
+     	}
+     	//TODO close the DOM handler
+     	return $this->manifest;
+     }
+     /**
+      * Import the scorm object (as a result from the parse_manifest function) into the database structure
       * @param	string	Unique course code
-      * @return	bool	Returns -1 on error
-      */
-     function import_manifest($course_code){
-     	if($this->debug>0){error_log('New LP - Entered import_manifest('.$course_code.')',0);}
+      * @return	bool	Returns -1 on error
+      */
+     function import_manifest($course_code){
+     	if($this->debug>0){error_log('New LP - Entered import_manifest('.$course_code.')',0);}
+
+		$sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE code='$course_code'";
+        $res = Database::query($sql,__FILE__,__LINE__);
+        if(Database::num_rows($res)<1){ error_log('Database for '.$course_code.' not found '.__FILE__.' '.__LINE__,0);return -1;}
+        $row = Database::fetch_array($res);
+        $dbname = $row['db_name'];
+
+		//get table names
+		$new_lp = Database::get_course_table(TABLE_LP_MAIN, $dbname);
+		$new_lp_item = Database::get_course_table(TABLE_LP_ITEM, $dbname);
+
+		foreach($this->organizations as $id => $dummy)
+		{
+			$oOrganization =& $this->organizations[$id];
+	     	//prepare and execute insert queries
+	     	//-for learnpath
+	     	//-for items
+	     	//-for views?
+	    	$get_max = "SELECT MAX(display_order) FROM $new_lp";
+	    	$res_max = Database::query($get_max);
+	    	$dsp = 1;
+	    	if(Database::num_rows($res_max)>0){
+	    		$row = Database::fetch_array($res_max);
+	    		$dsp = $row[0]+1;
+	    	}
+	     	$myname = $oOrganization->get_name();
+	     	//$this->manifest_encoding = 'UTF-8';
+	     	global $charset;
+	     	if(!empty($charset) && !empty($this->manifest_encoding) && $this->manifest_encoding != $charset){
+	     		$myname = api_convert_encoding($myname,$charset,$this->manifest_encoding);
+	     	}
+			$sql = "INSERT INTO $new_lp (lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order)" .
+					"VALUES (2,'".$myname."', '".$oOrganization->get_ref()."','','".$this->subdir."', 0, 'embedded', '".$this->manifest_encoding."','scorm_api.php',$dsp)";
+			if($this->debug>1){error_log('New LP - In import_manifest(), inserting path: '. $sql,0);}
+			$res = Database::query($sql,__FILE__,__LINE__);
+			$lp_id = Database::get_last_insert_id();
+			$this->lp_id = $lp_id;
+			//insert into item_property
+			api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'LearnpathAdded',api_get_user_id());
+			api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'visible',api_get_user_id());
 
-		$sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE code='$course_code'";
-        $res = Database::query($sql,__FILE__,__LINE__);
-        if(Database::num_rows($res)<1){ error_log('Database for '.$course_code.' not found '.__FILE__.' '.__LINE__,0);return -1;}
-        $row = Database::fetch_array($res);
-        $dbname = $row['db_name'];
-
-		//get table names
-		$new_lp = Database::get_course_table(TABLE_LP_MAIN, $dbname);
-		$new_lp_item = Database::get_course_table(TABLE_LP_ITEM, $dbname);
+			//now insert all elements from inside that learning path
+			//make sure we also get the href and sco/asset from the resources
+			$list = $oOrganization->get_flat_items_list();
+			$parents_stack = array(0);
+			$parent = 0;
+			$previous = 0;
+			$level = 0;
+			foreach($list as $item){
+				if($item['level'] > $level){
+					//push something into the parents array
+					array_push($parents_stack,$previous);
+					$parent = $previous;
+				}elseif($item['level'] < $level){
+					$diff = $level - $item['level'];
+					//pop something out of the parents array
+					for($j=1;$j<=$diff;$j++){
+						$outdated_parent = array_pop($parents_stack);
+					}
+					$parent = array_pop($parents_stack); //just save that value, then add it back
+					array_push($parents_stack,$parent);
+				}
+				$path = '';
+				$type = 'dir';
+				if(isset($this->resources[$item['identifierref']])){
+					$oRes =& $this->resources[$item['identifierref']];
+					$path = @$oRes->get_path();
+					if(!empty($path)){
+						$temptype = $oRes->get_scorm_type();
+						if(!empty($temptype)){
+							$type = $temptype;
+						}
+					}
+				}
+				$level = $item['level'];
+				$field_add = '';
+				$value_add = '';
+				if(!empty($item['masteryscore'])){
+					$field_add .= 'mastery_score, ';
+					$value_add .= $item['masteryscore'].',';
+				}
+				if(!empty($item['maxtimeallowed']))
+				{
+					$field_add .= 'max_time_allowed, ';
+					$value_add .= "'".$item['maxtimeallowed']."',";
+				}
+				$title = Database::escape_string($item['title']);
+				$max_score = Database::escape_string($item['max_score']);
+				if ($max_score==0 || is_null($max_score) || $max_score=='') {
+					$max_score=100;
+				}
+				//DOM in PHP5 is always recovering data as UTF-8, somehow, no matter what
+				//the XML document encoding is. This means that we have to convert
+				//the data to the declared encoding when it is not UTF-8
+				if($this->manifest_encoding != 'UTF-8'){
+		     		$title = api_convert_encoding($title,$this->manifest_encoding,'UTF-8');
+		     	}
+				//if($this->manifest_encoding != $charset){
+		     	//	$title = api_convert_encoding($title,$charset,$this->manifest_encoding);
+		     	//}
+				$identifier = Database::escape_string($item['identifier']);
+				$prereq = Database::escape_string($item['prerequisites']);
+				$sql_item = "INSERT INTO $new_lp_item " .
+						"(lp_id,item_type,ref,title," .
+						"path,min_score,max_score, $field_add" .
+						"parent_item_id,previous_item_id,next_item_id," .
+						"prerequisite,display_order,launch_data," .
+						"parameters) " .
+						"VALUES " .
+						"($lp_id, '$type','".$identifier."','".$title."'," .
+						"'$path',0,'$max_score', $value_add" .
+						"$parent, $previous, 0, " .
+						"'$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."'," .
+						"'".$item['parameters']."'" .
+						")";
+				$res_item = Database::query($sql_item);
+				if($this->debug>1){error_log('New LP - In import_manifest(), inserting item : '.$sql_item.' : '.mysql_error(),0);}
+				$item_id = Database::get_last_insert_id();
+				//now update previous item to change next_item_id
+				$upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE id = $previous";
+				$upd_res = Database::query($upd);
+				//update previous item id
+				$previous = $item_id;
 
-		foreach($this->organizations as $id => $dummy)
-		{
-			$oOrganization =& $this->organizations[$id];
-	     	//prepare and execute insert queries
-	     	//-for learnpath
-	     	//-for items
-	     	//-for views?
-	    	$get_max = "SELECT MAX(display_order) FROM $new_lp";
-	    	$res_max = Database::query($get_max);
-	    	$dsp = 1;
-	    	if(Database::num_rows($res_max)>0){
-	    		$row = Database::fetch_array($res_max);
-	    		$dsp = $row[0]+1;
-	    	}
-	     	$myname = $oOrganization->get_name();
-	     	//$this->manifest_encoding = 'UTF-8';
-	     	global $charset;
-	     	if(!empty($charset) && !empty($this->manifest_encoding) && $this->manifest_encoding != $charset){
-	     		$myname = api_convert_encoding($myname,$charset,$this->manifest_encoding);
-	     	}
-			$sql = "INSERT INTO $new_lp (lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order)" .
-					"VALUES (2,'".$myname."', '".$oOrganization->get_ref()."','','".$this->subdir."', 0, 'embedded', '".$this->manifest_encoding."','scorm_api.php',$dsp)";
-			if($this->debug>1){error_log('New LP - In import_manifest(), inserting path: '. $sql,0);}
-			$res = Database::query($sql,__FILE__,__LINE__);
-			$lp_id = Database::get_last_insert_id();
-			$this->lp_id = $lp_id;
-			//insert into item_property
-			api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'LearnpathAdded',api_get_user_id());
-			api_item_property_update(api_get_course_info($course_code),TOOL_LEARNPATH,$this->lp_id,'visible',api_get_user_id());
+				// code for indexing, now only index specific fields like terms and the title
+				if (!empty($_POST['index_document'])) {
+					require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
+					require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
+					require_once(api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php');
 
-			//now insert all elements from inside that learning path
-			//make sure we also get the href and sco/asset from the resources
-			$list = $oOrganization->get_flat_items_list();
-			$parents_stack = array(0);
-			$parent = 0;
-			$previous = 0;
-			$level = 0;
-			foreach($list as $item){
-				if($item['level'] > $level){
-					//push something into the parents array
-					array_push($parents_stack,$previous);
-					$parent = $previous;
-				}elseif($item['level'] < $level){
-					$diff = $level - $item['level'];
-					//pop something out of the parents array
-					for($j=1;$j<=$diff;$j++){
-						$outdated_parent = array_pop($parents_stack);
-					}
-					$parent = array_pop($parents_stack); //just save that value, then add it back
-					array_push($parents_stack,$parent);
-				}
-				$path = '';
-				$type = 'dir';
-				if(isset($this->resources[$item['identifierref']])){
-					$oRes =& $this->resources[$item['identifierref']];
-					$path = @$oRes->get_path();
-					if(!empty($path)){
-						$temptype = $oRes->get_scorm_type();
-						if(!empty($temptype)){
-							$type = $temptype;
-						}
-					}
-				}
-				$level = $item['level'];
-				$field_add = '';
-				$value_add = '';
-				if(!empty($item['masteryscore'])){
-					$field_add .= 'mastery_score, ';
-					$value_add .= $item['masteryscore'].',';
-				}
-				if(!empty($item['maxtimeallowed']))
-				{
-					$field_add .= 'max_time_allowed, ';
-					$value_add .= "'".$item['maxtimeallowed']."',";
-				}
-				$title = Database::escape_string($item['title']);
-				$max_score = Database::escape_string($item['max_score']);
-				if ($max_score==0 || is_null($max_score) || $max_score=='') {
-					$max_score=100;
+					$di = new DokeosIndexer();
+					isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
+					$di->connectDb(NULL, NULL, $lang);
+					$ic_slide = new IndexableChunk();
+					$ic_slide->addValue("title", $title);
+					$specific_fields = get_specific_field_list();
+					$all_specific_terms = '';
+					foreach ($specific_fields as $specific_field) {
+						if (isset($_REQUEST[$specific_field['code']])) {
+							$sterms = trim($_REQUEST[$specific_field['code']]);
+							$all_specific_terms .= ' '. $sterms;
+							if (!empty($sterms)) {
+								$sterms = explode(',', $sterms);
+								foreach ($sterms as $sterm) {
+									$ic_slide->addTerm(trim($sterm), $specific_field['code']);
+								}
+							}
+						}
+					}
+					$body_to_index = $all_specific_terms .' '. $title;
+					$ic_slide->addValue("content", $body_to_index);
+					//TODO: add a comment to say terms separated by commas
+					$courseid = api_get_course_id();
+					$ic_slide->addCourseId($courseid);
+					$ic_slide->addToolId(TOOL_LEARNPATH);
+					$xapian_data = array(
+						SE_COURSE_ID => $courseid,
+						SE_TOOL_ID => TOOL_LEARNPATH,
+						SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => ''), //TODO unify with other lp types
+						SE_USER => (int)api_get_user_id(),
+					);
+					$ic_slide->xapian_data = serialize($xapian_data);
+					$di->addChunk($ic_slide);
+					//index and return search engine document id
+					$did = $di->index();
+					if ($did) {
+                        // save it to db
+                        $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
+                        $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
+                                VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
+                        $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
+                        Database::query($sql,__FILE__,__LINE__);
+					}
 				}
-				//DOM in PHP5 is always recovering data as UTF-8, somehow, no matter what
-				//the XML document encoding is. This means that we have to convert
-				//the data to the declared encoding when it is not UTF-8
-				if($this->manifest_encoding != 'UTF-8'){
-		     		$title = api_convert_encoding($title,$this->manifest_encoding,'UTF-8');
-		     	}
-				//if($this->manifest_encoding != $charset){
-		     	//	$title = api_convert_encoding($title,$charset,$this->manifest_encoding);
-		     	//}
-				$identifier = Database::escape_string($item['identifier']);
-				$prereq = Database::escape_string($item['prerequisites']);
-				$sql_item = "INSERT INTO $new_lp_item " .
-						"(lp_id,item_type,ref,title," .
-						"path,min_score,max_score, $field_add" .
-						"parent_item_id,previous_item_id,next_item_id," .
-						"prerequisite,display_order,launch_data," .
-						"parameters) " .
-						"VALUES " .
-						"($lp_id, '$type','".$identifier."','".$title."'," .
-						"'$path',0,'$max_score', $value_add" .
-						"$parent, $previous, 0, " .
-						"'$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."'," .
-						"'".$item['parameters']."'" .
-						")";
-				$res_item = Database::query($sql_item);
-				if($this->debug>1){error_log('New LP - In import_manifest(), inserting item : '.$sql_item.' : '.mysql_error(),0);}
-				$item_id = Database::get_last_insert_id();
-				//now update previous item to change next_item_id
-				$upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE id = $previous";
-				$upd_res = Database::query($upd);
-				//update previous item id
-				$previous = $item_id;
-
-				// code for indexing, now only index specific fields like terms and the title
-				if (!empty($_POST['index_document'])) {
-					require_once(api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php');
-					require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
-					require_once(api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php');
-
-					$di = new DokeosIndexer();
-					isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
-					$di->connectDb(NULL, NULL, $lang);
-					$ic_slide = new IndexableChunk();
-					$ic_slide->addValue("title", $title);
-					$specific_fields = get_specific_field_list();
-					$all_specific_terms = '';
-					foreach ($specific_fields as $specific_field) {
-						if (isset($_REQUEST[$specific_field['code']])) {
-							$sterms = trim($_REQUEST[$specific_field['code']]);
-							$all_specific_terms .= ' '. $sterms;
-							if (!empty($sterms)) {
-								$sterms = explode(',', $sterms);
-								foreach ($sterms as $sterm) {
-									$ic_slide->addTerm(trim($sterm), $specific_field['code']);
-								}
-							}
-						}
-					}
-					$body_to_index = $all_specific_terms .' '. $title;
-					$ic_slide->addValue("content", $body_to_index);
-					//TODO: add a comment to say terms separated by commas
-					$courseid = api_get_course_id();
-					$ic_slide->addCourseId($courseid);
-					$ic_slide->addToolId(TOOL_LEARNPATH);
-					$xapian_data = array(
-						SE_COURSE_ID => $courseid,
-						SE_TOOL_ID => TOOL_LEARNPATH,
-						SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => ''), //TODO unify with other lp types
-						SE_USER => (int)api_get_user_id(),
-					);
-					$ic_slide->xapian_data = serialize($xapian_data);
-					$di->addChunk($ic_slide);
-					//index and return search engine document id
-					$did = $di->index();
-					if ($did) {
-                        // save it to db
-                        $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
-                        $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
-                                VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
-                        $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
-                        Database::query($sql,__FILE__,__LINE__);
-					}
-				}
-
-			}
-		}
-     }
-	 /**
-	  * Intermediate to import_package only to allow import from local zip files
+
+			}
+		}
+     }
+	 /**
+	  * Intermediate to import_package only to allow import from local zip files
 	  * @param	string	Path to the zip file, from the dokeos sys root
-	  * @param	string	Current path (optional)
-	  * @return string	Absolute path to the imsmanifest.xml file or empty string on error
-	  */
-	 function import_local_package($file_path,$current_dir='')
-	 {
-	 	//todo prepare info as given by the $_FILES[''] vector
-	 	$file_info = array();
-	 	$file_info['tmp_name'] = $file_path;
-	 	$file_info['name'] = basename($file_path);
-	 	//call the normal import_package function
+	  * @param	string	Current path (optional)
+	  * @return string	Absolute path to the imsmanifest.xml file or empty string on error
+	  */
+	 function import_local_package($file_path,$current_dir='')
+	 {
+	 	//todo prepare info as given by the $_FILES[''] vector
+	 	$file_info = array();
+	 	$file_info['tmp_name'] = $file_path;
+	 	$file_info['name'] = basename($file_path);
+	 	//call the normal import_package function
 	 	return $this->import_package($file_info,$current_dir);
-	 }
-     /**
-      * Imports a zip file into the Dokeos structure
-      * @param	string	Zip file info as given by $_FILES['userFile']
-      * @return	string	Absolute path to the imsmanifest.xml file or empty string on error
-      */
-     function import_package($zip_file_info,$current_dir = '')
-     {
-     	if($this->debug>0){error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method',0);}
-     	$maxFilledSpace = 1000000000;
-     	$zip_file_path = $zip_file_info['tmp_name'];
-     	$zip_file_name = $zip_file_info['name'];
-     	if($this->debug>1){error_log('New LP - import_package() - zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name,0);}
-     	$course_rel_dir  = api_get_course_path().'/scorm'; //scorm dir web path starting from /courses
-		$course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; //absolute system path for this course
-		$current_dir = replace_dangerous_char(trim($current_dir),'strict'); //current dir we are in, inside scorm/
-     	if($this->debug>1){error_log('New LP - import_package() - current_dir = '.$current_dir,0);}
+	 }
+     /**
+      * Imports a zip file into the Dokeos structure
+      * @param	string	Zip file info as given by $_FILES['userFile']
+      * @return	string	Absolute path to the imsmanifest.xml file or empty string on error
+      */
+     function import_package($zip_file_info,$current_dir = '')
+     {
+     	if($this->debug>0){error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method',0);}
+     	$maxFilledSpace = 1000000000;
+     	$zip_file_path = $zip_file_info['tmp_name'];
+     	$zip_file_name = $zip_file_info['name'];
+     	if($this->debug>1){error_log('New LP - import_package() - zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name,0);}
+     	$course_rel_dir  = api_get_course_path().'/scorm'; //scorm dir web path starting from /courses
+		$course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; //absolute system path for this course
+		$current_dir = replace_dangerous_char(trim($current_dir),'strict'); //current dir we are in, inside scorm/
+     	if($this->debug>1){error_log('New LP - import_package() - current_dir = '.$current_dir,0);}
+
+ 		//$uploaded_filename = $_FILES['userFile']['name'];
+		//get name of the zip file without the extension
+		if($this->debug>1){error_log('New LP - Received zip file name: '.$zip_file_path,0);}
+		$file_info = pathinfo($zip_file_name);
+		$filename = $file_info['basename'];
+		$extension = $file_info['extension'];
+		$file_base_name = str_replace('.'.$extension,'',$filename); //filename without its extension
+		$this->zipname = $file_base_name; //save for later in case we don't have a title
+
+		if($this->debug>1){error_log("New LP - base file name is : ".$file_base_name,0);}
+		$new_dir = replace_dangerous_char(trim($file_base_name),'strict');
+		$this->subdir = $new_dir;
+		if($this->debug>1){error_log("New LP - subdir is first set to : ".$this->subdir,0);}
+
+		$zipFile = new pclZip($zip_file_path);
 
- 		//$uploaded_filename = $_FILES['userFile']['name'];
-		//get name of the zip file without the extension
-		if($this->debug>1){error_log('New LP - Received zip file name: '.$zip_file_path,0);}
-		$file_info = pathinfo($zip_file_name);
-		$filename = $file_info['basename'];
-		$extension = $file_info['extension'];
-		$file_base_name = str_replace('.'.$extension,'',$filename); //filename without its extension
-		$this->zipname = $file_base_name; //save for later in case we don't have a title
+		// Check the zip content (real size and file extension)
 
-		if($this->debug>1){error_log("New LP - base file name is : ".$file_base_name,0);}
-		$new_dir = replace_dangerous_char(trim($file_base_name),'strict');
-		$this->subdir = $new_dir;
-		if($this->debug>1){error_log("New LP - subdir is first set to : ".$this->subdir,0);}
+		$zipContentArray = $zipFile->listContent();
 
-		$zipFile = new pclZip($zip_file_path);
+		$package_type='';
+		$at_root = false;
+		$manifest = '';
+		$manifest_list = array();
 
-		// Check the zip content (real size and file extension)
-
-		$zipContentArray = $zipFile->listContent();
-
-		$package_type='';
-		$at_root = false;
-		$manifest = '';
-		$manifest_list = array();
-
-		//the following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?)
-		foreach($zipContentArray as $thisContent)
-		{
-			//error_log('Looking at  '.$thisContent['filename'],0);
-			if ( preg_match('~.(php.*|phtml)$~i', $thisContent['filename']) )
-			{
-	     		$this->set_error_msg("File $file contains a PHP script");
-				//return api_failure::set_failure('php_file_in_zip_file');
-			}
-			elseif(stristr($thisContent['filename'],'imsmanifest.xml'))
-			{
-				//error_log('Found imsmanifest at '.$thisContent['filename'],0);
-				if($thisContent['filename'] == basename($thisContent['filename'])){
-					$at_root = true;
-				}else{
-					//$this->subdir .= '/'.dirname($thisContent['filename']);
-					if($this->debug>2){error_log("New LP - subdir is now ".$this->subdir,0);}
-				}
-				$package_type = 'scorm';
-				$manifest_list[] = $thisContent['filename'];
-				$manifest = $thisContent['filename']; //just the relative directory inside scorm/
-			}
-			else
-			{
-				//do nothing, if it has not been set as scorm somewhere else, it stays as '' default
-			}
-			$realFileSize += $thisContent['size'];
-		}
-		//now get the shortest path (basically, the imsmanifest that is the closest to the root)
-		$shortest_path = $manifest_list[0];
-		$slash_count = substr_count($shortest_path,'/');
-		foreach($manifest_list as $manifest_path){
+		//the following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?)
+		foreach($zipContentArray as $thisContent)
+		{
+			//error_log('Looking at  '.$thisContent['filename'],0);
+			if ( preg_match('~.(php.*|phtml)$~i', $thisContent['filename']) )
+			{
+	     		$this->set_error_msg("File $file contains a PHP script");
+				//return api_failure::set_failure('php_file_in_zip_file');
+			}
+			elseif(stristr($thisContent['filename'],'imsmanifest.xml'))
+			{
+				//error_log('Found imsmanifest at '.$thisContent['filename'],0);
+				if($thisContent['filename'] == basename($thisContent['filename'])){
+					$at_root = true;
+				}else{
+					//$this->subdir .= '/'.dirname($thisContent['filename']);
+					if($this->debug>2){error_log("New LP - subdir is now ".$this->subdir,0);}
+				}
+				$package_type = 'scorm';
+				$manifest_list[] = $thisContent['filename'];
+				$manifest = $thisContent['filename']; //just the relative directory inside scorm/
+			}
+			else
+			{
+				//do nothing, if it has not been set as scorm somewhere else, it stays as '' default
+			}
+			$realFileSize += $thisContent['size'];
+		}
+		//now get the shortest path (basically, the imsmanifest that is the closest to the root)
+		$shortest_path = $manifest_list[0];
+		$slash_count = substr_count($shortest_path,'/');
+		foreach($manifest_list as $manifest_path){
 			$tmp_slash_count = substr_count($manifest_path,'/');
-			if($tmp_slash_count<$slash_count){
-				$shortest_path = $manifest_path;
-				$slash_count = $tmp_slash_count;
-			}
-		}
-		$this->subdir .= '/'.dirname($shortest_path); //do not concatenate because already done above
-		$manifest = $shortest_path;
+			if($tmp_slash_count<$slash_count){
+				$shortest_path = $manifest_path;
+				$slash_count = $tmp_slash_count;
+			}
+		}
+		$this->subdir .= '/'.dirname($shortest_path); //do not concatenate because already done above
+		$manifest = $shortest_path;
 
-		if($this->debug>1){error_log('New LP - Package type is now '.$package_type,0);}
+		if($this->debug>1){error_log('New LP - Package type is now '.$package_type,0);}
 
-		if($package_type== '')
-		 // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
-		{
-			return api_failure::set_failure('not_scorm_content');
-		}
+		if($package_type== '')
+		 // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
+		{
+			return api_failure::set_failure('not_scorm_content');
+		}
 
-		if (! enough_size($realFileSize, $course_sys_dir, $maxFilledSpace) )
-		{
-			return api_failure::set_failure('not_enough_space');
-		}
+		if (! enough_size($realFileSize, $course_sys_dir, $maxFilledSpace) )
+		{
+			return api_failure::set_failure('not_enough_space');
+		}
 
-		// it happens on Linux that $new_dir sometimes doesn't start with '/'
-		if($new_dir[0] != '/')
-		{
-			$new_dir='/'.$new_dir;
-		}
+		// it happens on Linux that $new_dir sometimes doesn't start with '/'
+		if($new_dir[0] != '/')
+		{
+			$new_dir='/'.$new_dir;
+		}
 
-		if($new_dir[strlen($new_dir)-1] == '/')
-		{
-			$new_dir=substr($new_dir,0,-1);
-		}
+		if($new_dir[strlen($new_dir)-1] == '/')
+		{
+			$new_dir=substr($new_dir,0,-1);
+		}
 
-		/*
-		--------------------------------------
-			Uncompressing phase
-		--------------------------------------
-		*/
-		/*
-			We need to process each individual file in the zip archive to
-			- add it to the database
-			- parse & change relative html links
-			- make sure the filenames are secure (filter funny characters or php extensions)
-		*/
-		if(is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir))
-		{
+		/*
+		--------------------------------------
+			Uncompressing phase
+		--------------------------------------
+		*/
+		/*
+			We need to process each individual file in the zip archive to
+			- add it to the database
+			- parse & change relative html links
+			- make sure the filenames are secure (filter funny characters or php extensions)
+		*/
+		if(is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir))
+		{
 
-			// PHP method - slower...
-			if($this->debug>=1){error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir,0);}
-			$saved_dir = getcwd();
-			chdir($course_sys_dir.$new_dir);
-			$unzippingState = $zipFile->extract();
-			for($j=0;$j<count($unzippingState);$j++)
-			{
-				$state=$unzippingState[$j];
+			// PHP method - slower...
+			if($this->debug>=1){error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir,0);}
+			$saved_dir = getcwd();
+			chdir($course_sys_dir.$new_dir);
+			$unzippingState = $zipFile->extract();
+			for($j=0;$j<count($unzippingState);$j++)
+			{
+				$state=$unzippingState[$j];
 
-				//TODO fix relative links in html files (?)
-				$extension = strrchr($state["stored_filename"], ".");
-				if($this->debug>=1){error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'],0);}
+				//TODO fix relative links in html files (?)
+				$extension = strrchr($state["stored_filename"], ".");
+				if($this->debug>=1){error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'],0);}
 
-			}
+			}
 
-			if(!empty($new_dir))
-			{
-				$new_dir = $new_dir.'/';
-			}
-			//rename files, for example with \\ in it
-			if($dir=@opendir($course_sys_dir.$new_dir))
-			{
-				if($this->debug==1){error_log('New LP - Opened dir '.$course_sys_dir.$new_dir,0);}
-				while($file=readdir($dir))
-				{
-					if($file != '.' && $file != '..')
-					{
-						$filetype="file";
+			if(!empty($new_dir))
+			{
+				$new_dir = $new_dir.'/';
+			}
+			//rename files, for example with \\ in it
+			if($dir=@opendir($course_sys_dir.$new_dir))
+			{
+				if($this->debug==1){error_log('New LP - Opened dir '.$course_sys_dir.$new_dir,0);}
+				while($file=readdir($dir))
+				{
+					if($file != '.' && $file != '..')
+					{
+						$filetype="file";
 
-						if(is_dir($course_sys_dir.$new_dir.$file)) $filetype="folder";
+						if(is_dir($course_sys_dir.$new_dir.$file)) $filetype="folder";
 
-						//TODO RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
-						//$safe_file=replace_dangerous_char($file,'strict');
-						$find_str = array('\\','.php','.phtml');
-						$repl_str = array('/', '.txt','.txt');
-						$safe_file = str_replace($find_str,$repl_str,$file);
+						//TODO RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
+						//$safe_file=replace_dangerous_char($file,'strict');
+						$find_str = array('\\','.php','.phtml');
+						$repl_str = array('/', '.txt','.txt');
+						$safe_file = str_replace($find_str,$repl_str,$file);
 
-						if($safe_file != $file){
-							//@rename($course_sys_dir.$new_dir,$course_sys_dir.'/'.$safe_file);
-							$mydir = dirname($course_sys_dir.$new_dir.$safe_file);
-							if(!is_dir($mydir)){
-								$mysubdirs = split('/',$mydir);
-								$mybasedir = '/';
-								foreach($mysubdirs as $mysubdir){
-									if(!empty($mysubdir)){
-										$mybasedir = $mybasedir.$mysubdir.'/';
-										if(!is_dir($mybasedir)){
-											@mkdir($mybasedir);
-											if($this->debug==1){error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.',0);}
-										}
-									}
-								}
-							}
-							@rename($course_sys_dir.$new_dir.$file,$course_sys_dir.$new_dir.$safe_file);
-							if($this->debug==1){error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file,0);}
+						if($safe_file != $file){
+							//@rename($course_sys_dir.$new_dir,$course_sys_dir.'/'.$safe_file);
+							$mydir = dirname($course_sys_dir.$new_dir.$safe_file);
+							if(!is_dir($mydir)){
+								$mysubdirs = split('/',$mydir);
+								$mybasedir = '/';
+								foreach($mysubdirs as $mysubdir){
+									if(!empty($mysubdir)){
+										$mybasedir = $mybasedir.$mysubdir.'/';
+										if(!is_dir($mybasedir)){
+											@mkdir($mybasedir);
+											if($this->debug==1){error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.',0);}
+										}
+									}
+								}
+							}
+							@rename($course_sys_dir.$new_dir.$file,$course_sys_dir.$new_dir.$safe_file);
+							if($this->debug==1){error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file,0);}
 						}
-						//set_default_settings($course_sys_dir,$safe_file,$filetype);
-					}
-				}
+						//set_default_settings($course_sys_dir,$safe_file,$filetype);
+					}
+				}
 
-				closedir($dir);
-				chdir($saved_dir);
+				closedir($dir);
+				chdir($saved_dir);
 
-				$perm = api_get_setting('permissions_for_new_directories');
-				$perm = octdec(!empty($perm)?$perm:'0770');
+				$perm = api_get_setting('permissions_for_new_directories');
+				$perm = octdec(!empty($perm)?$perm:'0770');
 
-				api_chmod_R($course_sys_dir.$new_dir , $perm);
-			}
-		}else{
-			return '';
-		}
-		return $course_sys_dir.$new_dir.$manifest;
-	}
-	/**
-	 * Sets the proximity setting in the database
-	 * @param	string	Proximity setting
-	 */
-	 function set_proximity($proxy=''){
-		if($this->debug>0){error_log('In scorm::set_proximity('.$proxy.') method',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
+				api_chmod_R($course_sys_dir.$new_dir , $perm);
+			}
+		}else{
+			return '';
+		}
+		return $course_sys_dir.$new_dir.$manifest;
+	}
+	/**
+	 * Sets the proximity setting in the database
+	 * @param	string	Proximity setting
+	 */
+	 function set_proximity($proxy=''){
+		if($this->debug>0){error_log('In scorm::set_proximity('.$proxy.') method',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
 
-	 /**
-	 * Sets the theme setting in the database
-	 * @param	string	theme setting
-	 */
-	 function set_theme($theme=''){
-		if($this->debug>0){error_log('In scorm::set_theme('.$theme.') method',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
+	 /**
+	 * Sets the theme setting in the database
+	 * @param	string	theme setting
+	 */
+	 function set_theme($theme=''){
+		if($this->debug>0){error_log('In scorm::set_theme('.$theme.') method',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
 
-	 	 /**
-	 * Sets the image setting in the database
-	 * @param	string preview_image setting
-	 */
-	 function set_preview_image($preview_image=''){
-		if($this->debug>0){error_log('In scorm::set_theme('.$preview_image.') method',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET preview_image = '$preview_image' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
+	 	 /**
+	 * Sets the image setting in the database
+	 * @param	string preview_image setting
+	 */
+	 function set_preview_image($preview_image=''){
+		if($this->debug>0){error_log('In scorm::set_theme('.$preview_image.') method',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET preview_image = '$preview_image' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
 
 
-	 /**
-	 * Sets the author  setting in the database
-	 * @param	string preview_image setting
-	 */
-	 function set_author($author=''){
-		if($this->debug>0){error_log('In scorm::set_author('.$author.') method',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET author = '$author' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
+	 /**
+	 * Sets the author  setting in the database
+	 * @param	string preview_image setting
+	 */
+	 function set_author($author=''){
+		if($this->debug>0){error_log('In scorm::set_author('.$author.') method',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET author = '$author' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
 
 
 
 
-	/**
-	 * Sets the content maker setting in the database
-	 * @param	string	Proximity setting
-	 */
-	 function set_maker($maker=''){
-		if($this->debug>0){error_log('In scorm::set_maker method('.$maker.')',0);}
-	 	$lp = $this->get_id();
-	 	if($lp!=0){
-	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	 		$sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE id = ".$lp;
-	 		$res = Database::query($sql);
-	 		return $res;
-	 	}else{
-	 		return false;
-	 	}
-	 }
-	 /**
-	  * Exports the current SCORM object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
-	  * @param	integer	Learnpath ID (optional, taken from object context if not defined)
-	  */
-	  function export_zip($lp_id=null){
-		if($this->debug>0){error_log('In scorm::export_zip method('.$lp_id.')',0);}
-	 	if(empty($lp_id)){
-			if(!is_object($this))
-			{
-				return false;
-			}
-			else{
-				$id = $this->get_id();
-				if(empty($id)){
-					return false;
-				}
-	 			else{
-	 				$lp_id = $this->get_id();
-	 			}
-			}
-	 	}
-	 	//error_log('New LP - in export_zip()',0);
-	 	//zip everything that is in the corresponding scorm dir
-	 	//write the zip file somewhere (might be too big to return)
-		require_once (api_get_path(LIBRARY_PATH)."fileUpload.lib.php");
-		require_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
-		require_once (api_get_path(LIBRARY_PATH)."document.lib.php");
-		require_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
-		require_once ("learnpath_functions.inc.php");
-		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-		$_course = Database::get_course_info(api_get_course_id());
-
-		$sql = "SELECT * FROM $tbl_lp WHERE id=".$lp_id;
-		$result = Database::query($sql, __FILE__, __LINE__);
-		$row = mysql_fetch_array($result);
-		$LPname = $row['path'];
-		$list = split('/',$LPname);
-		$LPnamesafe = $list[0];
-		//$zipfoldername = '/tmp';
-		//$zipfoldername = '../../courses/'.$_course['directory']."/temp/".$LPnamesafe;
-		$zipfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/temp/".$LPnamesafe;
-		$scormfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/scorm/".$LPnamesafe;
-		$zipfilename = $zipfoldername."/".$LPnamesafe.".zip";
+	/**
+	 * Sets the content maker setting in the database
+	 * @param	string	Proximity setting
+	 */
+	 function set_maker($maker=''){
+		if($this->debug>0){error_log('In scorm::set_maker method('.$maker.')',0);}
+	 	$lp = $this->get_id();
+	 	if($lp!=0){
+	 		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+	 		$sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE id = ".$lp;
+	 		$res = Database::query($sql);
+	 		return $res;
+	 	}else{
+	 		return false;
+	 	}
+	 }
+	 /**
+	  * Exports the current SCORM object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
+	  * @param	integer	Learnpath ID (optional, taken from object context if not defined)
+	  */
+	  function export_zip($lp_id=null){
+		if($this->debug>0){error_log('In scorm::export_zip method('.$lp_id.')',0);}
+	 	if(empty($lp_id)){
+			if(!is_object($this))
+			{
+				return false;
+			}
+			else{
+				$id = $this->get_id();
+				if(empty($id)){
+					return false;
+				}
+	 			else{
+	 				$lp_id = $this->get_id();
+	 			}
+			}
+	 	}
+	 	//error_log('New LP - in export_zip()',0);
+	 	//zip everything that is in the corresponding scorm dir
+	 	//write the zip file somewhere (might be too big to return)
+		require_once (api_get_path(LIBRARY_PATH)."fileUpload.lib.php");
+		require_once (api_get_path(LIBRARY_PATH)."fileManage.lib.php");
+		require_once (api_get_path(LIBRARY_PATH)."document.lib.php");
+		require_once (api_get_path(LIBRARY_PATH)."pclzip/pclzip.lib.php");
+		require_once ("learnpath_functions.inc.php");
+		$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+		$_course = Database::get_course_info(api_get_course_id());
+
+		$sql = "SELECT * FROM $tbl_lp WHERE id=".$lp_id;
+		$result = Database::query($sql, __FILE__, __LINE__);
+		$row = mysql_fetch_array($result);
+		$LPname = $row['path'];
+		$list = split('/',$LPname);
+		$LPnamesafe = $list[0];
+		//$zipfoldername = '/tmp';
+		//$zipfoldername = '../../courses/'.$_course['directory']."/temp/".$LPnamesafe;
+		$zipfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/temp/".$LPnamesafe;
+		$scormfoldername = api_get_path('SYS_COURSE_PATH').$_course['directory']."/scorm/".$LPnamesafe;
+		$zipfilename = $zipfoldername."/".$LPnamesafe.".zip";
 
 		//Get a temporary dir for creating the zip file
 
-		//error_log('New LP - cleaning dir '.$zipfoldername,0);
-		deldir($zipfoldername); //make sure the temp dir is cleared
-		$res = mkdir($zipfoldername);
-		//error_log('New LP - made dir '.$zipfoldername,0);
+		//error_log('New LP - cleaning dir '.$zipfoldername,0);
+		deldir($zipfoldername); //make sure the temp dir is cleared
+		$res = mkdir($zipfoldername);
+		//error_log('New LP - made dir '.$zipfoldername,0);
+
+		//create zipfile of given directory
+		$zip_folder = new PclZip($zipfilename);
+		$zip_folder->create($scormfoldername.'/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername.'/');
 
-		//create zipfile of given directory
-		$zip_folder = new PclZip($zipfilename);
-		$zip_folder->create($scormfoldername.'/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername.'/');
+		//$zipfilename = '/var/www/dokeos-comp/courses/TEST2/scorm/example_document.html';
+		//this file sending implies removing the default mime-type from php.ini
+		//DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.".zip");
+		DocumentManager :: file_send_for_download($zipfilename, true);
 
-		//$zipfilename = '/var/www/dokeos-comp/courses/TEST2/scorm/example_document.html';
-		//this file sending implies removing the default mime-type from php.ini
-		//DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.".zip");
-		DocumentManager :: file_send_for_download($zipfilename, true);
-
-		// Delete the temporary zip file and directory in fileManage.lib.php
-		my_delete($zipfilename);
-		my_delete($zipfoldername);
+		// Delete the temporary zip file and directory in fileManage.lib.php
+		my_delete($zipfilename);
+		my_delete($zipfoldername);
 
-		return true;
+		return true;
 	}
-	/**
-	  * Gets a resource's path if available, otherwise return empty string
-	  * @param	string	Resource ID as used in resource array
-	  * @return string	The resource's path as declared in imsmanifest.xml
-	  */
-	  function get_res_path($id){
-		if($this->debug>0){error_log('In scorm::get_res_path('.$id.') method',0);}
-	  	$path = '';
-	  	if(isset($this->resources[$id])){
-			$oRes =& $this->resources[$id];
-			$path = @$oRes->get_path();
-		}
-		return $path;
-	  }
-	 /**
-	  * Gets a resource's type if available, otherwise return empty string
-	  * @param	string	Resource ID as used in resource array
-	  * @return string	The resource's type as declared in imsmanifest.xml
-	  */
-	  function get_res_type($id){
-		if($this->debug>0){error_log('In scorm::get_res_type('.$id.') method',0);}
-	  	$type = '';
-		if(isset($this->resources[$id])){
-			$oRes =& $this->resources[$id];
-			$temptype = $oRes->get_scorm_type();
-			if(!empty($temptype)){
-				$type = $temptype;
-			}
-		}
-		return $type;
-	  }
-	  /**
-	   * Gets the default organisation's title
-	   * @return	string	The organization's title
-	   */
-	  function get_title(){
-		if($this->debug>0){error_log('In scorm::get_title() method',0);}
-	  	$title = '';
-	  	if(isset($this->manifest['organizations']['default'])){
-	  		$title = $this->organizations[$this->manifest['organizations']['default']]->get_name();
-	  	}elseif(count($this->organizations)==1){
-	  		//this will only get one title but so we don't need to know the index
-	  		foreach($this->organizations as $id => $value){
-	  			$title = $this->organizations[$id]->get_name();
-	  			break;
-	  		}
-	  	}
-	  	return $title;
-	  }
-	  /**
-	   * //TODO @TODO implement this function to restore items data from an imsmanifest,
-	   * updating the existing table... This will prove very useful in case initial data
-	   * from imsmanifest were not imported well enough
-	   * @param	string	course Code
-	   * @param string	LP ID (in database)
-	   * @param string	Manifest file path (optional if lp_id defined)
-	   * @return	integer	New LP ID or false on failure
-	   * TODO @TODO Implement imsmanifest_path parameter
-	   */
-	  function reimport_manifest($course,$lp_id=null,$imsmanifest_path=''){
-		if($this->debug>0){error_log('In scorm::reimport_manifest() method',0);}
-		global $_course;
-		//RECOVERING PATH FROM DB
-		$main_table = Database::get_main_table(TABLE_MAIN_COURSE);
-		//$course = Database::escape_string($course);
-		$course = $this->escape_string($course);
-		$sql = "SELECT * FROM $main_table WHERE code = '$course'";
-		if($this->debug>2){error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying course: '.$sql,0);}
-		//$res = Database::query($sql);
-		$res = Database::query($sql);
-		if(Database::num_rows($res)>0)
-		{
-			$this->cc = $course;
-		}
-		else
-		{
-			$this->error = 'Course code does not exist in database ('.$sql.')';
-			return false;
-   		}
+	/**
+	  * Gets a resource's path if available, otherwise return empty string
+	  * @param	string	Resource ID as used in resource array
+	  * @return string	The resource's path as declared in imsmanifest.xml
+	  */
+	  function get_res_path($id){
+		if($this->debug>0){error_log('In scorm::get_res_path('.$id.') method',0);}
+	  	$path = '';
+	  	if(isset($this->resources[$id])){
+			$oRes =& $this->resources[$id];
+			$path = @$oRes->get_path();
+		}
+		return $path;
+	  }
+	 /**
+	  * Gets a resource's type if available, otherwise return empty string
+	  * @param	string	Resource ID as used in resource array
+	  * @return string	The resource's type as declared in imsmanifest.xml
+	  */
+	  function get_res_type($id){
+		if($this->debug>0){error_log('In scorm::get_res_type('.$id.') method',0);}
+	  	$type = '';
+		if(isset($this->resources[$id])){
+			$oRes =& $this->resources[$id];
+			$temptype = $oRes->get_scorm_type();
+			if(!empty($temptype)){
+				$type = $temptype;
+			}
+		}
+		return $type;
+	  }
+	  /**
+	   * Gets the default organisation's title
+	   * @return	string	The organization's title
+	   */
+	  function get_title(){
+		if($this->debug>0){error_log('In scorm::get_title() method',0);}
+	  	$title = '';
+	  	if(isset($this->manifest['organizations']['default'])){
+	  		$title = $this->organizations[$this->manifest['organizations']['default']]->get_name();
+	  	}elseif(count($this->organizations)==1){
+	  		//this will only get one title but so we don't need to know the index
+	  		foreach($this->organizations as $id => $value){
+	  			$title = $this->organizations[$id]->get_name();
+	  			break;
+	  		}
+	  	}
+	  	return $title;
+	  }
+	  /**
+	   * //TODO @TODO implement this function to restore items data from an imsmanifest,
+	   * updating the existing table... This will prove very useful in case initial data
+	   * from imsmanifest were not imported well enough
+	   * @param	string	course Code
+	   * @param string	LP ID (in database)
+	   * @param string	Manifest file path (optional if lp_id defined)
+	   * @return	integer	New LP ID or false on failure
+	   * TODO @TODO Implement imsmanifest_path parameter
+	   */
+	  function reimport_manifest($course,$lp_id=null,$imsmanifest_path=''){
+		if($this->debug>0){error_log('In scorm::reimport_manifest() method',0);}
+		global $_course;
+		//RECOVERING PATH FROM DB
+		$main_table = Database::get_main_table(TABLE_MAIN_COURSE);
+		//$course = Database::escape_string($course);
+		$course = $this->escape_string($course);
+		$sql = "SELECT * FROM $main_table WHERE code = '$course'";
+		if($this->debug>2){error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying course: '.$sql,0);}
+		//$res = Database::query($sql);
+		$res = Database::query($sql);
+		if(Database::num_rows($res)>0)
+		{
+			$this->cc = $course;
+		}
+		else
+		{
+			$this->error = 'Course code does not exist in database ('.$sql.')';
+			return false;
+   		}
+
+   		//TODO make it flexible to use any course_code (still using env course code here)
+		//$lp_table = Database::get_course_table(LEARNPATH_TABLE);
+    	$lp_table = Database::get_course_table(TABLE_LP_MAIN);
 
-   		//TODO make it flexible to use any course_code (still using env course code here)
-		//$lp_table = Database::get_course_table(LEARNPATH_TABLE);
-    	$lp_table = Database::get_course_table(TABLE_LP_MAIN);
-
-		//$id = Database::escape_integer($id);
-		$lp_id = $this->escape_string($lp_id);
-		$sql = "SELECT * FROM $lp_table WHERE id = '$lp_id'";
-		if($this->debug>2){error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying lp: '.$sql,0);}
-		//$res = Database::query($sql);
-		$res = Database::query($sql);
-		if(Database::num_rows($res)>0)
-		{
-    			$this->lp_id = $lp_id;
-    			$row = Database::fetch_array($res);
-    			$this->type = $row['lp_type'];
-    			$this->name = stripslashes($row['name']);
-    			$this->encoding = $row['default_encoding'];
-    			$this->proximity = $row['content_local'];
-    			$this->maker = $row['content_maker'];
-    			$this->prevent_reinit = $row['prevent_reinit'];
-    			$this->license = $row['content_license'];
-    			$this->scorm_debug = $row['debug'];
-	   			$this->js_lib = $row['js_lib'];
-	   			$this->path = $row['path'];
-	   			if($this->type == 2){
-    				if($row['force_commit'] == 1){
-    					$this->force_commit = true;
-    				}
-    			}
-    			$this->mode = $row['default_view_mod'];
-				$this->subdir = $row['path'];
-		}
-	  	//parse the manifest (it is already in this lp's details)
-	  	$manifest_file = api_get_path('SYS_COURSE_PATH').$_course['directory'].'/scorm/'.$this->subdir.'/imsmanifest.xml';
-	  	if($this->subdir == ''){
-	  		$manifest_file = api_get_path('SYS_COURSE_PATH').$_course['directory'].'/scorm/imsmanifest.xml';
-	  	}
-	  	echo $manifest_file;
-	  	if(is_file($manifest_file) && is_readable($manifest_file)){
-		  	//re-parse the manifest file
-	  		if($this->debug>1){error_log('New LP - In scorm::reimport_manifest() - Parsing manifest '.$manifest_file,0);}
-			$manifest = $this->parse_manifest($manifest_file);
-		  	//import new LP in DB (ignore the current one)
-	  		if($this->debug>1){error_log('New LP - In scorm::reimport_manifest() - Importing manifest '.$manifest_file,0);}
-			$this->import_manifest(api_get_course_id());
-	  	}else{
-	  		if($this->debug>0){error_log('New LP - In scorm::reimport_manifest() - Could not find manifest file at '.$manifest_file,0);}
+		//$id = Database::escape_integer($id);
+		$lp_id = $this->escape_string($lp_id);
+		$sql = "SELECT * FROM $lp_table WHERE id = '$lp_id'";
+		if($this->debug>2){error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying lp: '.$sql,0);}
+		//$res = Database::query($sql);
+		$res = Database::query($sql);
+		if(Database::num_rows($res)>0)
+		{
+    			$this->lp_id = $lp_id;
+    			$row = Database::fetch_array($res);
+    			$this->type = $row['lp_type'];
+    			$this->name = stripslashes($row['name']);
+    			$this->encoding = $row['default_encoding'];
+    			$this->proximity = $row['content_local'];
+    			$this->maker = $row['content_maker'];
+    			$this->prevent_reinit = $row['prevent_reinit'];
+    			$this->license = $row['content_license'];
+    			$this->scorm_debug = $row['debug'];
+	   			$this->js_lib = $row['js_lib'];
+	   			$this->path = $row['path'];
+	   			if($this->type == 2){
+    				if($row['force_commit'] == 1){
+    					$this->force_commit = true;
+    				}
+    			}
+    			$this->mode = $row['default_view_mod'];
+				$this->subdir = $row['path'];
+		}
+	  	//parse the manifest (it is already in this lp's details)
+	  	$manifest_file = api_get_path('SYS_COURSE_PATH').$_course['directory'].'/scorm/'.$this->subdir.'/imsmanifest.xml';
+	  	if($this->subdir == ''){
+	  		$manifest_file = api_get_path('SYS_COURSE_PATH').$_course['directory'].'/scorm/imsmanifest.xml';
+	  	}
+	  	echo $manifest_file;
+	  	if(is_file($manifest_file) && is_readable($manifest_file)){
+		  	//re-parse the manifest file
+	  		if($this->debug>1){error_log('New LP - In scorm::reimport_manifest() - Parsing manifest '.$manifest_file,0);}
+			$manifest = $this->parse_manifest($manifest_file);
+		  	//import new LP in DB (ignore the current one)
+	  		if($this->debug>1){error_log('New LP - In scorm::reimport_manifest() - Importing manifest '.$manifest_file,0);}
+			$this->import_manifest(api_get_course_id());
+	  	}else{
+	  		if($this->debug>0){error_log('New LP - In scorm::reimport_manifest() - Could not find manifest file at '.$manifest_file,0);}
 	  	}
-	  	return false;
-	  }
-}
+	  	return false;
+	  }
+}
 ?>

+ 191 - 191
main/newscorm/scorm.lib.php

@@ -1,191 +1,191 @@
-<?php //$id:$
-//TODO migrate this into the scorm.class.php file
-/*
-==============================================================================
-        Dokeos - elearning and course management software
-
-        Copyright (c) 2004 Dokeos S.A.
-        Copyright (c) 2004 Denes Nagy
-        Copyright (c) 2003 Ghent University (UGent)
-        Copyright (c) 2001 Universite catholique de Louvain (UCL)
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-        This program is free software; you can redistribute it and/or
-        modify it under the terms of the GNU General Public License
-        as published by the Free Software Foundation; either version 2
-        of the License, or (at your option) any later version.
-										        See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium,
-							info@dokeos.com
-=============================================================================
-*/
-/**
-=============================================================================
- * This file is a container for functions related to SCORM and other
- * standard or common course content types. It might later become a class
- * instead of a functions library, as several components are likely to be
- * re-used for different content types.
- * @package dokeos.learnpath.scorm
- * @author Yannick Warnier <ywarnier@beeznest.org>
- * @author Based on work from Denes NAgy, Isthvan Mandak and Roan Embrechts
-=============================================================================
- */
-/**
- * Delete a scorm directory (check for imsmanifest and if found, deletes the related rows in scorm tables also)
- * @param               string          Dir path
- * @return      boolean True on success, false otherwise
- */
-function removescormDir($dir)
-{
-  global $_course;
-  if(!@$opendir = opendir($dir))
-  {
-    return false;
-  }
-  while($readdir = readdir($opendir))
-  {
-    if($readdir != '..' && $readdir != '.')
-    {
-      if(is_file($dir.'/'.$readdir))
-      {
-        $pos=strpos('/'.$readdir, 'imsmanifest.xml');
-        if ($pos) {  //so we have the imsmanifest in this dir
-                     //from d:/myworks/dokeos/dokeos_cvs/dokeos/dokeos/courses/CVSCODE4/scorm/LP2/LP2
-                    //we have to get /LP2/LP2
-          $path=api_get_path('SYS_COURSE_PATH').$_course['official_code'].'/scorm';
-          $pos=strpos($dir,$path);
-          if ($pos==0) {
-            $scormdir=substr($dir,strlen($path),strlen($dir)-strlen($path));
-            $courseid=$_course['official_code'];
-            $sql="SELECT * FROM ".Database::get_scorm_table(TABLE_SCORM_MAIN)." where (contentTitle='$scormdir' and dokeosCourse='$courseid')";
-            $result=Database::query($sql,__FILE__,__LINE__);
-            while ($row=mysql_fetch_array($result))
-            {
-	      $c=$row['contentId'];
-	      $sql2="DELETE FROM ".Database::get_scorm_table(TABLE_SCORM_SCO_DATA)." where contentId=$c";
-	      $result2=Database::query($sql2,__FILE__,__LINE__);
-	    }
-	    $sql="DELETE FROM ".Database::get_scorm_table(TABLE_SCORM_MAIN)." where (contentTitle='$scormdir' and dokeosCourse='$courseid')";
-	    $result=Database::query($sql,__FILE__,__LINE__);
-	  }
-	}
-	if(!@unlink($dir.'/'.$readdir))
-	{
-	  return false;
-	}
-      } elseif(is_dir($dir.'/'.$readdir)) {
-        if(!removescormDir($dir.'/'.$readdir))
-        {
-	  return false;
-	}
-      }
-    }
-  }
-  closedir($opendir);
-  if(!@rmdir($dir)) {
-    return false;
-  }
-  return true;
-}
-/**
- * This function removes a directory if it exists
- * @param               string          Dir path
- * @return      boolean True on success, false otherwise
- * @uses        removescormDir()        to actually remove the directory
- */
-function scorm_delete($file)
-{
-  if ( check_name_exist($file) )
-  {
-    if ( is_dir($file) )
-    {
-      return removescormDir($file);
-    }
-  }
-  else
-  {
-    return false; // no file or directory to delete
-  }
-}
-/**
- * This function gets a list of scorm paths located in a given directory
- * @param	string	Base directory path
- * @param	string	Current directory
- * @param	array	Reference to a list of paths that exist in the database
- * @return	array	Array(type=>array(),size=>array(),date=>array())
- */
-function get_scorm_paths_from_dir($basedir, $curdir, &$attribute){
-	$scormcontent=false;
-	$saved_dir = getcwd();
-	$res = @chdir (realpath($basedir.$curdir));
-	if($res === false){ return(null);}
-	$handle = opendir(".");
-
-	define('A_DIRECTORY', 1);
-	define('A_FILE',      2);
-
-	$fileList = array();
-	// fill up $fileList for displaying the files list later on
-	while ($file = readdir($handle))
-	{
-		if ($file == "." || $file == ".." || $file == '.htaccess')
-		{
-			continue;						// Skip current and parent directories
-		}
-
-		$fileList['name'][] = $file;
-
-		//if ($file=='imsmanifest.xml') { $scormcontent=true; }
-
-		if(is_dir($file))
-		{
-			$fileList['type'][] = A_DIRECTORY;
-			$fileList['size'][] = false;
-			$fileList['date'][] = false;
-		}
-		elseif(is_file($file))
-		{
-			$fileList['type'][] = A_FILE;
-			$fileList['size'][] = filesize($file);
-			$fileList['date'][] = filectime($file);
-		}
-		/*
-		 * Make the correspondance between
-		 * info given by the file system
-		 * and info given by the DB
-		 */
-		if (is_array($attribute) && count($attribute['path'])>0)
-		{
-			$keyAttribute = array_search($curdir."/".$file, $attribute['path']);
-		}
-
-		if ($keyAttribute !== false)
-		{
-			$fileList['comment'   ][] = $attribute['comment'   ][$keyAttribute];
-			$fileList['visibility'][] = $attribute['visibility'][$keyAttribute];
-			unset ($attribute['comment'   ][$keyAttribute],
-			  $attribute['visibility'][$keyAttribute],
-			  $attribute['path'      ][$keyAttribute]);
-		}
-		else
-		{
-			$fileList['comment'   ][] = false;
-			$fileList['visibility'][] = false;
-		}
-	}
-	closedir($handle);
-	chdir($saved_dir);
-	return $fileList;
-}
-/**
- * Detects the SCORM version from an imsmanifest.xml file
- * @param	string	Path to imsmanifest.xml
- * @return	string	SCORM version (1.0,1.1,1.2,1.3)
- * @todo Implement this function
- */
-function get_scorm_version($path){
-	return '1.2';
-}
-?>
+<?php //$id:$
+//TODO migrate this into the scorm.class.php file
+/*
+==============================================================================
+        Dokeos - elearning and course management software
+
+        Copyright (c) 2004 Dokeos S.A.
+        Copyright (c) 2004 Denes Nagy
+        Copyright (c) 2003 Ghent University (UGent)
+        Copyright (c) 2001 Universite catholique de Louvain (UCL)
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+        This program is free software; you can redistribute it and/or
+        modify it under the terms of the GNU General Public License
+        as published by the Free Software Foundation; either version 2
+        of the License, or (at your option) any later version.
+										        See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium,
+							info@dokeos.com
+=============================================================================
+*/
+/**
+=============================================================================
+ * This file is a container for functions related to SCORM and other
+ * standard or common course content types. It might later become a class
+ * instead of a functions library, as several components are likely to be
+ * re-used for different content types.
+ * @package dokeos.learnpath.scorm
+ * @author Yannick Warnier <ywarnier@beeznest.org>
+ * @author Based on work from Denes NAgy, Isthvan Mandak and Roan Embrechts
+=============================================================================
+ */
+/**
+ * Delete a scorm directory (check for imsmanifest and if found, deletes the related rows in scorm tables also)
+ * @param               string          Dir path
+ * @return      boolean True on success, false otherwise
+ */
+function removescormDir($dir)
+{
+  global $_course;
+  if(!@$opendir = opendir($dir))
+  {
+    return false;
+  }
+  while($readdir = readdir($opendir))
+  {
+    if($readdir != '..' && $readdir != '.')
+    {
+      if(is_file($dir.'/'.$readdir))
+      {
+        $pos=strpos('/'.$readdir, 'imsmanifest.xml');
+        if ($pos) {  //so we have the imsmanifest in this dir
+                     //from d:/myworks/dokeos/dokeos_cvs/dokeos/dokeos/courses/CVSCODE4/scorm/LP2/LP2
+                    //we have to get /LP2/LP2
+          $path=api_get_path('SYS_COURSE_PATH').$_course['official_code'].'/scorm';
+          $pos=strpos($dir,$path);
+          if ($pos==0) {
+            $scormdir=substr($dir,strlen($path),strlen($dir)-strlen($path));
+            $courseid=$_course['official_code'];
+            $sql="SELECT * FROM ".Database::get_scorm_table(TABLE_SCORM_MAIN)." where (contentTitle='$scormdir' and dokeosCourse='$courseid')";
+            $result=Database::query($sql,__FILE__,__LINE__);
+            while ($row=mysql_fetch_array($result))
+            {
+	      $c=$row['contentId'];
+	      $sql2="DELETE FROM ".Database::get_scorm_table(TABLE_SCORM_SCO_DATA)." where contentId=$c";
+	      $result2=Database::query($sql2,__FILE__,__LINE__);
+	    }
+	    $sql="DELETE FROM ".Database::get_scorm_table(TABLE_SCORM_MAIN)." where (contentTitle='$scormdir' and dokeosCourse='$courseid')";
+	    $result=Database::query($sql,__FILE__,__LINE__);
+	  }
+	}
+	if(!@unlink($dir.'/'.$readdir))
+	{
+	  return false;
+	}
+      } elseif(is_dir($dir.'/'.$readdir)) {
+        if(!removescormDir($dir.'/'.$readdir))
+        {
+	  return false;
+	}
+      }
+    }
+  }
+  closedir($opendir);
+  if(!@rmdir($dir)) {
+    return false;
+  }
+  return true;
+}
+/**
+ * This function removes a directory if it exists
+ * @param               string          Dir path
+ * @return      boolean True on success, false otherwise
+ * @uses        removescormDir()        to actually remove the directory
+ */
+function scorm_delete($file)
+{
+  if ( check_name_exist($file) )
+  {
+    if ( is_dir($file) )
+    {
+      return removescormDir($file);
+    }
+  }
+  else
+  {
+    return false; // no file or directory to delete
+  }
+}
+/**
+ * This function gets a list of scorm paths located in a given directory
+ * @param	string	Base directory path
+ * @param	string	Current directory
+ * @param	array	Reference to a list of paths that exist in the database
+ * @return	array	Array(type=>array(),size=>array(),date=>array())
+ */
+function get_scorm_paths_from_dir($basedir, $curdir, &$attribute){
+	$scormcontent=false;
+	$saved_dir = getcwd();
+	$res = @chdir (realpath($basedir.$curdir));
+	if($res === false){ return(null);}
+	$handle = opendir(".");
+
+	define('A_DIRECTORY', 1);
+	define('A_FILE',      2);
+
+	$fileList = array();
+	// fill up $fileList for displaying the files list later on
+	while ($file = readdir($handle))
+	{
+		if ($file == "." || $file == ".." || $file == '.htaccess')
+		{
+			continue;						// Skip current and parent directories
+		}
+
+		$fileList['name'][] = $file;
+
+		//if ($file=='imsmanifest.xml') { $scormcontent=true; }
+
+		if(is_dir($file))
+		{
+			$fileList['type'][] = A_DIRECTORY;
+			$fileList['size'][] = false;
+			$fileList['date'][] = false;
+		}
+		elseif(is_file($file))
+		{
+			$fileList['type'][] = A_FILE;
+			$fileList['size'][] = filesize($file);
+			$fileList['date'][] = filectime($file);
+		}
+		/*
+		 * Make the correspondance between
+		 * info given by the file system
+		 * and info given by the DB
+		 */
+		if (is_array($attribute) && count($attribute['path'])>0)
+		{
+			$keyAttribute = array_search($curdir."/".$file, $attribute['path']);
+		}
+
+		if ($keyAttribute !== false)
+		{
+			$fileList['comment'   ][] = $attribute['comment'   ][$keyAttribute];
+			$fileList['visibility'][] = $attribute['visibility'][$keyAttribute];
+			unset ($attribute['comment'   ][$keyAttribute],
+			  $attribute['visibility'][$keyAttribute],
+			  $attribute['path'      ][$keyAttribute]);
+		}
+		else
+		{
+			$fileList['comment'   ][] = false;
+			$fileList['visibility'][] = false;
+		}
+	}
+	closedir($handle);
+	chdir($saved_dir);
+	return $fileList;
+}
+/**
+ * Detects the SCORM version from an imsmanifest.xml file
+ * @param	string	Path to imsmanifest.xml
+ * @return	string	SCORM version (1.0,1.1,1.2,1.3)
+ * @todo Implement this function
+ */
+function get_scorm_version($path){
+	return '1.2';
+}
+?>

+ 302 - 302
main/newscorm/scormItem.class.php

@@ -1,309 +1,309 @@
-<?php //$id:$
-/**
- * Container for the scormItem class that deals with <item> elements in an imsmanifest file
- * @package	dokeos.learnpath.scorm
- * @author	Yannick Warnier	<ywarnier@beeznest.org>
- */
-/**
- * This class handles the <item> elements from an imsmanifest file.
- */
-require_once('learnpathItem.class.php');
-class scormItem extends learnpathItem{
-	var $identifier = '';
-	var $identifierref = '';
-	var $isvisible = '';
-	var $parameters = '';
-	var $title = '';
-	var $sub_items = array();
-	var $metadata;
-	//var $prerequisites = ''; - defined in learnpathItem.class.php
-	var $max_time_allowed = ''; //should be something like HHHH:MM:SS.SS
-	var $timelimitaction = '';
-	var $datafromlms = '';
-	var $mastery_score = '';
-	var $scorm_contact;
+<?php //$id:$
+/**
+ * Container for the scormItem class that deals with <item> elements in an imsmanifest file
+ * @package	dokeos.learnpath.scorm
+ * @author	Yannick Warnier	<ywarnier@beeznest.org>
+ */
+/**
+ * This class handles the <item> elements from an imsmanifest file.
+ */
+require_once('learnpathItem.class.php');
+class scormItem extends learnpathItem{
+	var $identifier = '';
+	var $identifierref = '';
+	var $isvisible = '';
+	var $parameters = '';
+	var $title = '';
+	var $sub_items = array();
+	var $metadata;
+	//var $prerequisites = ''; - defined in learnpathItem.class.php
+	var $max_time_allowed = ''; //should be something like HHHH:MM:SS.SS
+	var $timelimitaction = '';
+	var $datafromlms = '';
+	var $mastery_score = '';
+	var $scorm_contact;
 
-    /**
-     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormItem
-     * object from database records or from the DOM element given as parameter
-     * @param	string	Type of construction needed ('db' or 'manifest', default = 'manifest')
-     * @param	mixed	Depending on the type given, DB id for the lp_item or reference to the DOM element
-     */
-    function scormItem($type='manifest',&$element) {
-    	if(isset($element))
-    	{
-
-			$v = substr(phpversion(),0,1);
-			if($v == 4){
-	    		switch($type){
-	    			case 'db':
-	    				parent::learnpathItem($element,api_get_user_id());
-	    				$this->scorm_contact = false;
-	    				//TODO implement this way of metadata object creation
-	    				return false;
-	    			case 'manifest': //do the same as the default
-	    			default:
-				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
-				     	$children = $element->children();
-				    	foreach($children as $a => $dummy)
-				     	{
-				     		$child =& $children[$a];
-				     		switch($child->type)
-				     		{
-				     			case XML_ELEMENT_NODE:
-									switch($child->tagname){
-				     					case 'title':
-						     				$tmp_children = $child->children();
-						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
-						     				{
-						     					$this->title = $tmp_children[0]->content;
-						     				}
-						     				break;
-				     					case 'maxtimeallowed':
-						     				$tmp_children = $child->children();
-						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
-						     				{
-						     					$this->max_time_allowed = $tmp_children[0]->content;
-						     				}
-						     				break;
-										case 'prerequisites':
-						     				$tmp_children = $child->children();
-						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
-						     				{
-						     					$this->prereq_string = $tmp_children[0]->content;
-						     				}
-						     				break;
-										case 'timelimitaction':
-						     				$tmp_children = $child->children();
-						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
-						     				{
-						     					$this->timelimitaction = $tmp_children[0]->content;
-						     				}
-						     				break;
-										case 'datafromlms':
-						     				$tmp_children = $child->children();
-						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
-						     				{
-						     					$this->datafromlms = $tmp_children[0]->content;
-						     				}
-						     				break;
-										case 'masteryscore':
-						     				$tmp_children = $child->children();
-						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
-						     				{
-						     					$this->mastery_score = $tmp_children[0]->content;
-						     				}
-						     				break;
-				     					case 'item':
-				     						$oItem = new scormItem('manifest',$child);
-				     						if($oItem->identifier != ''){
-				     							$this->sub_items[$oItem->identifier] = $oItem;
-				     						}
-											break;
-				     					case 'metadata':
-				     						$this->metadata = new scormMetadata('manifest',$child);
-				     						break;
-				     				}
-				     				break;
-				     			case XML_TEXT_NODE:
-				     				//this case is actually treated by looking into ELEMENT_NODEs above
-				     				break;
-				     		}
-				     	}
-				     	$attributes = $element->attributes();
-				     	//$keep_href = '';
-				     	foreach($attributes as $a1 => $dummy)
-				     	{
-				     		$attrib =& $attributes[$a1];
-				     		switch($attrib->name){
-				     			case 'identifier':
-				     				$this->identifier = $attrib->value;
-				     				break;
-				     			case 'identifierref':
-				     				$this->identifierref = $attrib->value;
-				     				break;
-				     			case 'isvisible':
-				     				$this->isvisible = $attrib->value;
-				     				break;
-				     			case 'parameters':
-				     				$this->parameters = $attrib->value;
-				     				break;
-				     		}
-				     	}
-						return true;
+    /**
+     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormItem
+     * object from database records or from the DOM element given as parameter
+     * @param	string	Type of construction needed ('db' or 'manifest', default = 'manifest')
+     * @param	mixed	Depending on the type given, DB id for the lp_item or reference to the DOM element
+     */
+    function scormItem($type='manifest',&$element) {
+    	if(isset($element))
+    	{
 
-	    		}
-	    	}elseif($v == 5){
-	    		//parsing using PHP5 DOMXML methods
-	    		switch($type){
-	    			case 'db':
-	    				parent::learnpathItem($element,api_get_user_id());
-	    				$this->scorm_contact = false;
-	    				//TODO implement this way of metadata object creation
-	    				return false;
-	    			case 'manifest': //do the same as the default
-	    			default:
-				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
-				     	$children = $element->childNodes;
-				    	foreach($children as $child)
-				     	{
-				     		switch($child->nodeType)
-				     		{
-				     			case XML_ELEMENT_NODE:
-									switch($child->tagName){
-				     					case 'title':
-						     				$tmp_children = $child->childNodes;
-						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
-						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
-						     				{
-						     					$this->title = $child->firstChild->nodeValue;
-						     				}
-						     				break;
-						     			case 'max_score':
-					     					if($tmp_children->length==1 and $child->firstChild->nodeValue!='' ) {
-						     					$this->max_score = $child->firstChild->nodeValue;
+			$v = substr(phpversion(),0,1);
+			if($v == 4){
+	    		switch($type){
+	    			case 'db':
+	    				parent::learnpathItem($element,api_get_user_id());
+	    				$this->scorm_contact = false;
+	    				//TODO implement this way of metadata object creation
+	    				return false;
+	    			case 'manifest': //do the same as the default
+	    			default:
+				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
+				     	$children = $element->children();
+				    	foreach($children as $a => $dummy)
+				     	{
+				     		$child =& $children[$a];
+				     		switch($child->type)
+				     		{
+				     			case XML_ELEMENT_NODE:
+									switch($child->tagname){
+				     					case 'title':
+						     				$tmp_children = $child->children();
+						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
+						     				{
+						     					$this->title = $tmp_children[0]->content;
 						     				}
-						     				break;
-				     					case 'maxtimeallowed':
-				     					case 'adlcp:maxtimeallowed':
-						     				$tmp_children = $child->childNodes;
-						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
-						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
-						     				{
-						     					$this->max_time_allowed = $child->firstChild->nodeValue;
-						     				}
-						     				break;
-										case 'prerequisites':
-										case 'adlcp:prerequisites':
-						     				$tmp_children = $child->childNodes;
-						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
-						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
-						     				{
-						     					$this->prereq_string = $child->firstChild->nodeValue;
-						     				}
-						     				break;
-										case 'timelimitaction':
-										case 'adlcp:timelimitaction':
-						     				$tmp_children = $child->childNodes;
-						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
-						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
-						     				{
-						     					$this->timelimitaction = $child->firstChild->nodeValue;
-						     				}
-						     				break;
-										case 'datafromlms':
-										case 'adlcp:datafromlms':
-										case 'adlcp:launchdata': //in some cases (Wouters)
-						     				$tmp_children = $child->childNodes;
-						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
-						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
-						     				{
-						     					$this->datafromlms = $child->firstChild->nodeValue;
-						     				}
-						     				break;
-										case 'masteryscore':
-										case 'adlcp:masteryscore':
-						     				$tmp_children = $child->childNodes;
-						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
-						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
-						     				{
-						     					$this->mastery_score = $child->firstChild->nodeValue;
-						     				}
-						     				break;
-				     					case 'item':
-				     						$oItem = new scormItem('manifest',$child);
-				     						if($oItem->identifier != ''){
-				     							$this->sub_items[$oItem->identifier] = $oItem;
-				     						}
-											break;
-				     					case 'metadata':
-				     						$this->metadata = new scormMetadata('manifest',$child);
-				     						break;
-				     				}
-				     				break;
-				     			case XML_TEXT_NODE:
-				     				//this case is actually treated by looking into ELEMENT_NODEs above
-				     				break;
-				     		}
-				     	}
-				     	if($element->hasAttributes()){
-					     	$attributes = $element->attributes;
-					     	//$keep_href = '';
-					     	foreach($attributes as $attrib)
-					     	{
-					     		switch($attrib->name){
-					     			case 'identifier':
-					     				$this->identifier = $attrib->value;
-					     				break;
-					     			case 'identifierref':
-					     				$this->identifierref = $attrib->value;
-					     				break;
-					     			case 'isvisible':
-					     				$this->isvisible = $attrib->value;
-					     				break;
-					     			case 'parameters':
-					     				$this->parameters = $attrib->value;
-					     				break;
-					     		}
-					     	}
-				     	}
-						return true;
+						     				break;
+				     					case 'maxtimeallowed':
+						     				$tmp_children = $child->children();
+						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
+						     				{
+						     					$this->max_time_allowed = $tmp_children[0]->content;
+						     				}
+						     				break;
+										case 'prerequisites':
+						     				$tmp_children = $child->children();
+						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
+						     				{
+						     					$this->prereq_string = $tmp_children[0]->content;
+						     				}
+						     				break;
+										case 'timelimitaction':
+						     				$tmp_children = $child->children();
+						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
+						     				{
+						     					$this->timelimitaction = $tmp_children[0]->content;
+						     				}
+						     				break;
+										case 'datafromlms':
+						     				$tmp_children = $child->children();
+						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
+						     				{
+						     					$this->datafromlms = $tmp_children[0]->content;
+						     				}
+						     				break;
+										case 'masteryscore':
+						     				$tmp_children = $child->children();
+						     				if(count($tmp_children)==1 and $tmp_children[0]->content!='' )
+						     				{
+						     					$this->mastery_score = $tmp_children[0]->content;
+						     				}
+						     				break;
+				     					case 'item':
+				     						$oItem = new scormItem('manifest',$child);
+				     						if($oItem->identifier != ''){
+				     							$this->sub_items[$oItem->identifier] = $oItem;
+				     						}
+											break;
+				     					case 'metadata':
+				     						$this->metadata = new scormMetadata('manifest',$child);
+				     						break;
+				     				}
+				     				break;
+				     			case XML_TEXT_NODE:
+				     				//this case is actually treated by looking into ELEMENT_NODEs above
+				     				break;
+				     		}
+				     	}
+				     	$attributes = $element->attributes();
+				     	//$keep_href = '';
+				     	foreach($attributes as $a1 => $dummy)
+				     	{
+				     		$attrib =& $attributes[$a1];
+				     		switch($attrib->name){
+				     			case 'identifier':
+				     				$this->identifier = $attrib->value;
+				     				break;
+				     			case 'identifierref':
+				     				$this->identifierref = $attrib->value;
+				     				break;
+				     			case 'isvisible':
+				     				$this->isvisible = $attrib->value;
+				     				break;
+				     			case 'parameters':
+				     				$this->parameters = $attrib->value;
+				     				break;
+				     		}
+				     	}
+						return true;
+
+	    		}
+	    	}elseif($v == 5){
+	    		//parsing using PHP5 DOMXML methods
+	    		switch($type){
+	    			case 'db':
+	    				parent::learnpathItem($element,api_get_user_id());
+	    				$this->scorm_contact = false;
+	    				//TODO implement this way of metadata object creation
+	    				return false;
+	    			case 'manifest': //do the same as the default
+	    			default:
+				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
+				     	$children = $element->childNodes;
+				    	foreach($children as $child)
+				     	{
+				     		switch($child->nodeType)
+				     		{
+				     			case XML_ELEMENT_NODE:
+									switch($child->tagName){
+				     					case 'title':
+						     				$tmp_children = $child->childNodes;
+						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
+						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
+						     				{
+						     					$this->title = $child->firstChild->nodeValue;
+						     				}
+						     				break;
+						     			case 'max_score':
+					     					if($tmp_children->length==1 and $child->firstChild->nodeValue!='' ) {
+						     					$this->max_score = $child->firstChild->nodeValue;
+						     				}
+						     				break;
+				     					case 'maxtimeallowed':
+				     					case 'adlcp:maxtimeallowed':
+						     				$tmp_children = $child->childNodes;
+						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
+						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
+						     				{
+						     					$this->max_time_allowed = $child->firstChild->nodeValue;
+						     				}
+						     				break;
+										case 'prerequisites':
+										case 'adlcp:prerequisites':
+						     				$tmp_children = $child->childNodes;
+						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
+						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
+						     				{
+						     					$this->prereq_string = $child->firstChild->nodeValue;
+						     				}
+						     				break;
+										case 'timelimitaction':
+										case 'adlcp:timelimitaction':
+						     				$tmp_children = $child->childNodes;
+						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
+						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
+						     				{
+						     					$this->timelimitaction = $child->firstChild->nodeValue;
+						     				}
+						     				break;
+										case 'datafromlms':
+										case 'adlcp:datafromlms':
+										case 'adlcp:launchdata': //in some cases (Wouters)
+						     				$tmp_children = $child->childNodes;
+						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
+						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
+						     				{
+						     					$this->datafromlms = $child->firstChild->nodeValue;
+						     				}
+						     				break;
+										case 'masteryscore':
+										case 'adlcp:masteryscore':
+						     				$tmp_children = $child->childNodes;
+						     				//if(count($tmp_children)==1 and $tmp_children[0]->textContent!='' )
+						     				if($tmp_children->length==1 and $child->firstChild->nodeValue!='' )
+						     				{
+						     					$this->mastery_score = $child->firstChild->nodeValue;
+						     				}
+						     				break;
+				     					case 'item':
+				     						$oItem = new scormItem('manifest',$child);
+				     						if($oItem->identifier != ''){
+				     							$this->sub_items[$oItem->identifier] = $oItem;
+				     						}
+											break;
+				     					case 'metadata':
+				     						$this->metadata = new scormMetadata('manifest',$child);
+				     						break;
+				     				}
+				     				break;
+				     			case XML_TEXT_NODE:
+				     				//this case is actually treated by looking into ELEMENT_NODEs above
+				     				break;
+				     		}
+				     	}
+				     	if($element->hasAttributes()){
+					     	$attributes = $element->attributes;
+					     	//$keep_href = '';
+					     	foreach($attributes as $attrib)
+					     	{
+					     		switch($attrib->name){
+					     			case 'identifier':
+					     				$this->identifier = $attrib->value;
+					     				break;
+					     			case 'identifierref':
+					     				$this->identifierref = $attrib->value;
+					     				break;
+					     			case 'isvisible':
+					     				$this->isvisible = $attrib->value;
+					     				break;
+					     			case 'parameters':
+					     				$this->parameters = $attrib->value;
+					     				break;
+					     		}
+					     	}
+				     	}
+						return true;
 
-	    		}
-			}else{
-				//cannot parse because not PHP4 nor PHP5... We should not even be here anyway...
-				return false;
-			}
-    	}
-    	return false;
-    }
-    /**
-     * Builds a flat list with the current item and calls itself recursively on all children
-     * @param	array	Reference to the array to complete with the current item
-     * @param	integer	Optional absolute order (pointer) of the item in this learning path
-     * @param	integer	Optional relative order of the item at this level
-     * @param	integer	Optional level. If not given, assumes it's level 0
-     */
-    function get_flat_list(&$list,&$abs_order,$rel_order=1,$level=0)
-    {
-    	$list[] = array(
-    		'abs_order' => $abs_order,
-			'datafromlms' => $this->datafromlms,
-			'identifier' => $this->identifier,
-			'identifierref' => $this->identifierref,
-			'isvisible' => $this->isvisible,
-			'level' => $level,
-			'masteryscore' => $this->mastery_score,
-			'maxtimeallowed' => $this->max_time_allowed,
-			'metadata' => $this->metadata,
-			'parameters' => $this->parameters,
-			'prerequisites' => (!empty($this->prereq_string)?$this->prereq_string:''),
-			'rel_order' => $rel_order,
-			'timelimitaction' => $this->timelimitaction,
-			'title' => $this->title,
+	    		}
+			}else{
+				//cannot parse because not PHP4 nor PHP5... We should not even be here anyway...
+				return false;
+			}
+    	}
+    	return false;
+    }
+    /**
+     * Builds a flat list with the current item and calls itself recursively on all children
+     * @param	array	Reference to the array to complete with the current item
+     * @param	integer	Optional absolute order (pointer) of the item in this learning path
+     * @param	integer	Optional relative order of the item at this level
+     * @param	integer	Optional level. If not given, assumes it's level 0
+     */
+    function get_flat_list(&$list,&$abs_order,$rel_order=1,$level=0)
+    {
+    	$list[] = array(
+    		'abs_order' => $abs_order,
+			'datafromlms' => $this->datafromlms,
+			'identifier' => $this->identifier,
+			'identifierref' => $this->identifierref,
+			'isvisible' => $this->isvisible,
+			'level' => $level,
+			'masteryscore' => $this->mastery_score,
+			'maxtimeallowed' => $this->max_time_allowed,
+			'metadata' => $this->metadata,
+			'parameters' => $this->parameters,
+			'prerequisites' => (!empty($this->prereq_string)?$this->prereq_string:''),
+			'rel_order' => $rel_order,
+			'timelimitaction' => $this->timelimitaction,
+			'title' => $this->title,
 			'max_score' => $this->max_score
-			);
-		$abs_order++;
-		$i = 1;
-		foreach($this->sub_items as $id => $dummy)
-		{
-			$oSubitem =& $this->sub_items[$id];
-			$oSubitem->get_flat_list($list,$abs_order,$i,$level+1);
-			$i++;
-		}
-    }
-    /**
-     * Save function. Uses the parent save function and adds a layer for SCORM.
-     * @param	boolean	Save from URL params (1) or from object attributes (0)
-     */
-    function save($from_outside=true,$prereqs_complete=false)
-    {
-    	parent::save($from_outside,$prereqs_complete);
-    	//under certain conditions, the scorm_contact should not be set, because no scorm signal was sent
-    	$this->scorm_contact = true;
-    	if(!$this->scorm_contact){
+			);
+		$abs_order++;
+		$i = 1;
+		foreach($this->sub_items as $id => $dummy)
+		{
+			$oSubitem =& $this->sub_items[$id];
+			$oSubitem->get_flat_list($list,$abs_order,$i,$level+1);
+			$i++;
+		}
+    }
+    /**
+     * Save function. Uses the parent save function and adds a layer for SCORM.
+     * @param	boolean	Save from URL params (1) or from object attributes (0)
+     */
+    function save($from_outside=true,$prereqs_complete=false)
+    {
+    	parent::save($from_outside,$prereqs_complete);
+    	//under certain conditions, the scorm_contact should not be set, because no scorm signal was sent
+    	$this->scorm_contact = true;
+    	if(!$this->scorm_contact){
     		//error_log('New LP - was expecting SCORM message but none received',0);
-    	}
-    }
-}
+    	}
+    }
+}
 ?>

+ 200 - 200
main/newscorm/scormMetadata.class.php

@@ -1,203 +1,203 @@
-<?php //$id:$
-/**
- * Container for the scormMetadata class, setup to hold information about the <metadata> element in imsmanifest files
- * @package dokeos.learnpath.scorm
- */
-/**
- * scormMetadata class, handling each <metadata> element found in an imsmanifest file
- */
-class scormMetadata {
-	var	$lom = '';
-	var $schema = '';
-	var $schemaversion = '';
-	var $location = '';
-	var $text = '';
-	var $attribs = array();
-
-	/**
-	 * Class constructor. Works in two different ways defined by the first element, being 'db' or 'manifest'.
-	 * If 'db', then it is built using the information available in the Dokeos database. If 'manifest', then it
-	 * is built using the element given as a parameter, expecting it to be a <metadata> element pointer from the
-	 * DOM parser.
-	 * @param	string	Type of creation required. Can be 'db' or 'manifest' (default)
-	 * @param	mixed	Depending on the type, can be the DB ID of the learnpath item or the pointer to the <metadata> element in the imsmanifest.xml file
-	 * @return	boolean	True on success, false on failure
-	 */
-    function scormMetadata($type='manifest', &$element) {
-    	if(isset($element))
-    	{
-    		$v = substr(phpversion(),0,1);
-			if($v == 4){
-	    		switch($type){
-	    			case 'db':
-	    				//TODO implement this way of metadata object creation
-	    				return false;
-	    				//break;
-	    			case 'manifest': //do the same as the default
-				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
-				     	$children = $element->children();
-				    	foreach($children as $a => $dummy)
-				     	{
-				     		$child =& $children[$a];
-				     		switch($child->type)
-				     		{
-				     			case XML_ELEMENT_NODE:
-									//could be 'lom','schema','schemaversion' or 'location'
-				     				switch($child->tagname){
-				     					case 'lom':
-				     						$childchildren = $child->children();
-				     						foreach($childchildren as $index => $dummy)
-				     						{
-				     							$my_elem = $childchildren[$index];
-				     							//there is generally only one child here
-				     							//$this->lom[] = $my_elem->content;
-				     							$this->lom = $my_elem->content;
-				     						}
-				     						break;
-				     					case 'schema':
-				     						$childchildren = $child->children();
-				     						foreach($childchildren as $index => $dummy)
-				     						{
-				     							$my_elem = $childchildren[$index];
-				     							//there is generally only one child here
-				     							//$this->schema[] = $my_elem->content;
-				     							$this->schema = $my_elem->content;
-				     						}
-				     						break;
-				     					case 'schemaversion':
-				     						$childchildren = $child->children();
-				     						foreach($childchildren as $index => $dummy)
-				     						{
-				     							$my_elem = $childchildren[$index];
-				     							//there is generally only one child here
-				     							//$this->schemaversion[] = $my_elem->content;
-				     							$this->schemaversion = $my_elem->content;
-				     						}
-				     						break;
-				     					case 'location':
-				     						$childchildren = $child->children();
-				     						foreach($childchildren as $index => $dummy)
-				     						{
-				     							$my_elem = $childchildren[$index];
-				     							//there is generally only one child here
-				     							//$this->location[] = $my_elem->content;
-				     							$this->location = $my_elem->content;
-				     						}
-				     						break;
-				     				}
-				     				break;
-				     			case XML_TEXT_NODE:
-				     				if(trim($child->content) != '')
-				     				{
+<?php //$id:$
+/**
+ * Container for the scormMetadata class, setup to hold information about the <metadata> element in imsmanifest files
+ * @package dokeos.learnpath.scorm
+ */
+/**
+ * scormMetadata class, handling each <metadata> element found in an imsmanifest file
+ */
+class scormMetadata {
+	var	$lom = '';
+	var $schema = '';
+	var $schemaversion = '';
+	var $location = '';
+	var $text = '';
+	var $attribs = array();
+
+	/**
+	 * Class constructor. Works in two different ways defined by the first element, being 'db' or 'manifest'.
+	 * If 'db', then it is built using the information available in the Dokeos database. If 'manifest', then it
+	 * is built using the element given as a parameter, expecting it to be a <metadata> element pointer from the
+	 * DOM parser.
+	 * @param	string	Type of creation required. Can be 'db' or 'manifest' (default)
+	 * @param	mixed	Depending on the type, can be the DB ID of the learnpath item or the pointer to the <metadata> element in the imsmanifest.xml file
+	 * @return	boolean	True on success, false on failure
+	 */
+    function scormMetadata($type='manifest', &$element) {
+    	if(isset($element))
+    	{
+    		$v = substr(phpversion(),0,1);
+			if($v == 4){
+	    		switch($type){
+	    			case 'db':
+	    				//TODO implement this way of metadata object creation
+	    				return false;
+	    				//break;
+	    			case 'manifest': //do the same as the default
+				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
+				     	$children = $element->children();
+				    	foreach($children as $a => $dummy)
+				     	{
+				     		$child =& $children[$a];
+				     		switch($child->type)
+				     		{
+				     			case XML_ELEMENT_NODE:
+									//could be 'lom','schema','schemaversion' or 'location'
+				     				switch($child->tagname){
+				     					case 'lom':
+				     						$childchildren = $child->children();
+				     						foreach($childchildren as $index => $dummy)
+				     						{
+				     							$my_elem = $childchildren[$index];
+				     							//there is generally only one child here
+				     							//$this->lom[] = $my_elem->content;
+				     							$this->lom = $my_elem->content;
+				     						}
+				     						break;
+				     					case 'schema':
+				     						$childchildren = $child->children();
+				     						foreach($childchildren as $index => $dummy)
+				     						{
+				     							$my_elem = $childchildren[$index];
+				     							//there is generally only one child here
+				     							//$this->schema[] = $my_elem->content;
+				     							$this->schema = $my_elem->content;
+				     						}
+				     						break;
+				     					case 'schemaversion':
+				     						$childchildren = $child->children();
+				     						foreach($childchildren as $index => $dummy)
+				     						{
+				     							$my_elem = $childchildren[$index];
+				     							//there is generally only one child here
+				     							//$this->schemaversion[] = $my_elem->content;
+				     							$this->schemaversion = $my_elem->content;
+				     						}
+				     						break;
+				     					case 'location':
+				     						$childchildren = $child->children();
+				     						foreach($childchildren as $index => $dummy)
+				     						{
+				     							$my_elem = $childchildren[$index];
+				     							//there is generally only one child here
+				     							//$this->location[] = $my_elem->content;
+				     							$this->location = $my_elem->content;
+				     						}
+				     						break;
+				     				}
+				     				break;
+				     			case XML_TEXT_NODE:
+				     				if(trim($child->content) != '')
+				     				{
 				     					if(count($children == 1)){
-				     						//if this is the only child at this level and it is a content... save differently
-				     						$this->text = $child->content;
-				     					}else{
-				     						$this->text[$element->tagname] = $child->content;
-				     					}
-				     				}
-				     				break;
-				     		}
-				     	}
-				     	$attributes = $element->attributes();
-				     	//$keep_href = '';
-				     	if(is_array($attributes)){
-					     	foreach($attributes as $a1 => $dummy)
-					     	{
-					     		$attrib =& $attributes[$a1];
-					     		if(trim($attrib->value) != ''){
-					     			$this->attribs[$attrib->name] = $attrib->value;
-					     		}
-					     	}
-				     	}
-						return true;
-	    				//break;
-	    		}
-	    	}elseif($v == 5){
-	    		//parsing using PHP5 DOMXML methods
-	    		switch($type){
-	    			case 'db':
-	    				//TODO implement this way of metadata object creation
-	    				return false;
-	    				//break;
-	    			case 'manifest': //do the same as the default
-				     	$children = $element->childNodes;
-				    	foreach($children as $child)
-				     	{
-				     		switch($child->nodeType)
-				     		{
-				     			case XML_ELEMENT_NODE:
-									//could be 'lom','schema','schemaversion' or 'location'
-				     				switch($child->tagName){
-				     					case 'lom':
-				     						$childchildren = $child->childNodes;
-				     						foreach($childchildren as $childchild)
-				     						{
-				     							//$this->lom = $childchild->textContent;
-				     							$this->lom = $childchild->nodeValue;
-				     						}
-				     						break;
-				     					case 'schema':
-				     						$childchildren = $child->childNodes;
-				     						foreach($childchildren as $childchild)
-				     						{
-				     							//there is generally only one child here
-				     							//$this->schema = $childchildren[$index]->textContent;
-				     							$this->schema = $childchild->nodeValue;
-				     						}
-				     						break;
-				     					case 'schemaversion':
-				     						$childchildren = $child->childNodes;
-				     						foreach($childchildren as $childchild)
-				     						{
-				     							//there is generally only one child here
-				     							//$this->schemaversion = $childchildren[$index]->textContent;
-				     							$this->schemaversion = $childchild->nodeValue;
-				     						}
-				     						break;
-				     					case 'location':
-				     						$childchildren = $child->childNodes;
-				     						foreach($childchildren as $childchild)
-				     						{
-				     							//there is generally only one child here
-				     							//$this->location = $childchildren[$index]->textContent;
-				     							$this->location = $childchild->nodeValue;
-				     						}
-				     						break;
-				     				}
-				     				break;
-				     			case XML_TEXT_NODE:
-				     				if(trim($child->textContent) != '')
-				     				{
+				     						//if this is the only child at this level and it is a content... save differently
+				     						$this->text = $child->content;
+				     					}else{
+				     						$this->text[$element->tagname] = $child->content;
+				     					}
+				     				}
+				     				break;
+				     		}
+				     	}
+				     	$attributes = $element->attributes();
+				     	//$keep_href = '';
+				     	if(is_array($attributes)){
+					     	foreach($attributes as $a1 => $dummy)
+					     	{
+					     		$attrib =& $attributes[$a1];
+					     		if(trim($attrib->value) != ''){
+					     			$this->attribs[$attrib->name] = $attrib->value;
+					     		}
+					     	}
+				     	}
+						return true;
+	    				//break;
+	    		}
+	    	}elseif($v == 5){
+	    		//parsing using PHP5 DOMXML methods
+	    		switch($type){
+	    			case 'db':
+	    				//TODO implement this way of metadata object creation
+	    				return false;
+	    				//break;
+	    			case 'manifest': //do the same as the default
+				     	$children = $element->childNodes;
+				    	foreach($children as $child)
+				     	{
+				     		switch($child->nodeType)
+				     		{
+				     			case XML_ELEMENT_NODE:
+									//could be 'lom','schema','schemaversion' or 'location'
+				     				switch($child->tagName){
+				     					case 'lom':
+				     						$childchildren = $child->childNodes;
+				     						foreach($childchildren as $childchild)
+				     						{
+				     							//$this->lom = $childchild->textContent;
+				     							$this->lom = $childchild->nodeValue;
+				     						}
+				     						break;
+				     					case 'schema':
+				     						$childchildren = $child->childNodes;
+				     						foreach($childchildren as $childchild)
+				     						{
+				     							//there is generally only one child here
+				     							//$this->schema = $childchildren[$index]->textContent;
+				     							$this->schema = $childchild->nodeValue;
+				     						}
+				     						break;
+				     					case 'schemaversion':
+				     						$childchildren = $child->childNodes;
+				     						foreach($childchildren as $childchild)
+				     						{
+				     							//there is generally only one child here
+				     							//$this->schemaversion = $childchildren[$index]->textContent;
+				     							$this->schemaversion = $childchild->nodeValue;
+				     						}
+				     						break;
+				     					case 'location':
+				     						$childchildren = $child->childNodes;
+				     						foreach($childchildren as $childchild)
+				     						{
+				     							//there is generally only one child here
+				     							//$this->location = $childchildren[$index]->textContent;
+				     							$this->location = $childchild->nodeValue;
+				     						}
+				     						break;
+				     				}
+				     				break;
+				     			case XML_TEXT_NODE:
+				     				if(trim($child->textContent) != '')
+				     				{
 				     					if(count($children == 1)){
-				     						//if this is the only child at this level and it is a content... save differently
-				     						$this->text = $child->textContent;
-				     					}else{
-				     						$this->text[$element->tagName] = $child->textContent;
-				     					}
-				     				}
-				     				break;
-				     		}
-				     	}
-				     	$attributes = $element->attributes;
-				     	//$keep_href = '';
-				     	if(is_array($attributes)){
-					     	foreach($attributes as $attrib)
-					     	{
-					     		if(trim($attrib->value) != ''){
-					     			$this->attribs[$attrib->name] = $attrib->value;
-					     		}
-					     	}
-				     	}
-						return true;
-	    				//break;
-	    		}
-			}else{
-				//cannot parse because not PHP4 nor PHP5... We should not even be here anyway...
-				return false;
-			}
-    	}
-    	return false;
-    }
-}
+				     						//if this is the only child at this level and it is a content... save differently
+				     						$this->text = $child->textContent;
+				     					}else{
+				     						$this->text[$element->tagName] = $child->textContent;
+				     					}
+				     				}
+				     				break;
+				     		}
+				     	}
+				     	$attributes = $element->attributes;
+				     	//$keep_href = '';
+				     	if(is_array($attributes)){
+					     	foreach($attributes as $attrib)
+					     	{
+					     		if(trim($attrib->value) != ''){
+					     			$this->attribs[$attrib->name] = $attrib->value;
+					     		}
+					     	}
+				     	}
+						return true;
+	    				//break;
+	    		}
+			}else{
+				//cannot parse because not PHP4 nor PHP5... We should not even be here anyway...
+				return false;
+			}
+    	}
+    	return false;
+    }
+}
 ?>

+ 206 - 206
main/newscorm/scormResource.class.php

@@ -1,211 +1,211 @@
-<?php //$id:$
-/**
- * Container for the scormResource class
- * @package dokeos.learnpath.scorm
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- */
-/**
- * Class defining the <resource> tag in an imsmanifest.xml file
+<?php //$id:$
+/**
+ * Container for the scormResource class
+ * @package dokeos.learnpath.scorm
+ * @author	Yannick Warnier <ywarnier@beeznest.org>
+ */
+/**
+ * Class defining the <resource> tag in an imsmanifest.xml file
  *
- */
-class scormResource {
-	var $identifier = '';
-	var $type = 'webcontent';
-	//var $identifierref = '';
-	var $scormtype = 'sco'; //fix problems with ENI content where asset is not defined
-	var $base = '';
-	var $href = '';
-	var $metadata;
-	//var $file_href;
-	//var $file_metadata;
-	var $files = array();
-	var $dependencies = array();
+ */
+class scormResource {
+	var $identifier = '';
+	var $type = 'webcontent';
+	//var $identifierref = '';
+	var $scormtype = 'sco'; //fix problems with ENI content where asset is not defined
+	var $base = '';
+	var $href = '';
+	var $metadata;
+	//var $file_href;
+	//var $file_metadata;
+	var $files = array();
+	var $dependencies = array();
 
-    /**
-     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormResource
-     * object from database records or from the DOM element given as parameter
-     * @param	string	Type of construction needed ('db' or 'manifest', default = 'manifest')
-     * @param	mixed	Depending on the type given, DB id for the lp_item or reference to the DOM element
-     */
-    function scormResource($type='manifest',&$element) {
-    	/*
-    	echo "<pre>Analysing resource:<br />\n";
-    	var_dump($element);
-    	echo "</pre><br />\n";
-    	*/
-    	if(isset($element))
-    	{
-			$v = substr(phpversion(),0,1);
-			if($v == 4){
-	    		switch($type){
-	    			case 'db':
-	    				//TODO implement this way of metadata object creation
-	    				return false;
-	    			case 'manifest': //do the same as the default
-	    			default:
-				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
-				     	$children = $element->children();
-				    	foreach($children as $a => $dummy)
-				     	{
-				     		$child =& $children[$a];
-				     		switch($child->type)
-				     		{
-				     			case XML_ELEMENT_NODE:
-									switch($child->tagname){
-				     					case 'file':
-				     						//echo "Child is a file tag<br />\n";
-				     						$this->files[] = $child->get_attribute('href');
-				     						//var_dump($this->files);
-				     						//ignoring file metadata
-											//files[] array contains all <file href='x'> tags one by one
-											break;
-				     					case 'metadata':
-				     						//echo "Child is a metadata tag<br />\n";
-				     						$this->metadata = new scormMetadata('manifest',$child);
-				     						break;
-				     					case 'dependency':
-				     						//echo "Child is a dependency tag<br />\n";
-				     						//need to get identifierref attribute inside dependency node
-				     						//dependencies[] array represents all <dependency identifierref='x'> tags united
-				     						$this->dependencies[] = $child->get_attribute('identifierref');
-				     						break;
-				     				}
-				     				break;
-				     		}
-				     	}
-				     	$attributes = $element->attributes();
-				     	//$keep_href = '';
-				     	if(count($attributes)>0){ //in some cases we get here with an empty attributes array
-				     	//TODO find when and why we get such a case (empty array)
-					     	foreach($attributes as $a1 => $dummy)
-					     	{
-					     		$attrib =& $attributes[$a1];
-					     		switch($attrib->name){
-					     			case 'identifier':
-					     				$this->identifier = $attrib->value;
-					     				break;
-					     			case 'type':
-					     				if(!empty($attrib->value)){
-					     					$this->type = $attrib->value;
-					     				}
-					     				break;
-					     			case 'scormtype':
-					     				if(!empty($attrib->value)){
-					     					$this->scormtype = $attrib->value;
-					     				}
-					     				break;
-					     			case 'base':
-					     				$this->base = $attrib->value;
-					     				break;
-					     			case 'href':
-					     				$this->href = $attrib->value;
-					     				break;
-					     		}
-					     	}
-				     	}
-						return true;
+    /**
+     * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormResource
+     * object from database records or from the DOM element given as parameter
+     * @param	string	Type of construction needed ('db' or 'manifest', default = 'manifest')
+     * @param	mixed	Depending on the type given, DB id for the lp_item or reference to the DOM element
+     */
+    function scormResource($type='manifest',&$element) {
+    	/*
+    	echo "<pre>Analysing resource:<br />\n";
+    	var_dump($element);
+    	echo "</pre><br />\n";
+    	*/
+    	if(isset($element))
+    	{
+			$v = substr(phpversion(),0,1);
+			if($v == 4){
+	    		switch($type){
+	    			case 'db':
+	    				//TODO implement this way of metadata object creation
+	    				return false;
+	    			case 'manifest': //do the same as the default
+	    			default:
+				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
+				     	$children = $element->children();
+				    	foreach($children as $a => $dummy)
+				     	{
+				     		$child =& $children[$a];
+				     		switch($child->type)
+				     		{
+				     			case XML_ELEMENT_NODE:
+									switch($child->tagname){
+				     					case 'file':
+				     						//echo "Child is a file tag<br />\n";
+				     						$this->files[] = $child->get_attribute('href');
+				     						//var_dump($this->files);
+				     						//ignoring file metadata
+											//files[] array contains all <file href='x'> tags one by one
+											break;
+				     					case 'metadata':
+				     						//echo "Child is a metadata tag<br />\n";
+				     						$this->metadata = new scormMetadata('manifest',$child);
+				     						break;
+				     					case 'dependency':
+				     						//echo "Child is a dependency tag<br />\n";
+				     						//need to get identifierref attribute inside dependency node
+				     						//dependencies[] array represents all <dependency identifierref='x'> tags united
+				     						$this->dependencies[] = $child->get_attribute('identifierref');
+				     						break;
+				     				}
+				     				break;
+				     		}
+				     	}
+				     	$attributes = $element->attributes();
+				     	//$keep_href = '';
+				     	if(count($attributes)>0){ //in some cases we get here with an empty attributes array
+				     	//TODO find when and why we get such a case (empty array)
+					     	foreach($attributes as $a1 => $dummy)
+					     	{
+					     		$attrib =& $attributes[$a1];
+					     		switch($attrib->name){
+					     			case 'identifier':
+					     				$this->identifier = $attrib->value;
+					     				break;
+					     			case 'type':
+					     				if(!empty($attrib->value)){
+					     					$this->type = $attrib->value;
+					     				}
+					     				break;
+					     			case 'scormtype':
+					     				if(!empty($attrib->value)){
+					     					$this->scormtype = $attrib->value;
+					     				}
+					     				break;
+					     			case 'base':
+					     				$this->base = $attrib->value;
+					     				break;
+					     			case 'href':
+					     				$this->href = $attrib->value;
+					     				break;
+					     		}
+					     	}
+				     	}
+						return true;
 
-	    		}
-	    	}elseif($v == 5){
-	    		//parsing using PHP5 DOMXML methods
-	    		switch($type){
-	    			case 'db':
-	    				//TODO implement this way of metadata object creation
-	    				return false;
-	    			case 'manifest': //do the same as the default
-	    			default:
-				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
-				     	$children = $element->childNodes;
-				    	if(is_array($children)){
-					    	foreach($children as $child)
-					     	{
-					     		switch($child->nodeType)
-					     		{
-					     			case XML_ELEMENT_NODE:
-										switch($child->tagName){
-					     					case 'file':
-					     						//echo "Child is a file tag<br />\n";
-					     						$this->files[] = $child->getAttribute('href');
-												break;
-					     					case 'metadata':
-					     						//echo "Child is a metadata tag<br />\n";
-					     						$this->metadata = new scormMetadata('manifest',$child);
-					     						break;
-					     					case 'dependency':
-					     						//need to get identifierref attribute inside dependency node
-					     						//dependencies[] array represents all <dependency identifierref='x'> tags united
-					     						$this->dependencies[] = $child->getAttribute('identifierref');
-					     						break;
-					     				}
-					     				break;
-					     		}
-					     	}
-				     	}
-				     	//$keep_href = '';
-				     	if($element->hasAttributes()){ //in some cases we get here with an empty attributes array
-				     	//TODO find when and why we get such a case (empty array)
-					     	$attributes = $element->attributes;
-					     	foreach($attributes as $attrib)
-					     	{
-					     		switch($attrib->name){
-					     			case 'identifier':
-					     				$this->identifier = $attrib->value;
-					     				break;
-					     			case 'type':
-					     				if(!empty($attrib->value)){
-					     					$this->type = $attrib->value;
-					     				}
-					     				break;
-					     			case 'scormtype':
-					     				if(!empty($attrib->value)){
-					     					$this->scormtype = $attrib->value;
-					     				}
-					     				break;
-					     			case 'base':
-					     				$this->base = $attrib->value;
-					     				break;
-					     			case 'href':
-					     				$this->href = $attrib->value;
-					     				break;
-					     		}
-					     	}
-				     	}
-						return true;
+	    		}
+	    	}elseif($v == 5){
+	    		//parsing using PHP5 DOMXML methods
+	    		switch($type){
+	    			case 'db':
+	    				//TODO implement this way of metadata object creation
+	    				return false;
+	    			case 'manifest': //do the same as the default
+	    			default:
+				     	//if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
+				     	$children = $element->childNodes;
+				    	if(is_array($children)){
+					    	foreach($children as $child)
+					     	{
+					     		switch($child->nodeType)
+					     		{
+					     			case XML_ELEMENT_NODE:
+										switch($child->tagName){
+					     					case 'file':
+					     						//echo "Child is a file tag<br />\n";
+					     						$this->files[] = $child->getAttribute('href');
+												break;
+					     					case 'metadata':
+					     						//echo "Child is a metadata tag<br />\n";
+					     						$this->metadata = new scormMetadata('manifest',$child);
+					     						break;
+					     					case 'dependency':
+					     						//need to get identifierref attribute inside dependency node
+					     						//dependencies[] array represents all <dependency identifierref='x'> tags united
+					     						$this->dependencies[] = $child->getAttribute('identifierref');
+					     						break;
+					     				}
+					     				break;
+					     		}
+					     	}
+				     	}
+				     	//$keep_href = '';
+				     	if($element->hasAttributes()){ //in some cases we get here with an empty attributes array
+				     	//TODO find when and why we get such a case (empty array)
+					     	$attributes = $element->attributes;
+					     	foreach($attributes as $attrib)
+					     	{
+					     		switch($attrib->name){
+					     			case 'identifier':
+					     				$this->identifier = $attrib->value;
+					     				break;
+					     			case 'type':
+					     				if(!empty($attrib->value)){
+					     					$this->type = $attrib->value;
+					     				}
+					     				break;
+					     			case 'scormtype':
+					     				if(!empty($attrib->value)){
+					     					$this->scormtype = $attrib->value;
+					     				}
+					     				break;
+					     			case 'base':
+					     				$this->base = $attrib->value;
+					     				break;
+					     			case 'href':
+					     				$this->href = $attrib->value;
+					     				break;
+					     		}
+					     	}
+				     	}
+						return true;
 
 	    		}
-			}else{
-				//cannot parse because not PHP4 nor PHP5... We should not even be here anyway...
-				return false;
-			}
-    	}
-    	return false;
-     }
-     /**
-      * Path getter
-      * @return	string	Path for this resource
-      */
-     function get_path()
-     {
-     	if(!empty($this->href))
-     	{
-     		require_once('learnpath.class.php');
-     		return learnpath::escape_string($this->href);
-     	}else{
-     		return '';
-     	}
-     }
-     /**
-      * Scorm type getter
-      * @return	string	generally 'asset' or 'sco' as these are the only two values defined in SCORM 1.2
-      */
-     function get_scorm_type()
-     {
-     	if(!empty($this->scormtype)){
-     		require_once('learnpath.class.php');
-     		return learnpath::escape_string($this->scormtype);
-     	}else{
-     		return '';
-     	}
-     }
-}
-?>
+			}else{
+				//cannot parse because not PHP4 nor PHP5... We should not even be here anyway...
+				return false;
+			}
+    	}
+    	return false;
+     }
+     /**
+      * Path getter
+      * @return	string	Path for this resource
+      */
+     function get_path()
+     {
+     	if(!empty($this->href))
+     	{
+     		require_once('learnpath.class.php');
+     		return learnpath::escape_string($this->href);
+     	}else{
+     		return '';
+     	}
+     }
+     /**
+      * Scorm type getter
+      * @return	string	generally 'asset' or 'sco' as these are the only two values defined in SCORM 1.2
+      */
+     function get_scorm_type()
+     {
+     	if(!empty($this->scormtype)){
+     		require_once('learnpath.class.php');
+     		return learnpath::escape_string($this->scormtype);
+     	}else{
+     		return '';
+     	}
+     }
+}
+?>

+ 414 - 414
main/newscorm/scorm_admin.php

@@ -1,415 +1,415 @@
-<?php //$id: $
-//This file is probably deprecated - 2009-05-14 - ywarnier
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2004 Denes Nagy
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
-/**
-==============================================================================
-* This script handles SCO administration features
-* @package dokeos.learnpath.scorm
-* @author Denes Nagy, principal author
-* @author Isthvan Mandak, several new features
-* @author Roan Embrechts, code improvements and refactoring
-* @author Yannick Warnier, complete refactoring <ywarnier@beeznest.org>
-==============================================================================
-*/
-/**
- * Script init
- */
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-// name of the language file that needs to be included
-$language_file = "scormdocument";
-$uncompress=1; //this variable shouldn't be found here (find its usage before removal)
-
-require_once('back_compat.inc.php');
-include('learnpath_functions.inc.php');
-include_once('scorm.lib.php');
-
-$is_allowedToEdit = api_is_allowed_to_edit();
-
-/**
- * Variables
- */
-//escapable integers
-if($_REQUEST['id'] != strval(intval($_REQUEST['id']))){$id = $_REQUEST['id'];}else{$id=null;}
-
-//imported strings
-$path 					= (!empty($_REQUEST['path'])?$_REQUEST['path']:null);
-$Submit 				= (!empty($_POST['Submit'])?$_POST['Submit']:null);
-$submitImage 			= (!empty($_POST['submitImage'])?$_POST['submitImage']:null);
-$cancelSubmitImage 		= (!empty($_POST['cancelSubmitImage'])?$_POST['cancelSubmitImage']:null);
-$action					= (!empty($_REQUEST['action'])?$_REQUEST['action']:null);
-$delete					= (!empty($_REQUEST['delete'])?$_REQUEST['delete']:null);
-$createDir				= (!empty($_REQUEST['createDir'])?$_REQUEST['createDir']:null);
-$make_directory_visible = (!empty($_REQUEST['make_directory_visible'])?$_REQUEST['make_directory_visible']:'');
-$make_directory_invisible = (!empty($_REQUEST['make_directory_invisible'])?$_REQUEST['make_directory_invisible']:'');
-
-//values from POST form to add directory
-$newDirPath				= (!empty($_POST['newDirPath'])?$_POST['newDirPath']:null);
-$newDirName				= (!empty($_POST['newDirName'])?$_POST['newDirName']:null);
-//initialising internal variables
-$dialogbox = '';
-
-if (! $is_allowed_in_course) api_not_allowed();
-$is_allowedToUnzip = $is_courseAdmin;
-
-
-/**
- * Main code
- */
-switch($action){
-	case 'exportpath':
-		if(!empty($id)){
-  			$export = exportpath($id);
-  			$dialogBox .= "This LP has been exported to the Document folder "
-  						."of your course.";
-		}
-		break;
-	case 'exportscorm':
-		exportSCORM($path);
-		break;
-	case 'deletepath':
-		/*==================================================
-			DELETE A DOKEOS LEARNPATH
-			and all the items in it
-		 ==================================================*/
-		if(!empty($id)){
-			$l="learnpath/learnpath_handler.php?learnpath_id=$id";
-			$sql="DELETE FROM $tbl_tool where (link='$l' AND image='scormbuilder.gif')";
-			$result=Database::query($sql,__FILE__,__LINE__);
-			$sql="SELECT * FROM $tbl_learnpath_chapter where learnpath_id=$id";
-			$result=Database::query($sql,__FILE__,__LINE__);
-			while ($row=mysql_fetch_array($result))
-			{
-				$c=$row['id'];
-				$sql2="DELETE FROM $tbl_learnpath_item where chapter_id=$c";
-				$result2=Database::query($sql2,__FILE__,__LINE__);
-			}
-			$sql="DELETE FROM $tbl_learnpath_chapter where learnpath_id=$id";
-			$result=Database::query($sql,__FILE__,__LINE__);
-			deletepath($id);
-			$dialogBox=get_lang('_learnpath_deleted');
-		}
-		break;
-	case 'publishpath':
-		/*==================================================================
-		  PUBLISHING (SHOWING) A DOKEOS LEARNPATH
-		  ==================================================================*/
-		if(!empty($id)){
-			$sql="SELECT * FROM $tbl_learnpath_main where learnpath_id=$id";
-			$result=Database::query($sql,__FILE__,__LINE__);
-			$row=mysql_fetch_array($result);
-			$name=domesticate($row['learnpath_name']);
-			if ($set_visibility == 'i') {
-				$s=$name." ".get_lang('_no_published');
-				$dialogBox=$s;
-				$v=0;
-			}
-			if ($set_visibility == 'v') {
-				$s=$name." ".get_lang('_published');
-				$dialogBox=$s;
-				$v=1;
-			}
-			$sql="SELECT * FROM $tbl_tool where (name='$name' and image='scormbuilder.gif')";
-			$result=Database::query($sql,__FILE__,__LINE__);
-			$row2=mysql_fetch_array($result);
-			$num=mysql_num_rows($result);
-			if (($set_visibility == 'i') && ($num>0))
-			{
-				//it is visible or hidden but once was published
-				if (($row2['visibility'])==1)
-				{
-					$sql ="DELETE FROM $tbl_tool WHERE (name='$name' and image='scormbuilder.gif')";
-				}
-				else
-				{
-					$sql ="UPDATE $tbl_tool set visibility=1 WHERE (name='$name' and image='scormbuilder.gif')";
-				}
-			}
-			elseif (($set_visibility == 'v') && ($num==0))
-			{
-				$sql ="INSERT INTO $tbl_tool (id, name, link, image, visibility, admin, address, added_tool) VALUES ('$theid','$name','learnpath/learnpath_handler.php?learnpath_id=$id','scormbuilder.gif','$v','0','pastillegris.gif',0)";
-			}
-			else
-			{
-				//parameter and database incompatible, do nothing
-			}
-			$result=Database::query($sql,__FILE__,__LINE__);
-
-		}
-		break;
-	case 'editpath':
-		/*==================================================================
-		  EDITING A DOKEOS NEW LEARNPATH
-  		==================================================================*/
-		if(!empty($Submit))
-		{
-		  $l="learnpath/learnpath_handler.php?learnpath_id=$id";
-		  $sql="UPDATE $tbl_tool set name='".domesticate($learnpath_name)."' where (link='$l' and image='scormbuilder.gif')";
-		  $result=Database::query($sql,__FILE__,__LINE__);
-		  $sql ="UPDATE $tbl_learnpath_main SET learnpath_name='".domesticate($learnpath_name)."', learnpath_description='".domesticate($learnpath_description)."' WHERE learnpath_id=$id";
-		  $result=Database::query($sql,__FILE__,__LINE__);
-		  $dialogBox=get_lang('_learnpath_edited');
-		}
-		break;
-	case 'add':
-		/*==================================================================
-		  		ADDING A NEW LEARNPATH : treating the form
-		 ==================================================================*/
-		if (!empty($Submit))
-		{
-		  $sql ="INSERT INTO $tbl_learnpath_main (learnpath_name, learnpath_description) VALUES ('".domesticate($learnpath_name)."','".domesticate($learnpath_description)."')";
-		  Database::query($sql,__FILE__,__LINE__);
-		  $my_lp_id = Database::get_last_insert_id();
-		  $sql ="INSERT INTO $tbl_tool (name, link, image, visibility, admin, address, added_tool) VALUES ('".domesticate($learnpath_name)."','learnpath/learnpath_handler.php?learnpath_id=$my_lp_id','scormbuilder.gif','1','0','pastillegris.gif',0)";
-		  Database::query($sql,__FILE__,__LINE__);
-		  //instead of displaying this info text, get the user directly to the learnpath edit page
-		  //$dialogBox=get_lang('_learnpath_added');
-		  header('location:../learnpath/learnpath_handler.php?'.api_get_cidreq().'&learnpath_id='.$my_lp_id);
-		  exit();
-		}
-		break;
-	case 'editscorm':
-		/*==================================================================
-		EDITING A SCORM PACKAGE
- 		==================================================================*/
-		if (!empty($Submit))
-		{
-			$sql ="UPDATE $tbl_document SET comment='".domesticate($learnpath_description)."', name='".domesticate($learnpath_name)."' WHERE path='$path'";
-			$result=Database::query($sql,__FILE__,__LINE__);
-			$dialogBox=get_lang('_learnpath_edited');
-		}
-		break;
-	default:
-		break;
-}
-
-/*============================================================================*/
-
-if($is_allowedToEdit) // TEACHER ONLY
-{
-  /*======================================
-	 UPLOAD SCORM
-   ======================================*/
-  /*
-   * Check the request method instead of a variable from POST
-   * because if the file size exceeds the maximum file upload
-   * size set in php.ini, all variables from POST are cleared !
-   */
-
-  if ($_SERVER['REQUEST_METHOD'] == 'POST'
-  	&& count($_FILES)>0
-  	&& empty($submitImage)
-  	&& empty($cancelSubmitImage)
-  	&& empty($action))
-  {
-    // A SCORM upload has been detected, now deal with the file...
-    //directory creation
-    $s=$_FILES['userFile']['name'];
-    $pathInfo = pathinfo($s);
-    //Check the filename has at least several letters in it :-)
-    //This is a very loose check as later on we might accept other formats of packages
-    //sent than just "zip"
-    if(preg_match('/[\w-_]+/',$pathInfo['basename'])){
-	    //get the basename without extension
-	    $newDirName=substr(
-	    	$pathInfo['basename'],
-	    	0,
-	    	strlen($pathInfo['basename'])-(strlen($pathInfo['extension'])+1));
-	    $newDirName = replace_dangerous_char(trim($newDirName),'strict');
-	    if( check_name_exist($baseWorkDir.$newDirPath.$openDir."/".$newDirName) )
-	    {
-	      /** @todo change this output. Inaccurate at least in french. In this case, the
-	       * file might not exist or the transfer might have been wrong (no $_FILES at all)
-	       * but we still get the error message
-	       */
-	      $dialogBox = get_lang('FileExists');
-	      $createDir = $newDirPath; unset($newDirPath);// return to step 1
-	    }
-	    else
-	    {
-	      if(mkdir($baseWorkDir.$newDirPath.$openDir."/".$newDirName, 0700)){
-	        FileManager::set_default_settings($newDirPath.$openDir, $newDirName, "folder", $tbl_document);
-	        // RH: was:  set_default_settings($newDirPath.$openDir,$newDirName,"folder");
-	        $dialogBox = get_lang('DirCr');
-	      }else{
-	      	//Display msg "could not create dir..."
-	        //exit();
-	    }
-	    //directory creation end
-
-	    $uploadPath=$openDir.'/'.$newDirName;
-	    if(!$_FILES['userFile']['size'])
-        {
-	        $dialogBox .= get_lang('FileError').'<br />'.get_lang('Notice').' : '.get_lang('MaxFileSize').' '.ini_get('upload_max_filesize');
-	    }
-	    else //the file size is alright, we can assume the file is OK too
-	    {
-	      if($uncompress == 1 && $is_allowedToUnzip)
-	      {
-		    $unzip = 'unzip';
-	      }
-	      else
-	      {
-	        $unzip = '';
-	      }
-	      if (treat_uploaded_file($_FILES['userFile'], $baseWorkDir,
-		        $uploadPath, $maxFilledSpace, $unzip))
-	      {
-	        if ($uncompress == 1)
-		    {
-	          //$dialogBox .= get_lang('DownloadAndZipEnd');
-	          //modified by darkden : I omitted this part, so the user can see
-		      //the scorm content message at once
-		    }
-	        else
-		    {
-		      $dialogBox = get_lang('DownloadEnd');
-		    }
-	        // "WHAT'S NEW" notification: update table last_tooledit
-	        //update_last_tooledit($_course, $nameTools, $id, get_lang('_new_document'), $_user['user_id']);
-	        item_property_update($_course, TOOL_LEARNPATH, $id, "LearnpathAdded", $_user['user_id']);
-	      }
-	      else
-	      {
-	        if(api_failure::get_last_failure() == 'not_enough_space')
-	        {
-	          $dialogBox = get_lang('NoSpace');
-		    }
-		    elseif (api_failure::get_last_failure() == 'php_file_in_zip_file')
-		    {
-		      $dialogBox = get_lang('ZipNoPhp');
-		    }
-		    elseif(api_failure::get_last_failure() == 'not_scorm_content')
-		    {
-		      $dialogBox = get_lang('NotScormContent');
-		    }
-	      }
-	    }
-	    $uploadPath='';
-	    if (api_failure::get_last_failure())
-	    {
-	      rmdir($baseWorkDir.$newDirPath.$openDir."/".$newDirName);
-	    }
-
-    }
-  }//
-  else
-  {//the filename doesn't contain any alphanum chars (empty filename?)
-  	//get a more detailed message?
-    $dialogBox .= get_lang('FileError').'<br />';
-  }
-
-  /*======================================
-	DELETE FILE OR DIRECTORY
-    ======================================*/
-
-  if ( isset($delete) )
-  {
-    if ( scorm_delete($baseWorkDir.$delete))
-    {
-      //$tbl_document = substr($tbl_document, 1, strlen($tbl_document) - 2);  // RH...
-      update_db_info("delete", $delete);
-      $dialogBox = get_lang('DocDeleted');
-    }
-  }
-  /*======================================
-	CREATE DIRECTORY
-  ======================================*/
-  /*
-   * The code begin with STEP 2 so it allows to return to STEP 1
-   * if STEP 2 unsucceds
-   */
-
-  /*-------------------------------------
-	STEP 2
-  --------------------------------------*/
-  if (isset($newDirPath) && isset($newDirName))
-  {
-    // echo $newDirPath . $newDirName;
-    $newDirName = replace_dangerous_char(trim(stripslashes($newDirName)),'strict');
-    if( check_name_exist($baseWorkDir.$newDirPath."/".$newDirName) )
-    {
-      $dialogBox = get_lang('FileExists');
-      $createDir = $newDirPath; unset($newDirPath);// return to step 1
-    }
-    else
-    {
-      if(mkdir($baseWorkDir.$newDirPath."/".$newDirName, 0700))
-        FileManager::set_default_settings($newDirPath, $newDirName, "folder", $tbl_document);
-      // RH: was:  set_default_settings($newDirPath,$newDirName,"folder");
-			$dialogBox = get_lang('DirCr');
-    }
-  }
-
-  /*-------------------------------------
-	 STEP 1
-   --------------------------------------*/
-  if (isset($createDir))
-  {
-    $dialogBox .= "<!-- create dir -->\n"
-	."<form name='createdir' action='' method='POST'>\n"
-	."<input type=\"hidden\" name=\"newDirPath\" value=\"$createDir\" />\n"
-	.get_lang('NameDir')." : \n"
-	."<input type=\"text\" name=\"newDirName\" />\n"
-	."<input type=\"submit\" value=\"".get_lang('Ok')."\" />\n"
-	."</form>\n";
-  }
-
-  /*======================================
-  	  VISIBILITY COMMANDS
-  ======================================*/
-  if (!empty($make_directory_visible) || !empty($make_directory_invisible))
-  {
-    $visibilityPath = $make_directory_visible.$make_directory_invisible;
-    // At least one of these variables are empty. So it's okay to proceed this way
-    /* Check if there is yet a record for this file in the DB */
-    $result = mysql_query ("SELECT * FROM $tbl_document WHERE path LIKE '".$visibilityPath."'");
-    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
-    {
-      $attribute['path'      ] = $row['path'      ];
-      $attribute['visibility'] = $row['visibility'];
-      $attribute['comment'   ] = $row['comment'   ];
-    }
-
-    if ($make_directory_visible)
-    {
-      $newVisibilityStatus = "v";
-    }
-    elseif ($make_directory_invisible)
-    {
-      $newVisibilityStatus = "i";
-    }
-    $query = "UPDATE $tbl_document SET visibility='$newVisibilityStatus' WHERE path=\"".$visibilityPath."\""; //added by Toon
-    Database::query($query,__FILE__,__LINE__);
-    if (mysql_affected_rows() == 0) // extra check added by Toon, normally not necessary anymore because all files are in the db
-    {
-      Database::query("INSERT INTO $tbl_document SET path=\"".$visibilityPath."\", visibility=\"".$newVisibilityStatus."\"",__FILE__,__LINE__);
-    }
-    unset($attribute);
-    $dialogBox = get_lang('ViMod');
-  }
- } // END is Allowed to Edit;
-}
+<?php //$id: $
+//This file is probably deprecated - 2009-05-14 - ywarnier
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2004 Denes Nagy
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
+
+	This program is free software; you can redistribute it and/or
+	modify it under the terms of the GNU General Public License
+	as published by the Free Software Foundation; either version 2
+	of the License, or (at your option) any later version.
+
+	See the GNU General Public License for more details.
+
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+==============================================================================
+*/
+/**
+==============================================================================
+* This script handles SCO administration features
+* @package dokeos.learnpath.scorm
+* @author Denes Nagy, principal author
+* @author Isthvan Mandak, several new features
+* @author Roan Embrechts, code improvements and refactoring
+* @author Yannick Warnier, complete refactoring <ywarnier@beeznest.org>
+==============================================================================
+*/
+/**
+ * Script init
+ */
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+// name of the language file that needs to be included
+$language_file = "scormdocument";
+$uncompress=1; //this variable shouldn't be found here (find its usage before removal)
+
+require_once('back_compat.inc.php');
+include('learnpath_functions.inc.php');
+include_once('scorm.lib.php');
+
+$is_allowedToEdit = api_is_allowed_to_edit();
+
+/**
+ * Variables
+ */
+//escapable integers
+if($_REQUEST['id'] != strval(intval($_REQUEST['id']))){$id = $_REQUEST['id'];}else{$id=null;}
+
+//imported strings
+$path 					= (!empty($_REQUEST['path'])?$_REQUEST['path']:null);
+$Submit 				= (!empty($_POST['Submit'])?$_POST['Submit']:null);
+$submitImage 			= (!empty($_POST['submitImage'])?$_POST['submitImage']:null);
+$cancelSubmitImage 		= (!empty($_POST['cancelSubmitImage'])?$_POST['cancelSubmitImage']:null);
+$action					= (!empty($_REQUEST['action'])?$_REQUEST['action']:null);
+$delete					= (!empty($_REQUEST['delete'])?$_REQUEST['delete']:null);
+$createDir				= (!empty($_REQUEST['createDir'])?$_REQUEST['createDir']:null);
+$make_directory_visible = (!empty($_REQUEST['make_directory_visible'])?$_REQUEST['make_directory_visible']:'');
+$make_directory_invisible = (!empty($_REQUEST['make_directory_invisible'])?$_REQUEST['make_directory_invisible']:'');
+
+//values from POST form to add directory
+$newDirPath				= (!empty($_POST['newDirPath'])?$_POST['newDirPath']:null);
+$newDirName				= (!empty($_POST['newDirName'])?$_POST['newDirName']:null);
+//initialising internal variables
+$dialogbox = '';
+
+if (! $is_allowed_in_course) api_not_allowed();
+$is_allowedToUnzip = $is_courseAdmin;
+
+
+/**
+ * Main code
+ */
+switch($action){
+	case 'exportpath':
+		if(!empty($id)){
+  			$export = exportpath($id);
+  			$dialogBox .= "This LP has been exported to the Document folder "
+  						."of your course.";
+		}
+		break;
+	case 'exportscorm':
+		exportSCORM($path);
+		break;
+	case 'deletepath':
+		/*==================================================
+			DELETE A DOKEOS LEARNPATH
+			and all the items in it
+		 ==================================================*/
+		if(!empty($id)){
+			$l="learnpath/learnpath_handler.php?learnpath_id=$id";
+			$sql="DELETE FROM $tbl_tool where (link='$l' AND image='scormbuilder.gif')";
+			$result=Database::query($sql,__FILE__,__LINE__);
+			$sql="SELECT * FROM $tbl_learnpath_chapter where learnpath_id=$id";
+			$result=Database::query($sql,__FILE__,__LINE__);
+			while ($row=mysql_fetch_array($result))
+			{
+				$c=$row['id'];
+				$sql2="DELETE FROM $tbl_learnpath_item where chapter_id=$c";
+				$result2=Database::query($sql2,__FILE__,__LINE__);
+			}
+			$sql="DELETE FROM $tbl_learnpath_chapter where learnpath_id=$id";
+			$result=Database::query($sql,__FILE__,__LINE__);
+			deletepath($id);
+			$dialogBox=get_lang('_learnpath_deleted');
+		}
+		break;
+	case 'publishpath':
+		/*==================================================================
+		  PUBLISHING (SHOWING) A DOKEOS LEARNPATH
+		  ==================================================================*/
+		if(!empty($id)){
+			$sql="SELECT * FROM $tbl_learnpath_main where learnpath_id=$id";
+			$result=Database::query($sql,__FILE__,__LINE__);
+			$row=mysql_fetch_array($result);
+			$name=domesticate($row['learnpath_name']);
+			if ($set_visibility == 'i') {
+				$s=$name." ".get_lang('_no_published');
+				$dialogBox=$s;
+				$v=0;
+			}
+			if ($set_visibility == 'v') {
+				$s=$name." ".get_lang('_published');
+				$dialogBox=$s;
+				$v=1;
+			}
+			$sql="SELECT * FROM $tbl_tool where (name='$name' and image='scormbuilder.gif')";
+			$result=Database::query($sql,__FILE__,__LINE__);
+			$row2=mysql_fetch_array($result);
+			$num=mysql_num_rows($result);
+			if (($set_visibility == 'i') && ($num>0))
+			{
+				//it is visible or hidden but once was published
+				if (($row2['visibility'])==1)
+				{
+					$sql ="DELETE FROM $tbl_tool WHERE (name='$name' and image='scormbuilder.gif')";
+				}
+				else
+				{
+					$sql ="UPDATE $tbl_tool set visibility=1 WHERE (name='$name' and image='scormbuilder.gif')";
+				}
+			}
+			elseif (($set_visibility == 'v') && ($num==0))
+			{
+				$sql ="INSERT INTO $tbl_tool (id, name, link, image, visibility, admin, address, added_tool) VALUES ('$theid','$name','learnpath/learnpath_handler.php?learnpath_id=$id','scormbuilder.gif','$v','0','pastillegris.gif',0)";
+			}
+			else
+			{
+				//parameter and database incompatible, do nothing
+			}
+			$result=Database::query($sql,__FILE__,__LINE__);
+
+		}
+		break;
+	case 'editpath':
+		/*==================================================================
+		  EDITING A DOKEOS NEW LEARNPATH
+  		==================================================================*/
+		if(!empty($Submit))
+		{
+		  $l="learnpath/learnpath_handler.php?learnpath_id=$id";
+		  $sql="UPDATE $tbl_tool set name='".domesticate($learnpath_name)."' where (link='$l' and image='scormbuilder.gif')";
+		  $result=Database::query($sql,__FILE__,__LINE__);
+		  $sql ="UPDATE $tbl_learnpath_main SET learnpath_name='".domesticate($learnpath_name)."', learnpath_description='".domesticate($learnpath_description)."' WHERE learnpath_id=$id";
+		  $result=Database::query($sql,__FILE__,__LINE__);
+		  $dialogBox=get_lang('_learnpath_edited');
+		}
+		break;
+	case 'add':
+		/*==================================================================
+		  		ADDING A NEW LEARNPATH : treating the form
+		 ==================================================================*/
+		if (!empty($Submit))
+		{
+		  $sql ="INSERT INTO $tbl_learnpath_main (learnpath_name, learnpath_description) VALUES ('".domesticate($learnpath_name)."','".domesticate($learnpath_description)."')";
+		  Database::query($sql,__FILE__,__LINE__);
+		  $my_lp_id = Database::get_last_insert_id();
+		  $sql ="INSERT INTO $tbl_tool (name, link, image, visibility, admin, address, added_tool) VALUES ('".domesticate($learnpath_name)."','learnpath/learnpath_handler.php?learnpath_id=$my_lp_id','scormbuilder.gif','1','0','pastillegris.gif',0)";
+		  Database::query($sql,__FILE__,__LINE__);
+		  //instead of displaying this info text, get the user directly to the learnpath edit page
+		  //$dialogBox=get_lang('_learnpath_added');
+		  header('location:../learnpath/learnpath_handler.php?'.api_get_cidreq().'&learnpath_id='.$my_lp_id);
+		  exit();
+		}
+		break;
+	case 'editscorm':
+		/*==================================================================
+		EDITING A SCORM PACKAGE
+ 		==================================================================*/
+		if (!empty($Submit))
+		{
+			$sql ="UPDATE $tbl_document SET comment='".domesticate($learnpath_description)."', name='".domesticate($learnpath_name)."' WHERE path='$path'";
+			$result=Database::query($sql,__FILE__,__LINE__);
+			$dialogBox=get_lang('_learnpath_edited');
+		}
+		break;
+	default:
+		break;
+}
+
+/*============================================================================*/
+
+if($is_allowedToEdit) // TEACHER ONLY
+{
+  /*======================================
+	 UPLOAD SCORM
+   ======================================*/
+  /*
+   * Check the request method instead of a variable from POST
+   * because if the file size exceeds the maximum file upload
+   * size set in php.ini, all variables from POST are cleared !
+   */
+
+  if ($_SERVER['REQUEST_METHOD'] == 'POST'
+  	&& count($_FILES)>0
+  	&& empty($submitImage)
+  	&& empty($cancelSubmitImage)
+  	&& empty($action))
+  {
+    // A SCORM upload has been detected, now deal with the file...
+    //directory creation
+    $s=$_FILES['userFile']['name'];
+    $pathInfo = pathinfo($s);
+    //Check the filename has at least several letters in it :-)
+    //This is a very loose check as later on we might accept other formats of packages
+    //sent than just "zip"
+    if(preg_match('/[\w-_]+/',$pathInfo['basename'])){
+	    //get the basename without extension
+	    $newDirName=substr(
+	    	$pathInfo['basename'],
+	    	0,
+	    	strlen($pathInfo['basename'])-(strlen($pathInfo['extension'])+1));
+	    $newDirName = replace_dangerous_char(trim($newDirName),'strict');
+	    if( check_name_exist($baseWorkDir.$newDirPath.$openDir."/".$newDirName) )
+	    {
+	      /** @todo change this output. Inaccurate at least in french. In this case, the
+	       * file might not exist or the transfer might have been wrong (no $_FILES at all)
+	       * but we still get the error message
+	       */
+	      $dialogBox = get_lang('FileExists');
+	      $createDir = $newDirPath; unset($newDirPath);// return to step 1
+	    }
+	    else
+	    {
+	      if(mkdir($baseWorkDir.$newDirPath.$openDir."/".$newDirName, 0700)){
+	        FileManager::set_default_settings($newDirPath.$openDir, $newDirName, "folder", $tbl_document);
+	        // RH: was:  set_default_settings($newDirPath.$openDir,$newDirName,"folder");
+	        $dialogBox = get_lang('DirCr');
+	      }else{
+	      	//Display msg "could not create dir..."
+	        //exit();
+	    }
+	    //directory creation end
+
+	    $uploadPath=$openDir.'/'.$newDirName;
+	    if(!$_FILES['userFile']['size'])
+        {
+	        $dialogBox .= get_lang('FileError').'<br />'.get_lang('Notice').' : '.get_lang('MaxFileSize').' '.ini_get('upload_max_filesize');
+	    }
+	    else //the file size is alright, we can assume the file is OK too
+	    {
+	      if($uncompress == 1 && $is_allowedToUnzip)
+	      {
+		    $unzip = 'unzip';
+	      }
+	      else
+	      {
+	        $unzip = '';
+	      }
+	      if (treat_uploaded_file($_FILES['userFile'], $baseWorkDir,
+		        $uploadPath, $maxFilledSpace, $unzip))
+	      {
+	        if ($uncompress == 1)
+		    {
+	          //$dialogBox .= get_lang('DownloadAndZipEnd');
+	          //modified by darkden : I omitted this part, so the user can see
+		      //the scorm content message at once
+		    }
+	        else
+		    {
+		      $dialogBox = get_lang('DownloadEnd');
+		    }
+	        // "WHAT'S NEW" notification: update table last_tooledit
+	        //update_last_tooledit($_course, $nameTools, $id, get_lang('_new_document'), $_user['user_id']);
+	        item_property_update($_course, TOOL_LEARNPATH, $id, "LearnpathAdded", $_user['user_id']);
+	      }
+	      else
+	      {
+	        if(api_failure::get_last_failure() == 'not_enough_space')
+	        {
+	          $dialogBox = get_lang('NoSpace');
+		    }
+		    elseif (api_failure::get_last_failure() == 'php_file_in_zip_file')
+		    {
+		      $dialogBox = get_lang('ZipNoPhp');
+		    }
+		    elseif(api_failure::get_last_failure() == 'not_scorm_content')
+		    {
+		      $dialogBox = get_lang('NotScormContent');
+		    }
+	      }
+	    }
+	    $uploadPath='';
+	    if (api_failure::get_last_failure())
+	    {
+	      rmdir($baseWorkDir.$newDirPath.$openDir."/".$newDirName);
+	    }
+
+    }
+  }//
+  else
+  {//the filename doesn't contain any alphanum chars (empty filename?)
+  	//get a more detailed message?
+    $dialogBox .= get_lang('FileError').'<br />';
+  }
+
+  /*======================================
+	DELETE FILE OR DIRECTORY
+    ======================================*/
+
+  if ( isset($delete) )
+  {
+    if ( scorm_delete($baseWorkDir.$delete))
+    {
+      //$tbl_document = substr($tbl_document, 1, strlen($tbl_document) - 2);  // RH...
+      update_db_info("delete", $delete);
+      $dialogBox = get_lang('DocDeleted');
+    }
+  }
+  /*======================================
+	CREATE DIRECTORY
+  ======================================*/
+  /*
+   * The code begin with STEP 2 so it allows to return to STEP 1
+   * if STEP 2 unsucceds
+   */
+
+  /*-------------------------------------
+	STEP 2
+  --------------------------------------*/
+  if (isset($newDirPath) && isset($newDirName))
+  {
+    // echo $newDirPath . $newDirName;
+    $newDirName = replace_dangerous_char(trim(stripslashes($newDirName)),'strict');
+    if( check_name_exist($baseWorkDir.$newDirPath."/".$newDirName) )
+    {
+      $dialogBox = get_lang('FileExists');
+      $createDir = $newDirPath; unset($newDirPath);// return to step 1
+    }
+    else
+    {
+      if(mkdir($baseWorkDir.$newDirPath."/".$newDirName, 0700))
+        FileManager::set_default_settings($newDirPath, $newDirName, "folder", $tbl_document);
+      // RH: was:  set_default_settings($newDirPath,$newDirName,"folder");
+			$dialogBox = get_lang('DirCr');
+    }
+  }
+
+  /*-------------------------------------
+	 STEP 1
+   --------------------------------------*/
+  if (isset($createDir))
+  {
+    $dialogBox .= "<!-- create dir -->\n"
+	."<form name='createdir' action='' method='POST'>\n"
+	."<input type=\"hidden\" name=\"newDirPath\" value=\"$createDir\" />\n"
+	.get_lang('NameDir')." : \n"
+	."<input type=\"text\" name=\"newDirName\" />\n"
+	."<input type=\"submit\" value=\"".get_lang('Ok')."\" />\n"
+	."</form>\n";
+  }
+
+  /*======================================
+  	  VISIBILITY COMMANDS
+  ======================================*/
+  if (!empty($make_directory_visible) || !empty($make_directory_invisible))
+  {
+    $visibilityPath = $make_directory_visible.$make_directory_invisible;
+    // At least one of these variables are empty. So it's okay to proceed this way
+    /* Check if there is yet a record for this file in the DB */
+    $result = mysql_query ("SELECT * FROM $tbl_document WHERE path LIKE '".$visibilityPath."'");
+    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
+    {
+      $attribute['path'      ] = $row['path'      ];
+      $attribute['visibility'] = $row['visibility'];
+      $attribute['comment'   ] = $row['comment'   ];
+    }
+
+    if ($make_directory_visible)
+    {
+      $newVisibilityStatus = "v";
+    }
+    elseif ($make_directory_invisible)
+    {
+      $newVisibilityStatus = "i";
+    }
+    $query = "UPDATE $tbl_document SET visibility='$newVisibilityStatus' WHERE path=\"".$visibilityPath."\""; //added by Toon
+    Database::query($query,__FILE__,__LINE__);
+    if (mysql_affected_rows() == 0) // extra check added by Toon, normally not necessary anymore because all files are in the db
+    {
+      Database::query("INSERT INTO $tbl_document SET path=\"".$visibilityPath."\", visibility=\"".$newVisibilityStatus."\"",__FILE__,__LINE__);
+    }
+    unset($attribute);
+    $dialogBox = get_lang('ViMod');
+  }
+ } // END is Allowed to Edit;
+}
 ?>

+ 1448 - 1448
main/newscorm/scorm_api.php

@@ -1,1580 +1,1580 @@
 <?php // $Id: scorm_api.php 21162 2009-06-01 16:18:46Z yannoo $
-/*
+/*
 ==============================================================================
-	Dokeos - elearning and course management software
+	Dokeos - elearning and course management software
 
-	Copyright (c) 2004-2009 Dokeos SPRL
-	Copyright (c) Denes Nagy (darkden@freemail.hu)
+	Copyright (c) 2004-2009 Dokeos SPRL
+	Copyright (c) Denes Nagy (darkden@freemail.hu)
 
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
+	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.
+	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.
+	See the GNU General Public License for more details.
 
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
+	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
 ==============================================================================
-*/
-/**
+*/
+/**
 ==============================================================================
-*	API event handler functions for Scorm 1.1 and 1.2 and 1.3
-*
-*	@author   Denes Nagy <darkden@freemail.hu>
-*   @author   Yannick Warnier <ywarnier@beeznest.org>
-*	@version  v 1.0
-*	@access   public
-*   @package  dokeos.learnpath.scorm
+*	API event handler functions for Scorm 1.1 and 1.2 and 1.3
+*
+*	@author   Denes Nagy <darkden@freemail.hu>
+*   @author   Yannick Warnier <ywarnier@beeznest.org>
+*	@version  v 1.0
+*	@access   public
+*   @package  dokeos.learnpath.scorm
 ==============================================================================
-*/
-/**
+*/
+/**
  * This script is divided into three sections.
- * The first section (below) is the initialisation part.
- * The second section is the SCORM object part
- * The third section defines the event handlers for Dokeos' internal messaging
- * and frames refresh
- */
-/*
+ * The first section (below) is the initialisation part.
+ * The second section is the SCORM object part
+ * The third section defines the event handlers for Dokeos' internal messaging
+ * and frames refresh
+ */
+/*
 ==============================================================================
-	   INIT SECTION
+	   INIT SECTION
 ==============================================================================
 */
-
-// if you open the imsmanifest.xml via local machine (f.ex.: file://c:/...), then the Apiwrapper.js
-// of Maritime Navigation when trying to execute this row
-//    var result = api.LMSInitialize("");
-// get the error response : you are not authorized to call this function
-
-//flag to allow for anonymous user - needs to be set before global.inc.php
-$use_anonymous = true;
-
-require_once('back_compat.inc.php');
-require_once('learnpath.class.php');
-require_once('learnpathItem.class.php');
-require_once('scorm.class.php');
-
-// Is this needed? This is probabaly done in the header file
-//$_user							= $_SESSION['_user'];
-$file							= (empty($_SESSION['file'])?'':$_SESSION['file']);
-$oLP							= unserialize($_SESSION['lpobject']);
-$oItem 							= $oLP->items[$oLP->current];
-if(!is_object($oItem)){
-	error_log('New LP - scorm_api - Could not load oItem item',0);
-	exit;
-}
-$autocomplete_when_80pct = 0;
-
-/*
+
+// if you open the imsmanifest.xml via local machine (f.ex.: file://c:/...), then the Apiwrapper.js
+// of Maritime Navigation when trying to execute this row
+//    var result = api.LMSInitialize("");
+// get the error response : you are not authorized to call this function
+
+//flag to allow for anonymous user - needs to be set before global.inc.php
+$use_anonymous = true;
+
+require_once('back_compat.inc.php');
+require_once('learnpath.class.php');
+require_once('learnpathItem.class.php');
+require_once('scorm.class.php');
+
+// Is this needed? This is probabaly done in the header file
+//$_user							= $_SESSION['_user'];
+$file							= (empty($_SESSION['file'])?'':$_SESSION['file']);
+$oLP							= unserialize($_SESSION['lpobject']);
+$oItem 							= $oLP->items[$oLP->current];
+if(!is_object($oItem)){
+	error_log('New LP - scorm_api - Could not load oItem item',0);
+	exit;
+}
+$autocomplete_when_80pct = 0;
+
+/*
 ==============================================================================
-		JavaScript Functions
+		JavaScript Functions
 ==============================================================================
 */
-?>var scorm_logs='<?php echo ((empty($oLP->scorm_debug) or !api_is_course_admin())?'0':'3');?>'; //debug log level for SCORM. 0 = none, 1=light, 2=a lot, 3=all - displays logs in log frame
-var lms_logs=0; //debug log level for LMS actions. 0=none, 1=light, 2=a lot, 3=all
-//logit_lms('scormfunctions.php included',0);
-
-function APIobject() {
-  this.LMSInitialize=LMSInitialize;  //for Scorm 1.2
-  this.Initialize=LMSInitialize;     //for Scorm 1.3
-  this.LMSGetValue=LMSGetValue;
-  this.GetValue=LMSGetValue;
-  this.LMSSetValue=LMSSetValue;
-  this.SetValue=LMSSetValue;
-  this.LMSCommit=LMSCommit;
-  this.Commit=LMSCommit;
-  this.LMSFinish=LMSFinish;
-  this.Finish=LMSFinish;
-  this.LMSGetLastError=LMSGetLastError;
-  this.GetLastError=LMSGetLastError;
-  this.LMSGetErrorString=LMSGetErrorString;
-  this.GetErrorString=LMSGetErrorString;
-  this.LMSGetDiagnostic=LMSGetDiagnostic;
-  this.GetDiagnostic=LMSGetDiagnostic;
-  this.Terminate=Terminate;  //only in Scorm 1.3
-  this.save_asset = dokeos_save_asset;
-  this.void_save_asset = dokeos_void_save_asset;
-}
-
-//it is not sure that the scos use the above declarations
-
-API = new APIobject(); //for scorm 1.2
-api = API;
-//api = new APIobject(); //for scorm 1.2
-API_1484_11 = new APIobject();  //for scorm 1.3
-api_1484_11 = API_1484_11;
-//api_1484_11 = new APIobject();  //for scorm 1.3
-
+?>var scorm_logs='<?php echo ((empty($oLP->scorm_debug) or !api_is_course_admin())?'0':'3');?>'; //debug log level for SCORM. 0 = none, 1=light, 2=a lot, 3=all - displays logs in log frame
+var lms_logs=0; //debug log level for LMS actions. 0=none, 1=light, 2=a lot, 3=all
+//logit_lms('scormfunctions.php included',0);
+
+function APIobject() {
+  this.LMSInitialize=LMSInitialize;  //for Scorm 1.2
+  this.Initialize=LMSInitialize;     //for Scorm 1.3
+  this.LMSGetValue=LMSGetValue;
+  this.GetValue=LMSGetValue;
+  this.LMSSetValue=LMSSetValue;
+  this.SetValue=LMSSetValue;
+  this.LMSCommit=LMSCommit;
+  this.Commit=LMSCommit;
+  this.LMSFinish=LMSFinish;
+  this.Finish=LMSFinish;
+  this.LMSGetLastError=LMSGetLastError;
+  this.GetLastError=LMSGetLastError;
+  this.LMSGetErrorString=LMSGetErrorString;
+  this.GetErrorString=LMSGetErrorString;
+  this.LMSGetDiagnostic=LMSGetDiagnostic;
+  this.GetDiagnostic=LMSGetDiagnostic;
+  this.Terminate=Terminate;  //only in Scorm 1.3
+  this.save_asset = dokeos_save_asset;
+  this.void_save_asset = dokeos_void_save_asset;
+}
+
+//it is not sure that the scos use the above declarations
+
+API = new APIobject(); //for scorm 1.2
+api = API;
+//api = new APIobject(); //for scorm 1.2
+API_1484_11 = new APIobject();  //for scorm 1.3
+api_1484_11 = API_1484_11;
+//api_1484_11 = new APIobject();  //for scorm 1.3
+
 // Error codes
-var G_NoError = 0;
-var G_GeneralException = 101;
+var G_NoError = 0;
+var G_GeneralException = 101;
 var G_ServerBusy 				= 102; // this is not in the Scorm1.2_Runtime document
-var G_InvalidArgumentError = 201;
-var G_ElementCannotHaveChildren = 202;
-var G_ElementIsNotAnArray = 203;
-var G_NotInitialized = 301;
-var G_NotImplementedError = 401;
-var G_InvalidSetValue = 402;
-var G_ElementIsReadOnly = 403;
-var G_ElementIsWriteOnly = 404;
-var G_IncorrectDataType = 405;
-
+var G_InvalidArgumentError = 201;
+var G_ElementCannotHaveChildren = 202;
+var G_ElementIsNotAnArray = 203;
+var G_NotInitialized = 301;
+var G_NotImplementedError = 401;
+var G_InvalidSetValue = 402;
+var G_ElementIsReadOnly = 403;
+var G_ElementIsWriteOnly = 404;
+var G_IncorrectDataType = 405;
+
 // Error messages
-var G_NoErrorMessage 					= '';
-var G_GeneralExceptionMessage 			= 'General Exception';
+var G_NoErrorMessage 					= '';
+var G_GeneralExceptionMessage 			= 'General Exception';
 var G_ServerBusyMessage 				= 'Server busy'; // this is not in the Scorm1.2_Runtime document
-var G_InvalidArgumentErrorMessage 		= 'Invalid argument error';
-var G_ElementCannotHaveChildrenMessage 	= 'Element cannot have children';
-var G_ElementIsNotAnArrayMessage 		= 'Element not an array.  Cannot have count';
-var G_NotInitializedMessage 			= 'Not initialized';
-var G_NotImplementedErrorMessage 		= 'Not implemented error';
-var G_InvalidSetValueMessage 			= 'Invalid set value, element is a keyword';
-var G_ElementIsReadOnlyMessage 			= 'Element is read only';
-var G_ElementIsWriteOnlyMessage 		= 'Element is write only';
-var G_IncorrectDataTypeMessage 			= 'Incorrect Data Type';
-
-var G_LastError = G_NoError ;
-var G_LastErrorMessage = 'No error';
-//this is not necessary and is only provided to make bad Articulate contents shut up (and not trigger useless JS messages)
-var G_LastErrorString = 'No error';
-status_info=new Array();
-var commit = false ;
-
-var variables_scorm = new Array('cmi.core.score.raw','cmi.core.score.max','cmi.core.score.min','cmi.core.lesson_location',
-'cmi.core.lesson_status','cmi.completion_status','cmi.core.session_time','cmi.score.scaled','cmi.success_status',
-'cmi.suspend_data','cmi.core.exit','interactions');
-
-var variable_to_send=new Array();
-var updatetable_to_list=new Array();
-var info_of_variable_to_send=new Array();
-
-//Strictly scorm variables
-var score=<?php echo $oItem->get_score();?>;
-var max='<?php echo $oItem->get_max();?>';
-var min='<?php echo $oItem->get_min();?>';
-var lesson_status='<?php echo $oItem->get_status();?>';
-var session_time='<?php echo $oItem->get_scorm_time('js');?>';
-var suspend_data = '<?php echo $oItem->get_suspend_data();?>';
-var lesson_location = '<?php echo $oItem->get_lesson_location();?>';
-var total_time = '<?php echo $oItem->get_scorm_time('js');?>';
-var mastery_score = '<?php echo $oItem->get_mastery_score();?>';
-var launch_data = '<?php echo $oItem->get_launch_data();?>';
-var max_time_allowed = '<?php echo $oItem->get_max_time_allowed();?>';
-var interactions = new Array(<?php echo $oItem->get_interactions_js_array();?>);
-item_objectives = new Array();
-info_lms_item=new Array();
+var G_InvalidArgumentErrorMessage 		= 'Invalid argument error';
+var G_ElementCannotHaveChildrenMessage 	= 'Element cannot have children';
+var G_ElementIsNotAnArrayMessage 		= 'Element not an array.  Cannot have count';
+var G_NotInitializedMessage 			= 'Not initialized';
+var G_NotImplementedErrorMessage 		= 'Not implemented error';
+var G_InvalidSetValueMessage 			= 'Invalid set value, element is a keyword';
+var G_ElementIsReadOnlyMessage 			= 'Element is read only';
+var G_ElementIsWriteOnlyMessage 		= 'Element is write only';
+var G_IncorrectDataTypeMessage 			= 'Incorrect Data Type';
+
+var G_LastError = G_NoError ;
+var G_LastErrorMessage = 'No error';
+//this is not necessary and is only provided to make bad Articulate contents shut up (and not trigger useless JS messages)
+var G_LastErrorString = 'No error';
+status_info=new Array();
+var commit = false ;
+
+var variables_scorm = new Array('cmi.core.score.raw','cmi.core.score.max','cmi.core.score.min','cmi.core.lesson_location',
+'cmi.core.lesson_status','cmi.completion_status','cmi.core.session_time','cmi.score.scaled','cmi.success_status',
+'cmi.suspend_data','cmi.core.exit','interactions');
+
+var variable_to_send=new Array();
+var updatetable_to_list=new Array();
+var info_of_variable_to_send=new Array();
+
+//Strictly scorm variables
+var score=<?php echo $oItem->get_score();?>;
+var max='<?php echo $oItem->get_max();?>';
+var min='<?php echo $oItem->get_min();?>';
+var lesson_status='<?php echo $oItem->get_status();?>';
+var session_time='<?php echo $oItem->get_scorm_time('js');?>';
+var suspend_data = '<?php echo $oItem->get_suspend_data();?>';
+var lesson_location = '<?php echo $oItem->get_lesson_location();?>';
+var total_time = '<?php echo $oItem->get_scorm_time('js');?>';
+var mastery_score = '<?php echo $oItem->get_mastery_score();?>';
+var launch_data = '<?php echo $oItem->get_launch_data();?>';
+var max_time_allowed = '<?php echo $oItem->get_max_time_allowed();?>';
+var interactions = new Array(<?php echo $oItem->get_interactions_js_array();?>);
+item_objectives = new Array();
+info_lms_item=new Array();
 $(document).ready( function() {
-	info_lms_item[0]='<?php echo $oItem->get_id();?>';
-	info_lms_item[1]='<?php echo $oItem->get_id();?>';
+	info_lms_item[0]='<?php echo $oItem->get_id();?>';
+	info_lms_item[1]='<?php echo $oItem->get_id();?>';
 
-	$("#current_item_id").attr("value",<?php echo $oItem->get_id();?>);
+	$("#current_item_id").attr("value",<?php echo $oItem->get_id();?>);
 	$("#old_item").attr("value",<?php echo $oItem->get_id();?>);
 
-	//var myiframe=document.getElementById('content_id');
-	//myiframe.Events.AttachEvent("onclick", update_lp_item_id);
-	//myiframe.contentWindow.document.addEventListener("click", update_lp_item_id, false);
+	//var myiframe=document.getElementById('content_id');
+	//myiframe.Events.AttachEvent("onclick", update_lp_item_id);
+	//myiframe.contentWindow.document.addEventListener("click", update_lp_item_id, false);
 
  } );
 
 
 $(document).ready( function() {
- $("iframe#content_id").load( function(){
-  //alert("Document title: " + $("iframe#content_id").attr('src'));
-  info_lms_item[0]=info_lms_item[1];
-  info_lms_item[1]= info_lms_item[1];
- });
-});
-
-
-//Dokeos internal variables
-var saved_lesson_status = 'not attempted';
-var lms_lp_id = <?php echo $oLP->get_id();?>;
-var lms_item_id = <?php echo $oItem->get_id();?>;
-//var lms_new_item_id = 0; //temporary value (only there between a load_item() and a LMSInitialize())
-var lms_been_synchronized = 0;
-var lms_initialized = 0;
-var lms_total_lessons = <?php echo $oLP->get_total_items_count(); ?>;
-var lms_complete_lessons = <?php echo $oLP->get_complete_items_count();?>;
-var lms_progress_bar_mode = '<?php echo $oLP->progress_bar_mode;?>';
-if(lms_progress_bar_mode == ''){lms_progress_bar_mode='%';}
-var lms_view_id = '<?php echo $oLP->get_view();?>';
-if(lms_view_id == ''){ lms_view_id = 1;}
-var lms_user_id = '<?php echo $_user['user_id'];?>';
-var lms_next_item = '<?php echo $oLP->get_next_item_id();?>';
-var lms_previous_item = '<?php echo $oLP->get_previous_item_id();?>';
-var lms_lp_type = '<?php echo $oLP->get_type();?>';
-var lms_item_type = '<?php echo $oItem->get_type();?>';
-var lms_item_credit = '<?php echo $oItem->get_credit();?>';
-var lms_item_lesson_mode = '<?php echo $oItem->get_lesson_mode();?>';
-var lms_item_launch_data = '<?php echo $oItem->get_launch_data();?>';
-var lms_item_core_exit = '<?php echo $oItem->get_core_exit();?>';
-var asset_timer = 0;
-
-//Backup for old values
-var old_score = 0;
-var old_max = 0;
-var old_min = 0;
-var old_lesson_status = '';
-var old_session_time = '';
-var old_suspend_data = '';
-var lms_old_item_id = 0;
-
-var execute_stats='false';
-
-
-
-/**
- * Function called mandatorily by the SCORM content to start the SCORM communication
- */
-function LMSInitialize() {  //this is the initialize function of all APIobjects
-
-	/* load info for this new item by calling the js_api_refresh command in
+ $("iframe#content_id").load( function(){
+  //alert("Document title: " + $("iframe#content_id").attr('src'));
+  info_lms_item[0]=info_lms_item[1];
+  info_lms_item[1]= info_lms_item[1];
+ });
+});
+
+
+//Dokeos internal variables
+var saved_lesson_status = 'not attempted';
+var lms_lp_id = <?php echo $oLP->get_id();?>;
+var lms_item_id = <?php echo $oItem->get_id();?>;
+//var lms_new_item_id = 0; //temporary value (only there between a load_item() and a LMSInitialize())
+var lms_been_synchronized = 0;
+var lms_initialized = 0;
+var lms_total_lessons = <?php echo $oLP->get_total_items_count(); ?>;
+var lms_complete_lessons = <?php echo $oLP->get_complete_items_count();?>;
+var lms_progress_bar_mode = '<?php echo $oLP->progress_bar_mode;?>';
+if(lms_progress_bar_mode == ''){lms_progress_bar_mode='%';}
+var lms_view_id = '<?php echo $oLP->get_view();?>';
+if(lms_view_id == ''){ lms_view_id = 1;}
+var lms_user_id = '<?php echo $_user['user_id'];?>';
+var lms_next_item = '<?php echo $oLP->get_next_item_id();?>';
+var lms_previous_item = '<?php echo $oLP->get_previous_item_id();?>';
+var lms_lp_type = '<?php echo $oLP->get_type();?>';
+var lms_item_type = '<?php echo $oItem->get_type();?>';
+var lms_item_credit = '<?php echo $oItem->get_credit();?>';
+var lms_item_lesson_mode = '<?php echo $oItem->get_lesson_mode();?>';
+var lms_item_launch_data = '<?php echo $oItem->get_launch_data();?>';
+var lms_item_core_exit = '<?php echo $oItem->get_core_exit();?>';
+var asset_timer = 0;
+
+//Backup for old values
+var old_score = 0;
+var old_max = 0;
+var old_min = 0;
+var old_lesson_status = '';
+var old_session_time = '';
+var old_suspend_data = '';
+var lms_old_item_id = 0;
+
+var execute_stats='false';
+
+
+
+/**
+ * Function called mandatorily by the SCORM content to start the SCORM communication
+ */
+function LMSInitialize() {  //this is the initialize function of all APIobjects
+
+	/* load info for this new item by calling the js_api_refresh command in
 	 * the message frame. The message frame will update the JS variables by
 	 * itself, in JS, by doing things like top.lesson_status = 'not attempted'
-	 * and that kind of stuff, so when the content loads in the content frame
+	 * and that kind of stuff, so when the content loads in the content frame
 	 * it will have all the correct variables set
-	 */
-	G_LastError = G_NoError ;
+	 */
+	G_LastError = G_NoError ;
 	G_LastErrorMessage = 'No error';
-	//reinit to list
-	reinit_update_table_list ()
-
-	lms_initialized=0;
-	// if there are more parameters than ""
-	if (arguments.length>1) {
-		G_LastError 		= G_InvalidArgumentError;
-		G_LastErrorMessage 	= G_InvalidArgumentErrorMessage;
-		logit_scorm('Error '+ G_InvalidArgumentError + G_InvalidArgumentErrorMessage, 0);
-		return('false');
-	} else {
-		logit_scorm('LMSInitialise()',0);
-	lms_initialized=1;
-	return('true');
-	}
-}
-
+	//reinit to list
+	reinit_update_table_list ()
+
+	lms_initialized=0;
+	// if there are more parameters than ""
+	if (arguments.length>1) {
+		G_LastError 		= G_InvalidArgumentError;
+		G_LastErrorMessage 	= G_InvalidArgumentErrorMessage;
+		logit_scorm('Error '+ G_InvalidArgumentError + G_InvalidArgumentErrorMessage, 0);
+		return('false');
+	} else {
+		logit_scorm('LMSInitialise()',0);
+	lms_initialized=1;
+	return('true');
+	}
+}
+
 function Initialize()
-{  //this is the initialize function of all APIobjects
-  return LMSInitialize();
-}
-
+{  //this is the initialize function of all APIobjects
+  return LMSInitialize();
+}
+
 function LMSGetValue(param)
-{
-	//logit_scorm("LMSGetValue('"+param+"')",1);
-	G_LastError = G_NoError ;
+{
+	//logit_scorm("LMSGetValue('"+param+"')",1);
+	G_LastError = G_NoError ;
 	G_LastErrorMessage = 'No error';
-	var result='';
-
-	// the LMSInitialize is missing
-	if (lms_initialized == 0) {
+	var result='';
+
+	// the LMSInitialize is missing
+	if (lms_initialized == 0) {
 		 G_LastError 		= G_NotInitialized;
-		 G_LastErrorMessage = G_NotInitializedMessage;
-		 logit_scorm('Error '+ G_NotInitialized + ' ' +G_NotInitializedMessage, 0);
-		 return '';
-	}
-
-	//Dokeos does not support this SCO object properties
-
+		 G_LastErrorMessage = G_NotInitializedMessage;
+		 logit_scorm('Error '+ G_NotInitialized + ' ' +G_NotInitializedMessage, 0);
+		 return '';
+	}
+
+	//Dokeos does not support this SCO object properties
+
 	if (param == 'cmi.student_preference.text' ||
-		param == 'cmi.student_preference.language' ||
-		param == 'cmi.student_preference.speed' ||
-		param == 'cmi.student_preference.audio' ||
+		param == 'cmi.student_preference.language' ||
+		param == 'cmi.student_preference.speed' ||
+		param == 'cmi.student_preference.audio' ||
 		param == 'cmi.student_preference._children' ||
-		param == 'cmi.student_data.time_limit_action' ||
-		param == 'cmi.comments' ||
-		param == 'cmi.comments_from_lms' ) {
+		param == 'cmi.student_data.time_limit_action' ||
+		param == 'cmi.comments' ||
+		param == 'cmi.comments_from_lms' ) {
 		// the value is not supported
-		G_lastError = G_NotImplementedError  ;
-		G_lastErrorString = G_NotImplementedErrorMessage;
-		logit_scorm("LMSGetValue  ('"+param+"') Error '"+G_NotImplementedErrorMessage+"'",1);
-		result = '';
-		return result;
-	}
-
-	// ---- cmi.core._children
-	if(param=='cmi.core._children' || param=='cmi.core_children'){
-		result='entry, exit, lesson_status, student_id, student_name, lesson_location, total_time, credit, lesson_mode, score, session_time';
-	}else if(param == 'cmi.core.entry'){
-	// ---- cmi.core.entry
-		if(lms_item_core_exit=='none') {
-			result='ab-initio';
-		} else if(lms_item_core_exit=='suspend') {
-			result='resume';
-		} else {
-			result='';
-		}
-	}else if(param == 'cmi.core.exit'){
-	// ---- cmi.core.exit
-		result='';
-		G_LastError = G_ElementIsWriteOnly;
-	}else if(param == 'cmi.core.session_time'){
-		result='';
-		G_LastError = G_ElementIsWriteOnly;
-	}else if(param == 'cmi.core.lesson_status'){
-	// ---- cmi.core.lesson_status
-	    if(lesson_status != '') {
-	    	result=lesson_status;
-	    } else {
-	    	//result='not attempted';
-	    }
-	}else if(param == 'cmi.core.student_id'){
-	// ---- cmi.core.student_id
-		result='<?php echo $_user['user_id']; ?>';
-	}else if(param == 'cmi.core.student_name'){
-	// ---- cmi.core.student_name
-		  <?php
-			$who=addslashes(api_get_person_name($_user['firstName'], $_user['lastName']));
+		G_lastError = G_NotImplementedError  ;
+		G_lastErrorString = G_NotImplementedErrorMessage;
+		logit_scorm("LMSGetValue  ('"+param+"') Error '"+G_NotImplementedErrorMessage+"'",1);
+		result = '';
+		return result;
+	}
+
+	// ---- cmi.core._children
+	if(param=='cmi.core._children' || param=='cmi.core_children'){
+		result='entry, exit, lesson_status, student_id, student_name, lesson_location, total_time, credit, lesson_mode, score, session_time';
+	}else if(param == 'cmi.core.entry'){
+	// ---- cmi.core.entry
+		if(lms_item_core_exit=='none') {
+			result='ab-initio';
+		} else if(lms_item_core_exit=='suspend') {
+			result='resume';
+		} else {
+			result='';
+		}
+	}else if(param == 'cmi.core.exit'){
+	// ---- cmi.core.exit
+		result='';
+		G_LastError = G_ElementIsWriteOnly;
+	}else if(param == 'cmi.core.session_time'){
+		result='';
+		G_LastError = G_ElementIsWriteOnly;
+	}else if(param == 'cmi.core.lesson_status'){
+	// ---- cmi.core.lesson_status
+	    if(lesson_status != '') {
+	    	result=lesson_status;
+	    } else {
+	    	//result='not attempted';
+	    }
+	}else if(param == 'cmi.core.student_id'){
+	// ---- cmi.core.student_id
+		result='<?php echo $_user['user_id']; ?>';
+	}else if(param == 'cmi.core.student_name'){
+	// ---- cmi.core.student_name
+		  <?php
+			$who=addslashes(api_get_person_name($_user['firstName'], $_user['lastName']));
 		    echo "result='$who';";
-		  ?>
-	}else if(param == 'cmi.core.lesson_location'){
-	// ---- cmi.core.lesson_location
-		result=lesson_location;
-	}else if(param == 'cmi.core.total_time'){
-	// ---- cmi.core.total_time
-		result=total_time;
-	}else if(param == 'cmi.core.score._children'){
-	// ---- cmi.core.score._children
-		result='raw,min,max';
-	}else if(param == 'cmi.core.score.raw'){
-	// ---- cmi.core.score.raw
-		result=score;
-	}else if(param == 'cmi.core.score.max'){
-	// ---- cmi.core.score.max
-		result=max;
-	}else if(param == 'cmi.core.score.min'){
-	// ---- cmi.core.score.min
-		result=min;
-	}else if(param == 'cmi.core.score'){
-	// ---- cmi.core.score -- non-standard item, provided as cmi.core.score.raw just in case
-		result=score;
-	}else if(param == 'cmi.core.credit'){
-	// ---- cmi.core.credit
-		result = lms_item_credit;
-	}else if(param == 'cmi.core.lesson_mode'){
-	// ---- cmi.core.lesson_mode
-		result = lms_item_lesson_mode;
-	}else if(param == 'cmi.suspend_data'){
-	// ---- cmi.suspend_data
-		result = suspend_data;
-	}else if(param == 'cmi.launch_data'){
-	// ---- cmi.launch_data
-		result = lms_item_launch_data;
-	}else if(param == 'cmi.objectives._children'){
-	// ---- cmi.objectives._children
-		result = 'id,score,status';
-	}else if(param == 'cmi.objectives._count'){
-	// ---- cmi.objectives._count
-		//result='<?php echo $oItem->get_view_count();?>';
-		result = item_objectives.length;
-	}else if(param.substring(0,15)== 'cmi.objectives.'){
-		var myres = '';
-		if(myres = param.match(/cmi.objectives.(\d+).(id|score|status|_children)(.*)/))
-		{
-			var obj_id = myres[1];
-			var req_type = myres[2];
-			if(item_objectives[obj_id]==null)
-			{
-				if(req_type == 'id')
-				{
-					result = '';
-				}else if(req_type == '_children'){
-					result = 'id,score,status';
-				}else if(req_type == 'score'){
-					if(myres[3]==null)
-					{
-						result = '';
-						G_lastError = G_NotImplementedError;
-						G_lastErrorString = 'Not implemented yet';
-					}else if (myres[3] == '._children'){
-						result = 'raw,min,max'; //non-standard, added for NetG
-					}else if (myres[3] == '.raw'){
-						result = '';
-					}else if (myres[3] == '.max'){
-						result = '';
-					}else if (myres[3] == '.min'){
-						result = '';
-					}else{
-						result = '';
-						G_lastError = G_NotImplementedError;
-						G_lastErrorString = 'Not implemented yet';
-					}
-				}else if(req_type == 'status'){
-					result = 'not attempted';
-				}
-			}
-			else
-			{
-				//the object is not null
-				if(req_type == 'id')
-				{
-					result = item_objectives[obj_id][0];
-				}else if(req_type == '_children'){
-					result = 'id,score,status';
-				}else if(req_type == 'score'){
-					if(myres[3]==null)
-					{
-						result = '';
-						G_lastError = G_NotImplementedError;
-						G_lastErrorString = 'Not implemented yet';
-					}else if (myres[3] == '._children'){
-						result = 'raw,min,max'; //non-standard, added for NetG
-					}else if (myres[3] == '.raw'){
-						if(item_objectives[obj_id][2] != null)
-						{
-							result = item_objectives[obj_id][2];
-						}else{
-							result = '';
-						}
-					}else if (myres[3] == '.max'){
-						if(item_objectives[obj_id][3] != null)
-						{
-							result = item_objectives[obj_id][3];
-						}else{
-							result = '';
-						}
-					}else if (myres[3] == '.min'){
-						if(item_objectives[obj_id][4] != null)
-						{
-							result = item_objectives[obj_id][4];
-						}else{
-							result = '';
-						}
-					}else{
-						result = '';
-						G_lastError = G_NotImplementedError;
-						G_lastErrorString = 'Not implemented yet';
-					}
-				}else if(req_type == 'status'){
-					if(item_objectives[obj_id][1] != null)
-					{
-						result = item_objectives[obj_id][1];
-					}else{
-						result = 'not attempted';
-					}
-				}
-			}
-		}
-	}else if(param == 'cmi.student_data._children'){
-	// ---- cmi.student_data._children
-		result = 'mastery_score,max_time_allowed';
-	}else if(param == 'cmi.student_data.mastery_score'){
-	// ---- cmi.student_data.mastery_score
-		result = mastery_score;
-	}else if(param == 'cmi.student_data.max_time_allowed'){
-	// ---- cmi.student_data.max_time_allowed
-		result = max_time_allowed;
-	}else if(param == 'cmi.interactions._count'){
-	// ---- cmi.interactions._count
-		result = interactions.length;
-	}else if(param == 'cmi.interactions._children'){
-	// ---- cmi.interactions._children
-		result = 'id,time,type,correct_responses,weighting,student_response,result,latency';
-	}else{
-	// ---- anything else
-		// Invalid argument error
-		G_lastError = G_InvalidArgumentError ;
-		G_lastErrorString = G_InvalidArgumentErrorMessage;
-		logit_scorm("LMSGetValue  ('"+param+"') Error '"+G_InvalidArgumentErrorMessage+"'",1);
-		result = '';
-		return result;
-	}
-	logit_scorm("LMSGetValue\n\t('"+param+"') returned '"+result+"'",1);
-	return result;
-}
-
-function GetValue(param) {
-	return LMSGetValue(param);
-}
-
-function LMSSetValue(param, val) {
-
-	logit_scorm("LMSSetValue\n\t('"+param+"','"+val+"')",0);
-	commit = true; //value has changed, need to re-commit
-	G_LastError = G_NoError ;
+		  ?>
+	}else if(param == 'cmi.core.lesson_location'){
+	// ---- cmi.core.lesson_location
+		result=lesson_location;
+	}else if(param == 'cmi.core.total_time'){
+	// ---- cmi.core.total_time
+		result=total_time;
+	}else if(param == 'cmi.core.score._children'){
+	// ---- cmi.core.score._children
+		result='raw,min,max';
+	}else if(param == 'cmi.core.score.raw'){
+	// ---- cmi.core.score.raw
+		result=score;
+	}else if(param == 'cmi.core.score.max'){
+	// ---- cmi.core.score.max
+		result=max;
+	}else if(param == 'cmi.core.score.min'){
+	// ---- cmi.core.score.min
+		result=min;
+	}else if(param == 'cmi.core.score'){
+	// ---- cmi.core.score -- non-standard item, provided as cmi.core.score.raw just in case
+		result=score;
+	}else if(param == 'cmi.core.credit'){
+	// ---- cmi.core.credit
+		result = lms_item_credit;
+	}else if(param == 'cmi.core.lesson_mode'){
+	// ---- cmi.core.lesson_mode
+		result = lms_item_lesson_mode;
+	}else if(param == 'cmi.suspend_data'){
+	// ---- cmi.suspend_data
+		result = suspend_data;
+	}else if(param == 'cmi.launch_data'){
+	// ---- cmi.launch_data
+		result = lms_item_launch_data;
+	}else if(param == 'cmi.objectives._children'){
+	// ---- cmi.objectives._children
+		result = 'id,score,status';
+	}else if(param == 'cmi.objectives._count'){
+	// ---- cmi.objectives._count
+		//result='<?php echo $oItem->get_view_count();?>';
+		result = item_objectives.length;
+	}else if(param.substring(0,15)== 'cmi.objectives.'){
+		var myres = '';
+		if(myres = param.match(/cmi.objectives.(\d+).(id|score|status|_children)(.*)/))
+		{
+			var obj_id = myres[1];
+			var req_type = myres[2];
+			if(item_objectives[obj_id]==null)
+			{
+				if(req_type == 'id')
+				{
+					result = '';
+				}else if(req_type == '_children'){
+					result = 'id,score,status';
+				}else if(req_type == 'score'){
+					if(myres[3]==null)
+					{
+						result = '';
+						G_lastError = G_NotImplementedError;
+						G_lastErrorString = 'Not implemented yet';
+					}else if (myres[3] == '._children'){
+						result = 'raw,min,max'; //non-standard, added for NetG
+					}else if (myres[3] == '.raw'){
+						result = '';
+					}else if (myres[3] == '.max'){
+						result = '';
+					}else if (myres[3] == '.min'){
+						result = '';
+					}else{
+						result = '';
+						G_lastError = G_NotImplementedError;
+						G_lastErrorString = 'Not implemented yet';
+					}
+				}else if(req_type == 'status'){
+					result = 'not attempted';
+				}
+			}
+			else
+			{
+				//the object is not null
+				if(req_type == 'id')
+				{
+					result = item_objectives[obj_id][0];
+				}else if(req_type == '_children'){
+					result = 'id,score,status';
+				}else if(req_type == 'score'){
+					if(myres[3]==null)
+					{
+						result = '';
+						G_lastError = G_NotImplementedError;
+						G_lastErrorString = 'Not implemented yet';
+					}else if (myres[3] == '._children'){
+						result = 'raw,min,max'; //non-standard, added for NetG
+					}else if (myres[3] == '.raw'){
+						if(item_objectives[obj_id][2] != null)
+						{
+							result = item_objectives[obj_id][2];
+						}else{
+							result = '';
+						}
+					}else if (myres[3] == '.max'){
+						if(item_objectives[obj_id][3] != null)
+						{
+							result = item_objectives[obj_id][3];
+						}else{
+							result = '';
+						}
+					}else if (myres[3] == '.min'){
+						if(item_objectives[obj_id][4] != null)
+						{
+							result = item_objectives[obj_id][4];
+						}else{
+							result = '';
+						}
+					}else{
+						result = '';
+						G_lastError = G_NotImplementedError;
+						G_lastErrorString = 'Not implemented yet';
+					}
+				}else if(req_type == 'status'){
+					if(item_objectives[obj_id][1] != null)
+					{
+						result = item_objectives[obj_id][1];
+					}else{
+						result = 'not attempted';
+					}
+				}
+			}
+		}
+	}else if(param == 'cmi.student_data._children'){
+	// ---- cmi.student_data._children
+		result = 'mastery_score,max_time_allowed';
+	}else if(param == 'cmi.student_data.mastery_score'){
+	// ---- cmi.student_data.mastery_score
+		result = mastery_score;
+	}else if(param == 'cmi.student_data.max_time_allowed'){
+	// ---- cmi.student_data.max_time_allowed
+		result = max_time_allowed;
+	}else if(param == 'cmi.interactions._count'){
+	// ---- cmi.interactions._count
+		result = interactions.length;
+	}else if(param == 'cmi.interactions._children'){
+	// ---- cmi.interactions._children
+		result = 'id,time,type,correct_responses,weighting,student_response,result,latency';
+	}else{
+	// ---- anything else
+		// Invalid argument error
+		G_lastError = G_InvalidArgumentError ;
+		G_lastErrorString = G_InvalidArgumentErrorMessage;
+		logit_scorm("LMSGetValue  ('"+param+"') Error '"+G_InvalidArgumentErrorMessage+"'",1);
+		result = '';
+		return result;
+	}
+	logit_scorm("LMSGetValue\n\t('"+param+"') returned '"+result+"'",1);
+	return result;
+}
+
+function GetValue(param) {
+	return LMSGetValue(param);
+}
+
+function LMSSetValue(param, val) {
+
+	logit_scorm("LMSSetValue\n\t('"+param+"','"+val+"')",0);
+	commit = true; //value has changed, need to re-commit
+	G_LastError = G_NoError ;
 	G_LastErrorMessage = 'No error';
-	return_value = 'false';
-	if( param == "cmi.core.score.raw" ) {
+	return_value = 'false';
+	if( param == "cmi.core.score.raw" ) {
 		score= val;
-		updatetable_to_list['cmi.core.score.raw']='true';
-		return_value='true';
-	} else if ( param == "cmi.core.score.max" ) {
-		max = val;
-		updatetable_to_list['cmi.core.score.max']='true';
-		return_value='true';
-	} else if ( param == "cmi.core.score.min" ) {
-		min = val;
-		updatetable_to_list['cmi.core.score.min']='true';
-		return_value='true';
-	} else if ( param == "cmi.core.lesson_location" ) {
-		lesson_location = val;
-		updatetable_to_list['cmi.core.lesson_location']='true';
-		return_value='true';
-	} else if ( param == "cmi.core.lesson_status" ) {
-		saved_lesson_status = lesson_status;
-		lesson_status = val;
-		updatetable_to_list['cmi.core.lesson_status']='true';
-	    return_value='true';
-	} else if ( param == "cmi.completion_status" ) {
-		lesson_status = val;
-		updatetable_to_list['cmi.completion_status']='true';
-		return_value='true'; //1.3
-	} else if ( param == "cmi.core.session_time" ) {
+		updatetable_to_list['cmi.core.score.raw']='true';
+		return_value='true';
+	} else if ( param == "cmi.core.score.max" ) {
+		max = val;
+		updatetable_to_list['cmi.core.score.max']='true';
+		return_value='true';
+	} else if ( param == "cmi.core.score.min" ) {
+		min = val;
+		updatetable_to_list['cmi.core.score.min']='true';
+		return_value='true';
+	} else if ( param == "cmi.core.lesson_location" ) {
+		lesson_location = val;
+		updatetable_to_list['cmi.core.lesson_location']='true';
+		return_value='true';
+	} else if ( param == "cmi.core.lesson_status" ) {
+		saved_lesson_status = lesson_status;
+		lesson_status = val;
+		updatetable_to_list['cmi.core.lesson_status']='true';
+	    return_value='true';
+	} else if ( param == "cmi.completion_status" ) {
+		lesson_status = val;
+		updatetable_to_list['cmi.completion_status']='true';
+		return_value='true'; //1.3
+	} else if ( param == "cmi.core.session_time" ) {
 		session_time = val;
 		updatetable_to_list['cmi.core.session_time']='true';
-		return_value='true';
-	} else if ( param == "cmi.score.scaled") { //1.3
-		if(val<=1 && val>=-1) {
-			score = val ;
-			updatetable_to_list['cmi.score.scaled']='true';
-			return_value='true';
-		} else {
-			return_value='false';
-		}
-	} else if ( param == "cmi.success_status" ) {
-		success_status = val;
-		updatetable_to_list['cmi.success_status']='true';
-		return_value='true'; //1.3
-	} else if ( param == "cmi.suspend_data" ) {
-		suspend_data = val;
-		updatetable_to_list['cmi.suspend_data']='true';
-		return_value='true';
-	} else if ( param == "cmi.core.exit" ) {
-		lms_item_core_exit = val;
-		updatetable_to_list['cmi.core.exit']='true';
-		return_value='true';
-	} else if ( param == "cmi.core.student_id" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.core.student_name" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.core.credit" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.core.entry" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.core.total_time" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.core.lesson_mode" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.comments_from_lms" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.student_data.time_limit_action" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.student_data.mastery_score" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.student_data.max_time_allowed" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.student_preference._children" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else if ( param == "cmi.launch_data" ) {
-		G_LastError = G_ElementIsReadOnly;
-	} else {
-		var myres = new Array();
-		if(myres = param.match(/cmi.interactions.(\d+).(id|time|type|correct_responses|weighting|student_response|result|latency)(.*)/)) {
-			updatetable_to_list['interactions']='true';
-			elem_id = myres[1];
-			if(elem_id > interactions.length) //interactions setting should start at 0
-			{
-				/*
-				G_LastError = G_InvalidArgumentError;
-                G_LastErrorString = 'Invalid argument (interactions)';
-				return_value = false;
-                */
-                interactions[0] = ['0','','','','','','',''];
-			}
-			if(interactions[elem_id] == null){
-					interactions[elem_id] = ['','','','','','','',''];
-					//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
-					interactions[elem_id][4] = new Array();
-			}
-			elem_attrib = myres[2];
-			switch(elem_attrib) {
-					case "id":
-						interactions[elem_id][0] = val;
-						logit_scorm("Interaction "+elem_id+"'s id updated",2);
-						return_value='true';
-						break;
-					case "time":
-						interactions[elem_id][2] = val;
-						logit_scorm("Interaction "+elem_id+"'s time updated",2);
-						return_value='true';
-						break;
-					case "type":
-						interactions[elem_id][1] = val;
-						logit_scorm("Interaction "+elem_id+"'s type updated",2);
-						return_value='true';
-						break;
-					case "correct_responses":
-						//do nothing yet
-						interactions[elem_id][4].push(val);
-						logit_scorm("Interaction "+elem_id+"'s correct_responses not updated",2);
-						return_value='true';
-						break;
-					case "weighting":
-						interactions[elem_id][3] = val;
-						logit_scorm("Interaction "+elem_id+"'s weighting updated",2);
-						return_value='true';
-						break;
-					case "student_response":
-						interactions[elem_id][5] = ''+val;
-						logit_scorm("Interaction "+elem_id+"'s student_response updated",2);
-						return_value='true';
-						break;
-					case "result":
-						interactions[elem_id][6] = val;
-						logit_scorm("Interaction "+elem_id+"'s result updated",2);
-						return_value='true';
-						break;
-					case "latency":
-						interactions[elem_id][7] = val;
-						logit_scorm("Interaction "+elem_id+"'s latency updated",2);
-						return_value='true';
-						break;
-					default:
-							G_lastError = G_NotImplementedError;
-							G_lastErrorString = 'Not implemented yet';
-			}
-		}else if(param.substring(0,15)== 'cmi.objectives.'){
-			var myres = '';
-			updatetable_to_list['objectives']='true';
-			if(myres = param.match(/cmi.objectives.(\d+).(id|score|status)(.*)/))
-			{
-				obj_id = myres[1];
-				if(obj_id > item_objectives.length) //objectives setting should start at 0
-				{
-					G_LastError = G_InvalidArgumentError;
-                    G_LastErrorString = 'Invalid argument (objectives)';
-					return_value = false;
-				}
-				else
-				{
-					req_type = myres[2];
-					if(obj_id == null || obj_id == '')
-					{
-						;//do nothing
-					}
-					else
-					{
-						if(item_objectives[obj_id]==null)
-						{
-							item_objectives[obj_id] = ['','','','',''];
-						}
-						if( req_type == "id" ) {
-								//item_objectives[obj_id][0] = val.substring(51,57);
-								item_objectives[obj_id][0] = val;
-								logit_scorm("Objective "+obj_id+"'s id updated",2);
-								return_value = 'true';
-						} else if ( req_type == "score" ) {
-								if (myres[3] == '._children'){
-									return_value = '';
-									G_lastError = G_InvalidSetValue;
-									G_lastErrorString = 'Invalid set value, element is a keyword';
-								}else if (myres[3] == '.raw'){
-									item_objectives[obj_id][2] = val;
-									logit_scorm("Objective "+obj_id+"'s score raw updated",2);
-									return_value = 'true';
-								}else if (myres[3] == '.max'){
-									item_objectives[obj_id][3] = val;
-									logit_scorm("Objective "+obj_id+"'s score max updated",2);
-									return_value = 'true';
-								}else if (myres[3] == '.min'){
-									item_objectives[obj_id][4] = val;
-									logit_scorm("Objective "+obj_id+"'s score min updated",2);
-									return_value = 'true';
-								}else{
-									return_value = '';
-									G_lastError = G_NotImplementedError;
-									G_lastErrorString = 'Not implemented yet';
-								}
-						} else if ( req_type == "status" ) {
-								item_objectives[obj_id][1] = val;
-								logit_scorm("Objective "+obj_id+"'s status updated",2);
-								return_value = 'true';
-						} else {
-								G_lastError = G_NotImplementedError;
-								G_lastErrorString = 'Not implemented yet';
-						}
-					}
-				}
-			}
-		}else{
-			G_lastError = G_NotImplementedError;
-			G_lastErrorString = G_NotImplementedErrorMessage;
-		}
-	}
+		return_value='true';
+	} else if ( param == "cmi.score.scaled") { //1.3
+		if(val<=1 && val>=-1) {
+			score = val ;
+			updatetable_to_list['cmi.score.scaled']='true';
+			return_value='true';
+		} else {
+			return_value='false';
+		}
+	} else if ( param == "cmi.success_status" ) {
+		success_status = val;
+		updatetable_to_list['cmi.success_status']='true';
+		return_value='true'; //1.3
+	} else if ( param == "cmi.suspend_data" ) {
+		suspend_data = val;
+		updatetable_to_list['cmi.suspend_data']='true';
+		return_value='true';
+	} else if ( param == "cmi.core.exit" ) {
+		lms_item_core_exit = val;
+		updatetable_to_list['cmi.core.exit']='true';
+		return_value='true';
+	} else if ( param == "cmi.core.student_id" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.core.student_name" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.core.credit" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.core.entry" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.core.total_time" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.core.lesson_mode" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.comments_from_lms" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.student_data.time_limit_action" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.student_data.mastery_score" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.student_data.max_time_allowed" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.student_preference._children" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else if ( param == "cmi.launch_data" ) {
+		G_LastError = G_ElementIsReadOnly;
+	} else {
+		var myres = new Array();
+		if(myres = param.match(/cmi.interactions.(\d+).(id|time|type|correct_responses|weighting|student_response|result|latency)(.*)/)) {
+			updatetable_to_list['interactions']='true';
+			elem_id = myres[1];
+			if(elem_id > interactions.length) //interactions setting should start at 0
+			{
+				/*
+				G_LastError = G_InvalidArgumentError;
+                G_LastErrorString = 'Invalid argument (interactions)';
+				return_value = false;
+                */
+                interactions[0] = ['0','','','','','','',''];
+			}
+			if(interactions[elem_id] == null){
+					interactions[elem_id] = ['','','','','','','',''];
+					//id(0), type(1), time(2), weighting(3),correct_responses(4),student_response(5),result(6),latency(7)
+					interactions[elem_id][4] = new Array();
+			}
+			elem_attrib = myres[2];
+			switch(elem_attrib) {
+					case "id":
+						interactions[elem_id][0] = val;
+						logit_scorm("Interaction "+elem_id+"'s id updated",2);
+						return_value='true';
+						break;
+					case "time":
+						interactions[elem_id][2] = val;
+						logit_scorm("Interaction "+elem_id+"'s time updated",2);
+						return_value='true';
+						break;
+					case "type":
+						interactions[elem_id][1] = val;
+						logit_scorm("Interaction "+elem_id+"'s type updated",2);
+						return_value='true';
+						break;
+					case "correct_responses":
+						//do nothing yet
+						interactions[elem_id][4].push(val);
+						logit_scorm("Interaction "+elem_id+"'s correct_responses not updated",2);
+						return_value='true';
+						break;
+					case "weighting":
+						interactions[elem_id][3] = val;
+						logit_scorm("Interaction "+elem_id+"'s weighting updated",2);
+						return_value='true';
+						break;
+					case "student_response":
+						interactions[elem_id][5] = ''+val;
+						logit_scorm("Interaction "+elem_id+"'s student_response updated",2);
+						return_value='true';
+						break;
+					case "result":
+						interactions[elem_id][6] = val;
+						logit_scorm("Interaction "+elem_id+"'s result updated",2);
+						return_value='true';
+						break;
+					case "latency":
+						interactions[elem_id][7] = val;
+						logit_scorm("Interaction "+elem_id+"'s latency updated",2);
+						return_value='true';
+						break;
+					default:
+							G_lastError = G_NotImplementedError;
+							G_lastErrorString = 'Not implemented yet';
+			}
+		}else if(param.substring(0,15)== 'cmi.objectives.'){
+			var myres = '';
+			updatetable_to_list['objectives']='true';
+			if(myres = param.match(/cmi.objectives.(\d+).(id|score|status)(.*)/))
+			{
+				obj_id = myres[1];
+				if(obj_id > item_objectives.length) //objectives setting should start at 0
+				{
+					G_LastError = G_InvalidArgumentError;
+                    G_LastErrorString = 'Invalid argument (objectives)';
+					return_value = false;
+				}
+				else
+				{
+					req_type = myres[2];
+					if(obj_id == null || obj_id == '')
+					{
+						;//do nothing
+					}
+					else
+					{
+						if(item_objectives[obj_id]==null)
+						{
+							item_objectives[obj_id] = ['','','','',''];
+						}
+						if( req_type == "id" ) {
+								//item_objectives[obj_id][0] = val.substring(51,57);
+								item_objectives[obj_id][0] = val;
+								logit_scorm("Objective "+obj_id+"'s id updated",2);
+								return_value = 'true';
+						} else if ( req_type == "score" ) {
+								if (myres[3] == '._children'){
+									return_value = '';
+									G_lastError = G_InvalidSetValue;
+									G_lastErrorString = 'Invalid set value, element is a keyword';
+								}else if (myres[3] == '.raw'){
+									item_objectives[obj_id][2] = val;
+									logit_scorm("Objective "+obj_id+"'s score raw updated",2);
+									return_value = 'true';
+								}else if (myres[3] == '.max'){
+									item_objectives[obj_id][3] = val;
+									logit_scorm("Objective "+obj_id+"'s score max updated",2);
+									return_value = 'true';
+								}else if (myres[3] == '.min'){
+									item_objectives[obj_id][4] = val;
+									logit_scorm("Objective "+obj_id+"'s score min updated",2);
+									return_value = 'true';
+								}else{
+									return_value = '';
+									G_lastError = G_NotImplementedError;
+									G_lastErrorString = 'Not implemented yet';
+								}
+						} else if ( req_type == "status" ) {
+								item_objectives[obj_id][1] = val;
+								logit_scorm("Objective "+obj_id+"'s status updated",2);
+								return_value = 'true';
+						} else {
+								G_lastError = G_NotImplementedError;
+								G_lastErrorString = 'Not implemented yet';
+						}
+					}
+				}
+			}
+		}else{
+			G_lastError = G_NotImplementedError;
+			G_lastErrorString = G_NotImplementedErrorMessage;
+		}
+	}
 	<?php
-	if ($oLP->force_commit == 1){
-		echo "    var mycommit = LMSCommit('force');";
-	}
-	?>
-	return(return_value);
-}
-
-function SetValue(param, val) {
-	return LMSSetValue(param, val);
-}
-
-function ProcessValueScorm () {
-
-	for (i=0;i<variables_scorm.length;i++) {
-
-		if (updatetable_to_list[variables_scorm[i]]=='true') {
-			info_update_table=variables_scorm[i];
-			variable_to_send.push(info_update_table);
-		}
-	}
-
-	return variable_to_send;
-}
-
-function reinit_update_table_list () {
-
-	for (i=0;i<variables_scorm.length;i++) {
-
-		if (updatetable_to_list[variables_scorm[i]]=='true') {
-			updatetable_to_list[variables_scorm[i]]='false';
-		}
-	}
-	lesson_status='';
-
-}
-
+	if ($oLP->force_commit == 1){
+		echo "    var mycommit = LMSCommit('force');";
+	}
+	?>
+	return(return_value);
+}
+
+function SetValue(param, val) {
+	return LMSSetValue(param, val);
+}
+
+function ProcessValueScorm () {
+
+	for (i=0;i<variables_scorm.length;i++) {
+
+		if (updatetable_to_list[variables_scorm[i]]=='true') {
+			info_update_table=variables_scorm[i];
+			variable_to_send.push(info_update_table);
+		}
+	}
+
+	return variable_to_send;
+}
+
+function reinit_update_table_list () {
+
+	for (i=0;i<variables_scorm.length;i++) {
+
+		if (updatetable_to_list[variables_scorm[i]]=='true') {
+			updatetable_to_list[variables_scorm[i]]='false';
+		}
+	}
+	lesson_status='';
+
+}
+
 function savedata(origin) {
 	//origin can be 'commit', 'finish' or 'terminate'
-    if ((lesson_status != 'completed') && (lesson_status != 'passed') && (mastery_score >=0) && (score >= mastery_score)) {
-      lesson_status = 'passed';
-        updatetable_to_list['cmi.core.lesson_status']='true';
-    } else if( (mastery_score < 0) && (lms_lp_type != '2') && ( lesson_status == 'incomplete') && (score >= (0.8*max) ) ) {
-    	//the status cannot be modified automatically by the LMS under SCORM 1.2's rules
-    <?php if ($autocomplete_when_80pct){ ?>
-    	      lesson_status = 'completed';
-              updatetable_to_list['cmi.core.lesson_status']='true';
-    <?php }?>
-    ;
-    } else {
-        /*
-         * See notes in switch_item for why this has been disabled
-    	if ((origin== 'finish' || origin == 'unload') && lesson_status != 'completed' && lesson_status != 'passed' && lesson_status != 'browsed' && lesson_status != 'failed' && lesson_status != 'incomplete')  {
+    if ((lesson_status != 'completed') && (lesson_status != 'passed') && (mastery_score >=0) && (score >= mastery_score)) {
+      lesson_status = 'passed';
+        updatetable_to_list['cmi.core.lesson_status']='true';
+    } else if( (mastery_score < 0) && (lms_lp_type != '2') && ( lesson_status == 'incomplete') && (score >= (0.8*max) ) ) {
+    	//the status cannot be modified automatically by the LMS under SCORM 1.2's rules
+    <?php if ($autocomplete_when_80pct){ ?>
+    	      lesson_status = 'completed';
+              updatetable_to_list['cmi.core.lesson_status']='true';
+    <?php }?>
+    ;
+    } else {
+        /*
+         * See notes in switch_item for why this has been disabled
+    	if ((origin== 'finish' || origin == 'unload') && lesson_status != 'completed' && lesson_status != 'passed' && lesson_status != 'browsed' && lesson_status != 'failed' && lesson_status != 'incomplete')  {
 	    	// The SCORM1.2 Runtime object document says for the "cmi.core.lesson_status" variable:
 	    	// Upon receiving the LMSFinish() call or the user navigates away,
 	    	// the LMS should set the cmi.core.lesson_status for the SCO to 'completed'
-            logit_lms('the LMS did saving data (status='+lesson_status+' - interactions: '+ interactions.length +')',1);
+            logit_lms('the LMS did saving data (status='+lesson_status+' - interactions: '+ interactions.length +')',1);
 	    	if (mastery_score && mastery_score!= '' && score && score != '') {
-	    		if  (score >= mastery_score) {
-	    		  lesson_status = 'passed';
-	    		} else {
-	    		  lesson_status = 'failed';
-	    		}
-                updatetable_to_list['cmi.core.lesson_status']='true';
-	    	} else if (mastery_score && mastery_score!= '') {
-	    		lesson_status = 'completed';
-                updatetable_to_list['cmi.core.lesson_status']='true';
-	    	}
-    	}
-        */
-    }
-
-    my_get_value_scorm=new Array();
-    my_get_value_scorm=ProcessValueScorm();
-
-	logit_lms('saving data (status='+lesson_status+' - interactions: '+ interactions.length +')',1);
-
-	old_item_id=info_lms_item[0];
-	// xajax_save_item is replaced to xajax_save_item_scorm for scorm LP's
-	//xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location, interactions, lms_item_core_exit);
+	    		if  (score >= mastery_score) {
+	    		  lesson_status = 'passed';
+	    		} else {
+	    		  lesson_status = 'failed';
+	    		}
+                updatetable_to_list['cmi.core.lesson_status']='true';
+	    	} else if (mastery_score && mastery_score!= '') {
+	    		lesson_status = 'completed';
+                updatetable_to_list['cmi.core.lesson_status']='true';
+	    	}
+    	}
+        */
+    }
+
+    my_get_value_scorm=new Array();
+    my_get_value_scorm=ProcessValueScorm();
+
+	logit_lms('saving data (status='+lesson_status+' - interactions: '+ interactions.length +')',1);
+
+	old_item_id=info_lms_item[0];
+	// xajax_save_item is replaced to xajax_save_item_scorm for scorm LP's
+	//xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location, interactions, lms_item_core_exit);
 
 	xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, old_item_id,my_get_value_scorm);
-	//info_lms_item[0] is old_item_id and info_lms_item[1] is current_item_id
-	info_lms_item[0]=info_lms_item[0];
-	info_lms_item[1]=lms_item_id;
-
-	if(item_objectives.length>0) {
-		xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,old_item_id,item_objectives);
-	}
-	execute_stats='false';
-
-	//clean array
-	variable_to_send=new Array();
-	my_get_value_scorm=new Array();
-}
-/*
+	//info_lms_item[0] is old_item_id and info_lms_item[1] is current_item_id
+	info_lms_item[0]=info_lms_item[0];
+	info_lms_item[1]=lms_item_id;
+
+	if(item_objectives.length>0) {
+		xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,old_item_id,item_objectives);
+	}
+	execute_stats='false';
+
+	//clean array
+	variable_to_send=new Array();
+	my_get_value_scorm=new Array();
+}
+/*
  * See notes in switch_item for why this has been disabled
-function savedata_onunload() {
-	savedata('unload');
-}
-*/
-
-function LMSCommit(val) {
-	logit_scorm('LMSCommit()',0);
-	G_LastError = G_NoError ;
+function savedata_onunload() {
+	savedata('unload');
+}
+*/
+
+function LMSCommit(val) {
+	logit_scorm('LMSCommit()',0);
+	G_LastError = G_NoError ;
 	G_LastErrorMessage = 'No error';
-
-			savedata('commit');
-		reinit_update_table_list();
-	    //commit = 'false' ; //now changes have been commited, no need to update until next SetValue()
-	return('true');
-}
-
-function Commit(val) {
-	return LMSCommit(val);
-}
-
-function LMSFinish(val) {
-	G_LastError = G_NoError ;
+
+			savedata('commit');
+		reinit_update_table_list();
+	    //commit = 'false' ; //now changes have been commited, no need to update until next SetValue()
+	return('true');
+}
+
+function Commit(val) {
+	return LMSCommit(val);
+}
+
+function LMSFinish(val) {
+	G_LastError = G_NoError ;
 	G_LastErrorMessage = 'No error';
-	// why commit==false?
+	// why commit==false?
 	if (( commit == false )) {
 		logit_scorm('LMSFinish() (no LMSCommit())',1);
-
-	}
-
-		//if ( commit == true ) {
+
+	}
+
+		//if ( commit == true ) {
 			logit_scorm('LMSFinish() called',1);
-			savedata('finish');
-		    commit = 'false' ;
-		//}
+			savedata('finish');
+		    commit = 'false' ;
+		//}
 
-		//reinit to list
+		//reinit to list
 		reinit_update_table_list()
-		return('true');
-}
-
-function Finish(val) {
-	return LMSFinish(val);
-}
-
-function LMSGetLastError() {
-	logit_scorm('LMSGetLastError()',1);
-	return(G_LastError.toString());
-}
-
-function GetLastError() {
-	return LMSGetLastError();
-}
-
-function LMSGetErrorString(errCode){
-	logit_scorm('LMSGetErrorString()',1);
-	return(G_LastErrorString);
-}
-
-function GetErrorString(errCode){
-	return LMSGetErrorString(errCode);
-}
-
-function LMSGetDiagnostic(errCode){
-	logit_scorm('LMSGetDiagnostic()',1);
-	return(API.LMSGetLastError());
-}
-
-function GetDiagnostic(errCode){
-	return LMSGetDiagnostic(errCode);
-}
-
-function Terminate()
-{
-	if (lms_initialized == 0) {
+		return('true');
+}
+
+function Finish(val) {
+	return LMSFinish(val);
+}
+
+function LMSGetLastError() {
+	logit_scorm('LMSGetLastError()',1);
+	return(G_LastError.toString());
+}
+
+function GetLastError() {
+	return LMSGetLastError();
+}
+
+function LMSGetErrorString(errCode){
+	logit_scorm('LMSGetErrorString()',1);
+	return(G_LastErrorString);
+}
+
+function GetErrorString(errCode){
+	return LMSGetErrorString(errCode);
+}
+
+function LMSGetDiagnostic(errCode){
+	logit_scorm('LMSGetDiagnostic()',1);
+	return(API.LMSGetLastError());
+}
+
+function GetDiagnostic(errCode){
+	return LMSGetDiagnostic(errCode);
+}
+
+function Terminate()
+{
+	if (lms_initialized == 0) {
 		G_LastError 		= G_NotInitialized;
-		G_LastErrorMessage = G_NotInitializedMessage;
-		logit_scorm('Error '+ G_NotInitialized + G_NotInitializedMessage, 0);
-		return('false');
-	} else {
-		logit_scorm('Terminate()',0);
-		G_LastError = G_NoError ;
+		G_LastErrorMessage = G_NotInitializedMessage;
+		logit_scorm('Error '+ G_NotInitialized + G_NotInitializedMessage, 0);
+		return('false');
+	} else {
+		logit_scorm('Terminate()',0);
+		G_LastError = G_NoError ;
 		G_LastErrorMessage = 'No error';
-		commit = true;
-		savedata('terminate');
-		return (true);
-	}
-}
-<?php
-//--------------------------------------------------------------------//
-/**
- * Dokeos-specific code that deals with event handling and inter-frames
- * messaging/refreshing.
- * Note that from now on, the Dokeos JS code in this library will act as
- * a controller, of the MVC pattern, and receive all requests for frame
- * updates, then redispatch to any frame concerned.
- */
-?>
-/**
- * Defining the AJAX-object class to be made available from other frames
- */
-function XAJAXobject() {
-  this.xajax_switch_item_details=xajax_switch_item_details;
-  this.switch_item=switch_item;
-  this.xajax_save_objectives=xajax_save_objectives;
-  this.xajax_save_item = xajax_save_item;
-}
-
-//it is not sure that the scos use the above declarations
-
-oXAJAX = new XAJAXobject();
-oxajax = new XAJAXobject();
-
-/**
- * Cross-browser event handling by Scott Andrew
- * @param	element	Element that needs an event attached
- * @param   string	Event type (load, unload, click, keyDown, ...)
- * @param   string	Function name (the event handler)
- * @param   string	used in addEventListener
- */
-function addEvent(elm, evType, fn, useCapture){
-	if(elm.addEventListener){
-		elm.addEventListener(evType, fn, useCapture);
-		return true;
-	}else if (elm.attachEvent){
-		var r = elm.attachEvent('on' + evType, fn);
-	}else{
-		elm['on'+evType] = fn;
-	}
-}
-/**
- * Add listeners to the page objects. This has to be defined for
- * the current context as it acts on objects that should exist
+		commit = true;
+		savedata('terminate');
+		return (true);
+	}
+}
+<?php
+//--------------------------------------------------------------------//
+/**
+ * Dokeos-specific code that deals with event handling and inter-frames
+ * messaging/refreshing.
+ * Note that from now on, the Dokeos JS code in this library will act as
+ * a controller, of the MVC pattern, and receive all requests for frame
+ * updates, then redispatch to any frame concerned.
+ */
+?>
+/**
+ * Defining the AJAX-object class to be made available from other frames
+ */
+function XAJAXobject() {
+  this.xajax_switch_item_details=xajax_switch_item_details;
+  this.switch_item=switch_item;
+  this.xajax_save_objectives=xajax_save_objectives;
+  this.xajax_save_item = xajax_save_item;
+}
+
+//it is not sure that the scos use the above declarations
+
+oXAJAX = new XAJAXobject();
+oxajax = new XAJAXobject();
+
+/**
+ * Cross-browser event handling by Scott Andrew
+ * @param	element	Element that needs an event attached
+ * @param   string	Event type (load, unload, click, keyDown, ...)
+ * @param   string	Function name (the event handler)
+ * @param   string	used in addEventListener
+ */
+function addEvent(elm, evType, fn, useCapture){
+	if(elm.addEventListener){
+		elm.addEventListener(evType, fn, useCapture);
+		return true;
+	}else if (elm.attachEvent){
+		var r = elm.attachEvent('on' + evType, fn);
+	}else{
+		elm['on'+evType] = fn;
+	}
+}
+/**
+ * Add listeners to the page objects. This has to be defined for
+ * the current context as it acts on objects that should exist
  * on the page
- * possibly deprecated
- */
-function addListeners(){
-	//exit if the browser doesn't support ID or tag retrieval
-	logit_lms('Entering addListeners()',2);
-	if(!document.getElementsByTagName){
-		logit_lms("getElementsByTagName not available",2);
-		return;
-	}
-	if(!document.getElementById){
-		logit_lms("getElementById not available",2);
-		return;
-	}
-	//assign event handlers to objects
-	if(lms_lp_type==1 || lms_item_type=='asset'){
-		logit_lms('Dokeos LP or asset',2);
-		//if this path is a Dokeos learnpath, then start manual save
-		//when something is loaded in there
-		addEvent(window,'unload',dokeos_save_asset,false);
-		logit_lms('Added event listener on content_id for unload',2);
-	}
-    /* See notes in switch_item() for why this has been disabled
-    if (lms_lp_type==2) {
+ * possibly deprecated
+ */
+function addListeners(){
+	//exit if the browser doesn't support ID or tag retrieval
+	logit_lms('Entering addListeners()',2);
+	if(!document.getElementsByTagName){
+		logit_lms("getElementsByTagName not available",2);
+		return;
+	}
+	if(!document.getElementById){
+		logit_lms("getElementById not available",2);
+		return;
+	}
+	//assign event handlers to objects
+	if(lms_lp_type==1 || lms_item_type=='asset'){
+		logit_lms('Dokeos LP or asset',2);
+		//if this path is a Dokeos learnpath, then start manual save
+		//when something is loaded in there
+		addEvent(window,'unload',dokeos_save_asset,false);
+		logit_lms('Added event listener on content_id for unload',2);
+	}
+    /* See notes in switch_item() for why this has been disabled
+    if (lms_lp_type==2) {
         addEvent(window,'unload',savedata_onunload,false);
-	}
-    */
-	logit_lms('Quitting addListeners()',2);
-}
-
-/**
- * Load an item into the content frame:
- * - making sure the previous item status have been saved
+	}
+    */
+	logit_lms('Quitting addListeners()',2);
+}
+
+/**
+ * Load an item into the content frame:
+ * - making sure the previous item status have been saved
  * - first updating the current item ID (to save the right item)
- * - updating the frame src
- * possibly deprecated
- */
-function load_item(item_id,url){
-	if(document.getElementById('content_id')) {
-		logit_lms('Loading item '+item_id,2);
-		var cont_f = document.getElementById('content_id');
-		if(cont_f.src){
-			lms_old_item_id = lms_item_id;
-			var lms_new_item_id = item_id;
-			//load new content page into content frame
-			if(lms_lp_type==1 || lms_item_type=='asset'){
-				dokeos_save_asset();
-			}
-			cont_f.src = url;
-
-			update_toc('unhighlight',lms_old_item_id);
-			update_toc('highlight',lms_old_item_id);
-			return true;
-		}
-		logit_lms('cont_f.src has no properties',0);
-	}
-	logit_lms('content_id has no properties',0);
-	return false;
-}
-/**
- * Save a Dokeos learnpath item's time and mark as completed upon
- * leaving it
- */
-function dokeos_save_asset(){
-	// only for dokeos lps
-	if (execute_stats=='true') {
-		execute_stats='false';
-	} else {
-		execute_stats='true';
-	}
-
-	if(lms_lp_type==1 || lms_item_type=='asset'){
-		logit_lms('dokeos_save_asset',2);
-	    xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location,interactions, lms_item_core_exit);
-	    if(item_objectives.length>0)
-		{
-			xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,item_objectives);
-		}
-	}
-}
-/**
- * Save a Dokeos learnpath item's time and mark as completed upon leaving it.
- * Same function as dokeos_save_asset() but saves it with empty params
- * to use values set from another side in the database. Only used by Dokeos quizzes.
- * Also save the score locally because it hasn't been done through SetValue().
- * Saving the status will be dealt with by the XAJAX function.
- */
-function dokeos_void_save_asset(myscore,mymax)
-{
-	logit_lms('dokeos_save_asset',2);
-	score = myscore;
-	if((mymax == null) || (mymax == '')){mymax = 100;} //assume a default of 100, otherwise the score will not get saved (see lpi->set_score())
-    xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, myscore, mymax);
-}
-
-/**
- * Logs information about SCORM messages into the log frame
- * @param	string	Message to log
- * @param	integer Priority (0 for top priority, 3 for lowest)
- */
-function logit_scorm(message,priority){
-
-	if(scorm_logs>priority){
-		if($("#lp_log_name") && $("#log_content")){
-			$("#log_content").append("SCORM: " + message + "<br/>");
-		}
-	}
-
-}
-
-/**
- * Logs information about LMS activity into the log frame
- * @param	string	Message to log
- * @param	integer Priority (0 for top priority, 3 for lowest)
- */
-function logit_lms(message,priority){
-	if(lms_logs>priority){
-		if ($("#lp_log_name") && $("#log_content")) {
-			$("#log_content").append("LMS: " + message + "<br />");
-		}
-	}
-}
-
-/**
- * update the Table Of Contents frame, by changing CSS styles, mostly
- * @param	string	Action to be taken
- * @param	integer	Item id to update
- */
-function update_toc(update_action,update_id,change_ids)
-{
-        if (!change_ids || change_ids != 'no') {
-            change_ids = 'yes';
-        }
+ * - updating the frame src
+ * possibly deprecated
+ */
+function load_item(item_id,url){
+	if(document.getElementById('content_id')) {
+		logit_lms('Loading item '+item_id,2);
+		var cont_f = document.getElementById('content_id');
+		if(cont_f.src){
+			lms_old_item_id = lms_item_id;
+			var lms_new_item_id = item_id;
+			//load new content page into content frame
+			if(lms_lp_type==1 || lms_item_type=='asset'){
+				dokeos_save_asset();
+			}
+			cont_f.src = url;
+
+			update_toc('unhighlight',lms_old_item_id);
+			update_toc('highlight',lms_old_item_id);
+			return true;
+		}
+		logit_lms('cont_f.src has no properties',0);
+	}
+	logit_lms('content_id has no properties',0);
+	return false;
+}
+/**
+ * Save a Dokeos learnpath item's time and mark as completed upon
+ * leaving it
+ */
+function dokeos_save_asset(){
+	// only for dokeos lps
+	if (execute_stats=='true') {
+		execute_stats='false';
+	} else {
+		execute_stats='true';
+	}
+
+	if(lms_lp_type==1 || lms_item_type=='asset'){
+		logit_lms('dokeos_save_asset',2);
+	    xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location,interactions, lms_item_core_exit);
+	    if(item_objectives.length>0)
+		{
+			xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,item_objectives);
+		}
+	}
+}
+/**
+ * Save a Dokeos learnpath item's time and mark as completed upon leaving it.
+ * Same function as dokeos_save_asset() but saves it with empty params
+ * to use values set from another side in the database. Only used by Dokeos quizzes.
+ * Also save the score locally because it hasn't been done through SetValue().
+ * Saving the status will be dealt with by the XAJAX function.
+ */
+function dokeos_void_save_asset(myscore,mymax)
+{
+	logit_lms('dokeos_save_asset',2);
+	score = myscore;
+	if((mymax == null) || (mymax == '')){mymax = 100;} //assume a default of 100, otherwise the score will not get saved (see lpi->set_score())
+    xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, myscore, mymax);
+}
+
+/**
+ * Logs information about SCORM messages into the log frame
+ * @param	string	Message to log
+ * @param	integer Priority (0 for top priority, 3 for lowest)
+ */
+function logit_scorm(message,priority){
+
+	if(scorm_logs>priority){
+		if($("#lp_log_name") && $("#log_content")){
+			$("#log_content").append("SCORM: " + message + "<br/>");
+		}
+	}
+
+}
+
+/**
+ * Logs information about LMS activity into the log frame
+ * @param	string	Message to log
+ * @param	integer Priority (0 for top priority, 3 for lowest)
+ */
+function logit_lms(message,priority){
+	if(lms_logs>priority){
+		if ($("#lp_log_name") && $("#log_content")) {
+			$("#log_content").append("LMS: " + message + "<br />");
+		}
+	}
+}
+
+/**
+ * update the Table Of Contents frame, by changing CSS styles, mostly
+ * @param	string	Action to be taken
+ * @param	integer	Item id to update
+ */
+function update_toc(update_action,update_id,change_ids)
+{
+        if (!change_ids || change_ids != 'no') {
+            change_ids = 'yes';
+        }
 		var myelem = $("#toc_"+update_id);
 		var myelemimg = $("#toc_img_"+update_id);
-		logit_lms('update_toc("'+update_action+'",'+update_id+')',2);
-
-		if(update_id != 0)
-		{
-			switch(update_action)
-			{
-				case 'unhighlight':
-					if (update_id%2==0)
-					{
-						myelem.attr('class',"scorm_item_2");
-					}
-					else
-					{
-						myelem.attr('class',"scorm_item_1");
-					}
-					break;
-				case 'highlight':
-                    if (change_ids=='yes') {
-					   lms_next_item = update_id;
-					   lms_previous_item = update_id;
+		logit_lms('update_toc("'+update_action+'",'+update_id+')',2);
+
+		if(update_id != 0)
+		{
+			switch(update_action)
+			{
+				case 'unhighlight':
+					if (update_id%2==0)
+					{
+						myelem.attr('class',"scorm_item_2");
+					}
+					else
+					{
+						myelem.attr('class',"scorm_item_1");
+					}
+					break;
+				case 'highlight':
+                    if (change_ids=='yes') {
+					   lms_next_item = update_id;
+					   lms_previous_item = update_id;
                     }
-					myelem.attr('class',"scorm_item_highlight");
-					break;
-				case 'not attempted':
-					if( myelemimg.attr('src') != '../img/notattempted.gif') {
-						myelemimg.attr('src','../img/notattempted.gif');
+					myelem.attr('class',"scorm_item_highlight");
+					break;
+				case 'not attempted':
+					if( myelemimg.attr('src') != '../img/notattempted.gif') {
+						myelemimg.attr('src','../img/notattempted.gif');
 						myelemimg.attr('alt','n');
-					}
-					break;
-				case 'incomplete':
-					if( myelemimg.attr('src') != '../img/incomplete.gif') {
-						myelemimg.attr('src','../img/incomplete.gif');
+					}
+					break;
+				case 'incomplete':
+					if( myelemimg.attr('src') != '../img/incomplete.gif') {
+						myelemimg.attr('src','../img/incomplete.gif');
 						myelemimg.attr('alt','i');
-					}
-					break;
-				case 'completed':
-					if( myelemimg.attr('src') != '../img/completed.gif') {
-						myelemimg.attr('src','../img/completed.gif');
+					}
+					break;
+				case 'completed':
+					if( myelemimg.attr('src') != '../img/completed.gif') {
+						myelemimg.attr('src','../img/completed.gif');
 						myelemimg.attr('alt','c');
-					}
-					break;
-				case 'failed':
-					if( myelemimg.attr('src') != '../img/failed.gif') {
-						myelemimg.attr('src','../img/failed.gif');
+					}
+					break;
+				case 'failed':
+					if( myelemimg.attr('src') != '../img/failed.gif') {
+						myelemimg.attr('src','../img/failed.gif');
 						myelemimg.attr('alt','f');
-					}
-					break;
-				case 'passed':
-					if( myelemimg.attr('src') != '../img/completed.gif' && myelemimg.attr('alt') != 'passed') {
-						myelemimg.attr('src','../img/completed.gif');
+					}
+					break;
+				case 'passed':
+					if( myelemimg.attr('src') != '../img/completed.gif' && myelemimg.attr('alt') != 'passed') {
+						myelemimg.attr('src','../img/completed.gif');
 						myelemimg.attr('alt','p');
-					}
-					break;
-				case 'browsed':
-					if( myelemimg.attr('src') != '../img/completed.gif' && myelemimg.attr('alt') != 'browsed') {
-						myelemimg.attr('src','../img/completed.gif');
+					}
+					break;
+				case 'browsed':
+					if( myelemimg.attr('src') != '../img/completed.gif' && myelemimg.attr('alt') != 'browsed') {
+						myelemimg.attr('src','../img/completed.gif');
 						myelemimg.attr('alt','b');
-					}
-					break;
-				default:
-					logit_lms('Update action unknown',2);
-					break;
-			}
-		}
-		return true;
-}
-
-function update_stats() {
-	if (execute_stats=='true') {
-		try {
-		cont_f = document.getElementById('content_id');
-		cont_f.src="lp_controller.php?action=stats";
-		cont_f.reload();
-		} catch (e) {
-			return false;
+					}
+					break;
+				default:
+					logit_lms('Update action unknown',2);
+					break;
+			}
 		}
-	}
-	execute_stats='false';
-}
-/**
- * Updates the progress bar with the new status. Prevents the need of a page refresh and flickering
- * @param	integer	Number of completed items
- * @param	integer	Number of items in total
- * @param	string  Display mode (absolute 'abs' or percentage '%').Defaults to %
- */
-function update_progress_bar(nbr_complete, nbr_total, mode)
-{
-	logit_lms('update_progress_bar('+nbr_complete+','+nbr_total+','+mode+')',2);
-	logit_lms('could update with data: '+lms_lp_id+','+lms_view_id+','+lms_user_id,2);
-
-		if(mode == ''){mode='%';}
-		if(nbr_total == 0){nbr_total=1;}
-		var percentage = (nbr_complete/nbr_total)*100;
-		percentage = Math.round(percentage);
-
-	var pr_text  = $("#progress_text");
+		return true;
+}
+
+function update_stats() {
+	if (execute_stats=='true') {
+		try {
+		cont_f = document.getElementById('content_id');
+		cont_f.src="lp_controller.php?action=stats";
+		cont_f.reload();
+		} catch (e) {
+			return false;
+		}
+	}
+	execute_stats='false';
+}
+/**
+ * Updates the progress bar with the new status. Prevents the need of a page refresh and flickering
+ * @param	integer	Number of completed items
+ * @param	integer	Number of items in total
+ * @param	string  Display mode (absolute 'abs' or percentage '%').Defaults to %
+ */
+function update_progress_bar(nbr_complete, nbr_total, mode)
+{
+	logit_lms('update_progress_bar('+nbr_complete+','+nbr_total+','+mode+')',2);
+	logit_lms('could update with data: '+lms_lp_id+','+lms_view_id+','+lms_user_id,2);
+
+		if(mode == ''){mode='%';}
+		if(nbr_total == 0){nbr_total=1;}
+		var percentage = (nbr_complete/nbr_total)*100;
+		percentage = Math.round(percentage);
+
+	var pr_text  = $("#progress_text");
 	var pr_full  = $("#progress_img_full");
-	var pr_empty = $("#progress_img_empty");
+	var pr_empty = $("#progress_img_empty");
 
 	pr_full.attr('width',percentage*1.2);
-	pr_empty.attr('width',(100-percentage)*1.2);
-
-		var mytext = '';
-		switch(mode){
-			case 'abs':
-				mytext = nbr_complete + '/' + nbr_total;
-				break;
-			case '%':
-			default:
+	pr_empty.attr('width',(100-percentage)*1.2);
+
+		var mytext = '';
+		switch(mode){
+			case 'abs':
+				mytext = nbr_complete + '/' + nbr_total;
+				break;
+			case '%':
+			default:
 				mytext = percentage + '%';
-				break;
-		}
-	pr_text.html(mytext);
-
-	return true;
-}
-
-function update_stats_page()
-{
-	var myframe = document.getElementById('content_id');
-	var mysrc = myframe.location.href;
-	if(mysrc == 'lp_controller.php?action=stats'){
-		if(myframe && myframe.src){
-			var mysrc = myframe.src;
-			myframe.src = mysrc;
-		}
-		// = mysrc; //refresh page
-	}
-	return true;
-}
-/**
- * Updates the message frame with the given string
- */
-function update_message_frame(msg_msg)
-{
-	if(msg_msg==null){msg_msg='';}
-	if(!($("#msg_div_id"))){
-		logit_lms('In update_message_frame() - message frame has no document property',0);
-	}else{
-		logit_lms('In update_message_frame() - updating frame',0);
+				break;
+		}
+	pr_text.html(mytext);
+
+	return true;
+}
+
+function update_stats_page()
+{
+	var myframe = document.getElementById('content_id');
+	var mysrc = myframe.location.href;
+	if(mysrc == 'lp_controller.php?action=stats'){
+		if(myframe && myframe.src){
+			var mysrc = myframe.src;
+			myframe.src = mysrc;
+		}
+		// = mysrc; //refresh page
+	}
+	return true;
+}
+/**
+ * Updates the message frame with the given string
+ */
+function update_message_frame(msg_msg)
+{
+	if(msg_msg==null){msg_msg='';}
+	if(!($("#msg_div_id"))){
+		logit_lms('In update_message_frame() - message frame has no document property',0);
+	}else{
+		logit_lms('In update_message_frame() - updating frame',0);
 		$("#msg_div_id").html(msg_msg);
-	}
-}
-/**
- * Function that handles the saving of an item and switching from an item to another.
- * Once called, this function should be able to do the whole process of
- * (1) saving the current item,
- * (2) refresh all the values inside the SCORM API object,
- * (3) open the new item into the content_id frame,
- * (4) refresh the table of contents
- * (5) refresh the progress bar (completion)
- * (6) refresh the message frame
- * @param	integer		Dokeos ID for the current item
+	}
+}
+/**
+ * Function that handles the saving of an item and switching from an item to another.
+ * Once called, this function should be able to do the whole process of
+ * (1) saving the current item,
+ * (2) refresh all the values inside the SCORM API object,
+ * (3) open the new item into the content_id frame,
+ * (4) refresh the table of contents
+ * (5) refresh the progress bar (completion)
+ * (6) refresh the message frame
+ * @param	integer		Dokeos ID for the current item
  * @param	string		This parameter can be a string specifying the next
  *						item (like 'next', 'previous', 'first' or 'last') or the id to the next item
- */
-
-function switch_item(current_item, next_item){
-    //backup these params
-    var orig_current_item = current_item;
-    var orig_next_item = next_item;
-    var orig_lesson_status = lesson_status;
-	//(1) save the current item
-	logit_lms('Called switch_item with params '+lms_item_id+' and '+next_item+'',0);
-	if(lms_lp_type==1 || lms_item_type=='asset' || session_time == '0' || session_time == '0:00:00'){
-		if (lms_lp_type==1) {
+ */
+
+function switch_item(current_item, next_item){
+    //backup these params
+    var orig_current_item = current_item;
+    var orig_next_item = next_item;
+    var orig_lesson_status = lesson_status;
+	//(1) save the current item
+	logit_lms('Called switch_item with params '+lms_item_id+' and '+next_item+'',0);
+	if(lms_lp_type==1 || lms_item_type=='asset' || session_time == '0' || session_time == '0:00:00'){
+		if (lms_lp_type==1) {
 		xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, asset_timer, suspend_data, lesson_location,interactions, lms_item_core_exit);
-		} else {
-			my_get_value_scorm=new Array();
-    		my_get_value_scorm=ProcessValueScorm();
-        	xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, lms_item_id,my_get_value_scorm);
-        }
-		if(item_objectives.length>0) {
-		xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,item_objectives);
-	}
-	}else{
+		} else {
+			my_get_value_scorm=new Array();
+    		my_get_value_scorm=ProcessValueScorm();
+        	xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, lms_item_id,my_get_value_scorm);
+        }
+		if(item_objectives.length>0) {
+		xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,item_objectives);
+	}
+	}else{
         /**
-         * Because of SCORM 1.2's special rule about unsent commits and the fact
+         * Because of SCORM 1.2's special rule about unsent commits and the fact
          * that a SCO should be SET TO 'completed' IF NO STATUS WAS SENT (and
          * then some checks have to be done on score), we have to force a
-         * special commit here to avoid getting to the next element with a
-         * missing prerequisite. The 'onunload' event is treated with
+         * special commit here to avoid getting to the next element with a
+         * missing prerequisite. The 'onunload' event is treated with
          * savedata_onunload(), and doesn't need to be triggered at any
-         * particular time, but here we are in the case of switching to another
-         * item, so this is particularly important to complete the element in
-         * time.
-         * However, this cannot be initiated from the JavaScript, mainly
-         * because another onunload event can be triggered by the SCO itself,
-         * which can set, for example, the status to incomplete while the
-         * status has already been set to "completed" by the hand-made
+         * particular time, but here we are in the case of switching to another
+         * item, so this is particularly important to complete the element in
+         * time.
+         * However, this cannot be initiated from the JavaScript, mainly
+         * because another onunload event can be triggered by the SCO itself,
+         * which can set, for example, the status to incomplete while the
+         * status has already been set to "completed" by the hand-made
          * savedata(unload) (and then the status cannot be "incompleted"
-         * anymore)
-         */
-        //if (lms_item_type=='sco' && lesson_status != 'completed' && lesson_status != 'passed' && lesson_status != 'browsed' && lesson_status != 'incomplete' && lesson_status != 'failed') {
+         * anymore)
+         */
+        //if (lms_item_type=='sco' && lesson_status != 'completed' && lesson_status != 'passed' && lesson_status != 'browsed' && lesson_status != 'incomplete' && lesson_status != 'failed') {
             /**
-             * savedata('finish') treats the special condition and saves the
-             * new status to the database, so switch_item_details() enjoys the
-             * new status
-             */
+             * savedata('finish') treats the special condition and saves the
+             * new status to the database, so switch_item_details() enjoys the
+             * new status
+             */
         	//savedata('finish');
-        //}
-       // xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location,interactions, lms_item_core_exit);
-
-	}
-	execute_stats=false;
-	//(2) Refresh all the values inside this SCORM API object - use AJAX
-	xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,next_item);
-
-	status_info.push(lesson_status);
-
-	//current item
-
-	//old item
-	//info_lms_item[0]=next_item;
-
-	if (info_lms_item[1]==next_item && next_item!='next' && next_item!='previous') {
-		info_lms_item[0]=next_item;
-		info_lms_item[1]=next_item;
-	} else {
-		if (next_item!='next' && next_item!='previous') {
-			info_lms_item[0]=info_lms_item[1];
-			info_lms_item[1]=next_item;
-		}
-	}
-
-	if (info_lms_item[0]==next_item && next_item!='next' && next_item!='previous') {
-		info_lms_item[0]=next_item;
-		info_lms_item[1]=next_item;
-	} else {
-		if (next_item!='next' && next_item!='previous') {
-			info_lms_item[0]=info_lms_item[0];
-			info_lms_item[1]=next_item;
+        //}
+       // xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location,interactions, lms_item_core_exit);
+
+	}
+	execute_stats=false;
+	//(2) Refresh all the values inside this SCORM API object - use AJAX
+	xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,next_item);
+
+	status_info.push(lesson_status);
+
+	//current item
+
+	//old item
+	//info_lms_item[0]=next_item;
+
+	if (info_lms_item[1]==next_item && next_item!='next' && next_item!='previous') {
+		info_lms_item[0]=next_item;
+		info_lms_item[1]=next_item;
+	} else {
+		if (next_item!='next' && next_item!='previous') {
+			info_lms_item[0]=info_lms_item[1];
+			info_lms_item[1]=next_item;
+		}
+	}
+
+	if (info_lms_item[0]==next_item && next_item!='next' && next_item!='previous') {
+		info_lms_item[0]=next_item;
+		info_lms_item[1]=next_item;
+	} else {
+		if (next_item!='next' && next_item!='previous') {
+			info_lms_item[0]=info_lms_item[0];
+			info_lms_item[1]=next_item;
 		}
-	}
-
-	//(3) open the new item in the content_id frame
-	switch(next_item){
-		case 'next':
-			next_item = lms_next_item;
-			info_lms_item[0]=info_lms_item[1];
-			info_lms_item[1]=lms_next_item;
-			break;
-		case 'previous':
-			next_item = lms_previous_item;
-			info_lms_item[0]=info_lms_item[1];
-			info_lms_item[1]=lms_previous_item;
-			break;
-		default:
-			break;
-	}
-	var mysrc = 'lp_controller.php?action=content&lp_id='+lms_lp_id+'&item_id='+next_item;
+	}
+
+	//(3) open the new item in the content_id frame
+	switch(next_item){
+		case 'next':
+			next_item = lms_next_item;
+			info_lms_item[0]=info_lms_item[1];
+			info_lms_item[1]=lms_next_item;
+			break;
+		case 'previous':
+			next_item = lms_previous_item;
+			info_lms_item[0]=info_lms_item[1];
+			info_lms_item[1]=lms_previous_item;
+			break;
+		default:
+			break;
+	}
+	var mysrc = 'lp_controller.php?action=content&lp_id='+lms_lp_id+'&item_id='+next_item;
 	var cont_f = $("#content_id");
 
-		<?php if($oLP->mode == 'fullscreen'){ ?>
-	cont_f = window.open(''+mysrc,'content_id','toolbar=0,location=0,status=0,scrollbars=1,resizable=1');
-	cont_f.onload=function(){
-		info_lms_item[0]=info_lms_item[1];
-		info_lms_item[1]= info_lms_item[1];
-	}
-
-	cont_f.onunload=function(){
-		info_lms_item[0]=info_lms_item[1];
-		info_lms_item[1]= info_lms_item[1];
-	}
-
-		<?php } else { ?>
+		<?php if($oLP->mode == 'fullscreen'){ ?>
+	cont_f = window.open(''+mysrc,'content_id','toolbar=0,location=0,status=0,scrollbars=1,resizable=1');
+	cont_f.onload=function(){
+		info_lms_item[0]=info_lms_item[1];
+		info_lms_item[1]= info_lms_item[1];
+	}
+
+	cont_f.onunload=function(){
+		info_lms_item[0]=info_lms_item[1];
+		info_lms_item[1]= info_lms_item[1];
+	}
+
+		<?php } else { ?>
 			cont_f.attr("src",mysrc);
-	<?php } ?>
+	<?php } ?>
 
-	if(lms_lp_type==1 || lms_item_type=='asset'){
-		xajax_start_timer();
+	if(lms_lp_type==1 || lms_item_type=='asset'){
+		xajax_start_timer();
 	}
 
 	//(4) refresh the audio player if needed
 	$.ajax({
-		type: "GET",
-		url: "lp_nav.php",
-		data: "",
-		success: function(tmp_data) {
+		type: "GET",
+		url: "lp_nav.php",
+		data: "",
+		success: function(tmp_data) {
 		 		$("#media").html(tmp_data);
-	}
+	}
   	});
-/*
-    if ( lms_lp_type==2 && (orig_lesson_status == 'not attempted' || orig_lesson_status == '') && orig_current_item != orig_next_item) {
-        params = 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id+'&iid='+orig_current_item;
-        $.ajax({
-        type:"GET",
-        data: params,
+/*
+    if ( lms_lp_type==2 && (orig_lesson_status == 'not attempted' || orig_lesson_status == '') && orig_current_item != orig_next_item) {
+        params = 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id+'&iid='+orig_current_item;
+        $.ajax({
+        type:"GET",
+        data: params,
         url: "lp_ajax_last_update_status.php",
-        dataType: "script"
-        });
-    }
-*/
-	return true;
-}
-/**
- * Save a specific item (with its interactions, if any) into the LMS through
- * an AJAX call. Originally, we used the xajax library. Now we use jQuery.
- * Because of the need to pass an array, we have to build the parameters
- * manually into GET[]
- */
-function xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location, interactions, lms_item_core_exit) {
-        params='';
-        params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id;
-        params += '&iid='+lms_item_id+'&s='+score+'&max='+max+'&min='+min;
-        params += '&status='+lesson_status+'&t='+session_time;
-        params += '&suspend='+suspend_data+'&loc='+lesson_location;
-        params += '&core_exit='+lms_item_core_exit;
-        interact_string = '';
-        for (i in interactions){
-        	interact_string += '&interact['+i+']=';
-            interact_temp = '[';
-            for (j in interactions[i]) {
-            	interact_temp += interactions[i][j]+',';
-            }
-            interact_temp = interact_temp.substr(0,(interact_temp.length-2)) + ']';
-            interact_string += encodeURIComponent(interact_temp);
-        }
-        //interact_string = encodeURIComponent(interact_string.substr(0,(interact_string.length-1)));
-        params += interact_string;
-        /*params = {
-            'lid': lms_lp_id,
-            'uid': lms_user_id,
-            'vid': lms_view_id,
-            'iid': lms_item_id,
-            's': score,
-            'max': max,
-            'min': min,
+        dataType: "script"
+        });
+    }
+*/
+	return true;
+}
+/**
+ * Save a specific item (with its interactions, if any) into the LMS through
+ * an AJAX call. Originally, we used the xajax library. Now we use jQuery.
+ * Because of the need to pass an array, we have to build the parameters
+ * manually into GET[]
+ */
+function xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score, max, min, lesson_status, session_time, suspend_data, lesson_location, interactions, lms_item_core_exit) {
+        params='';
+        params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id;
+        params += '&iid='+lms_item_id+'&s='+score+'&max='+max+'&min='+min;
+        params += '&status='+lesson_status+'&t='+session_time;
+        params += '&suspend='+suspend_data+'&loc='+lesson_location;
+        params += '&core_exit='+lms_item_core_exit;
+        interact_string = '';
+        for (i in interactions){
+        	interact_string += '&interact['+i+']=';
+            interact_temp = '[';
+            for (j in interactions[i]) {
+            	interact_temp += interactions[i][j]+',';
+            }
+            interact_temp = interact_temp.substr(0,(interact_temp.length-2)) + ']';
+            interact_string += encodeURIComponent(interact_temp);
+        }
+        //interact_string = encodeURIComponent(interact_string.substr(0,(interact_string.length-1)));
+        params += interact_string;
+        /*params = {
+            'lid': lms_lp_id,
+            'uid': lms_user_id,
+            'vid': lms_view_id,
+            'iid': lms_item_id,
+            's': score,
+            'max': max,
+            'min': min,
             'status': lesson_status,
             't': session_time,
-            'suspend': suspend_data,
-            'loc': lesson_location,
+            'suspend': suspend_data,
+            'loc': lesson_location,
             'interact': interac_string,
-            'core_exit': lms_item_core_exit
-        }
-        */
-       if ( lms_lp_type==1) {
-          $.ajax({
-            type:"GET",
-            data: params,
+            'core_exit': lms_item_core_exit
+        }
+        */
+       if ( lms_lp_type==1) {
+          $.ajax({
+            type:"GET",
+            data: params,
             url: "lp_ajax_save_item.php",
-            dataType: "script",
-            async: false
-            }
+            dataType: "script",
+            async: false
+            }
         );
-       }
-}
-
-function xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, lms_item_id,info_get_lms) {
-
-// var variables_scorm = new Array('cmi.core.score.raw','cmi.core.score.max','cmi.core.score.min','cmi.core.lesson_location',
-//'cmi.core.lesson_status','cmi.completion_status','cmi.core.session_time','cmi.score.scaled','cmi.success_status',
-//'cmi.suspend_data','cmi.core.exit','interactions');
-
+       }
+}
+
+function xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, lms_item_id,info_get_lms) {
+
+// var variables_scorm = new Array('cmi.core.score.raw','cmi.core.score.max','cmi.core.score.min','cmi.core.lesson_location',
+//'cmi.core.lesson_status','cmi.completion_status','cmi.core.session_time','cmi.score.scaled','cmi.success_status',
+//'cmi.suspend_data','cmi.core.exit','interactions');
+
 	var is_interactions='false';
-	var params='';
-	params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id+'&iid='+lms_item_id;
-
-	for (k=0;k<info_get_lms.length;k++) {
-		if (my_get_value_scorm[k]=='cmi.core.session_time') {
-			params += '&t='+session_time;
-		} else if (my_get_value_scorm[k]=='cmi.core.lesson_status' && lesson_status!='') {
-			 params += '&status='+lesson_status;
-		} else if (my_get_value_scorm[k]=='cmi.core.score.raw') {
-			 params += '&s='+score;
-		} else if (my_get_value_scorm[k]=='cmi.core.score.max') {
+	var params='';
+	params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id+'&iid='+lms_item_id;
+
+	for (k=0;k<info_get_lms.length;k++) {
+		if (my_get_value_scorm[k]=='cmi.core.session_time') {
+			params += '&t='+session_time;
+		} else if (my_get_value_scorm[k]=='cmi.core.lesson_status' && lesson_status!='') {
+			 params += '&status='+lesson_status;
+		} else if (my_get_value_scorm[k]=='cmi.core.score.raw') {
+			 params += '&s='+score;
+		} else if (my_get_value_scorm[k]=='cmi.core.score.max') {
         	params += '&max='+max;
-		} else if (my_get_value_scorm[k]=='cmi.core.score.min') {
+		} else if (my_get_value_scorm[k]=='cmi.core.score.min') {
 	        params += '&min='+min;
-		} else if (my_get_value_scorm[k]=='cmi.core.lesson_location') {
+		} else if (my_get_value_scorm[k]=='cmi.core.lesson_location') {
 	        params += '&loc='+lesson_location;
-		} else if (my_get_value_scorm[k]=='cmi.completion_status') {
+		} else if (my_get_value_scorm[k]=='cmi.completion_status') {
 
-		} else if (my_get_value_scorm[k]=='cmi.score.scaled') {
+		} else if (my_get_value_scorm[k]=='cmi.score.scaled') {
 
-		} else if (my_get_value_scorm[k]=='cmi.suspend_data') {
+		} else if (my_get_value_scorm[k]=='cmi.suspend_data') {
 	        params += '&suspend='+suspend_data;
-		} else if (my_get_value_scorm[k]=='cmi.completion_status') {
+		} else if (my_get_value_scorm[k]=='cmi.completion_status') {
 
-		} else if (my_get_value_scorm[k]=='cmi.core.exit') {
+		} else if (my_get_value_scorm[k]=='cmi.core.exit') {
 	        params += '&core_exit='+lms_item_core_exit;
-		}
-
-		if (my_get_value_scorm[k]=='interactions') {
-			is_interactions='true';
-		} else {
-			is_interactions='false';
-		}
-	}
-
-
- if (is_interactions=='true')  {
-         interact_string = '';
-  		temp = '';
-        for (i in interactions){
-
-        	interact_string += '&interact['+i+']=';
-            interact_temp = '[';
-            for (j in interactions[i]) {
-            	temp = interactions[i][j];
-            	temp = ''+temp; // if temp == 1 there are problems with indexOf and an integer number
+		}
+
+		if (my_get_value_scorm[k]=='interactions') {
+			is_interactions='true';
+		} else {
+			is_interactions='false';
+		}
+	}
+
+
+ if (is_interactions=='true')  {
+         interact_string = '';
+  		temp = '';
+        for (i in interactions){
+
+        	interact_string += '&interact['+i+']=';
+            interact_temp = '[';
+            for (j in interactions[i]) {
+            	temp = interactions[i][j];
+            	temp = ''+temp; // if temp == 1 there are problems with indexOf and an integer number
             	//this fix when an interaction have ',' i.e:   {a,b,c,d} is replace to {a@.|@b@.|@c@.|@d} see DT#4444
 				while(temp.indexOf(',') >= 0){
 					temp = temp.replace(',','@.|@');
-				};
-            	interact_temp +=temp+',';
-            }
-            interact_temp = interact_temp.substr(0,(interact_temp.length-2)) + ']';
-          //  interact_string += encodeURIComponent(interact_temp);
+				};
+            	interact_temp +=temp+',';
+            }
+            interact_temp = interact_temp.substr(0,(interact_temp.length-2)) + ']';
+          //  interact_string += encodeURIComponent(interact_temp);
 
 
            interact_string += interact_temp;
-        }
-        //interact_string = encodeURIComponent(interact_string.substr(0,(interact_string.length-1)));
+        }
+        //interact_string = encodeURIComponent(interact_string.substr(0,(interact_string.length-1)));
         params += interact_string;
-        is_interactions='false';
- }
-
+        is_interactions='false';
+ }
+
   	//alert("parameters : "+params);
-        /*params = {
-            'lid': lms_lp_id,
-            'uid': lms_user_id,
-            'vid': lms_view_id,
-            'iid': lms_item_id,
-            's': score,
-            'max': max,
-            'min': min,
+        /*params = {
+            'lid': lms_lp_id,
+            'uid': lms_user_id,
+            'vid': lms_view_id,
+            'iid': lms_item_id,
+            's': score,
+            'max': max,
+            'min': min,
             'status': lesson_status,
             't': session_time,
-            'suspend': suspend_data,
-            'loc': lesson_location,
+            'suspend': suspend_data,
+            'loc': lesson_location,
             'interact': interac_string,
-            'core_exit': lms_item_core_exit
-        }*/
-       $.ajax({
-            type:"GET",
-            data: params,
+            'core_exit': lms_item_core_exit
+        }*/
+       $.ajax({
+            type:"GET",
+            data: params,
             url: "lp_ajax_save_item.php",
-            dataType: "script",
-            async: false
-            }
-        );
-
-        params='';
-
-}
-
-/**
- * Starts the timer with the server clock time.
- * Originally, we used the xajax library. Now we use jQuery
- */
-function xajax_start_timer() {
-    $.ajax({
-        type: "GET",
-        url: "lp_ajax_start_timer.php",
-        dataType: "script",
-        async: false
+            dataType: "script",
+            async: false
+            }
+        );
+
+        params='';
+
+}
+
+/**
+ * Starts the timer with the server clock time.
+ * Originally, we used the xajax library. Now we use jQuery
+ */
+function xajax_start_timer() {
+    $.ajax({
+        type: "GET",
+        url: "lp_ajax_start_timer.php",
+        dataType: "script",
+        async: false
+    });
+}
+/**
+ * Save a specific item's objectives into the LMS through
+ * an AJAX call. Originally, we used the xajax library. Now we use jQuery
+ */
+function xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,item_objectives) {
+        params='';
+        params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id;
+        params += '&iid='+lms_item_id;
+        obj_string = '';
+        for (i in item_objectives){
+            obj_string += '&objectives['+i+']=';
+            obj_temp = '[';
+            for (j in item_objectives[i]) {
+                obj_temp += item_objectives[i][j]+',';
+            }
+            obj_temp = obj_temp.substr(0,(obj_temp.length-2)) + ']';
+            obj_string += encodeURIComponent(obj_temp);
+        }
+        params += obj_string;
+        $.ajax({
+            type: "GET",
+            data: params,
+            url: "lp_ajax_save_objectives.php",
+            dataType: "script",
+            async: false
+        });
+}
+/**
+ * Switch between two items through
+ * an AJAX call. Originally, we used the xajax library. Now we use jQuery
+ */
+function xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,next_item) {
+    params = {
+        'lid': lms_lp_id,
+        'uid': lms_user_id,
+        'vid': lms_view_id,
+        'iid': lms_item_id,
+        'next': next_item
+    }
+    $.ajax({
+        type: "GET",
+        data: params,
+        url: "lp_ajax_switch_item.php",
+        dataType: "script",
+        async: false
     });
-}
-/**
- * Save a specific item's objectives into the LMS through
- * an AJAX call. Originally, we used the xajax library. Now we use jQuery
- */
-function xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,item_objectives) {
-        params='';
-        params += 'lid='+lms_lp_id+'&uid='+lms_user_id+'&vid='+lms_view_id;
-        params += '&iid='+lms_item_id;
-        obj_string = '';
-        for (i in item_objectives){
-            obj_string += '&objectives['+i+']=';
-            obj_temp = '[';
-            for (j in item_objectives[i]) {
-                obj_temp += item_objectives[i][j]+',';
-            }
-            obj_temp = obj_temp.substr(0,(obj_temp.length-2)) + ']';
-            obj_string += encodeURIComponent(obj_temp);
-        }
-        params += obj_string;
-        $.ajax({
-            type: "GET",
-            data: params,
-            url: "lp_ajax_save_objectives.php",
-            dataType: "script",
-            async: false
-        });
-}
-/**
- * Switch between two items through
- * an AJAX call. Originally, we used the xajax library. Now we use jQuery
- */
-function xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,next_item) {
-    params = {
-        'lid': lms_lp_id,
-        'uid': lms_user_id,
-        'vid': lms_view_id,
-        'iid': lms_item_id,
-        'next': next_item
-    }
-    $.ajax({
-        type: "GET",
-        data: params,
-        url: "lp_ajax_switch_item.php",
-        dataType: "script",
-        async: false
-    });
-}
-
-
-addEvent(window,'load',addListeners,false);
-if(lms_lp_type==1 || lms_item_type=='asset'){
-	xajax_start_timer();
-}
+}
+
+
+addEvent(window,'load',addListeners,false);
+if(lms_lp_type==1 || lms_item_type=='asset'){
+	xajax_start_timer();
+}

+ 9 - 9
main/newscorm/scorm_manage.php

@@ -1,9 +1,9 @@
-<?php
-/**
- * Admin script for SCORM packages
- * @package	dokeos.learnpath.scorm
- */
-/**
- * Here comes the script
- */
-?>
+<?php
+/**
+ * Admin script for SCORM packages
+ * @package	dokeos.learnpath.scorm
+ */
+/**
+ * Here comes the script
+ */
+?>

+ 305 - 305
main/notebook/index.php

@@ -1,377 +1,377 @@
-<?php  //$id: $
-
-/* For licensing terms, see /dokeos_license.txt */
-
-/**
- * @package dokeos.glossary
- * @author Christian Fasanando, initial version
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium, refactoring and tighter integration in Dokeos
- */
-
-// name of the language file that needs to be included
-$language_file = array('notebook');
-
-// including the global dokeos file
-require_once '../inc/global.inc.php';
-
-// the section (tabs)
-$this_section=SECTION_COURSES;
-
-
-// notice for unauthorized people.
-api_protect_course_script(true);
-
-// including additional libraries
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-
-// additional javascript
-$htmlHeadXtra[] = javascript_notebook();
-
-// setting the tool constants
-$tool = TOOL_NOTEBOOK;
-
-// tracking
-event_access_tool(TOOL_NOTEBOOK);
-
-// tool name
-if ( isset($_GET['action']) && $_GET['action'] == 'addnote')
-{
-	$tool = get_lang('NoteAddNew');
-	$interbreadcrumb[] = array ("url"=>"index.php", "name"=> get_lang('Notebook'));
-}
-if ( isset($_GET['action']) && $_GET['action'] == 'editnote')
-{
-	$tool = get_lang('ModifyNote');
-	$interbreadcrumb[] = array ("url"=>"index.php", "name"=> get_lang('Notebook'));
-}
-
-// displaying the header
-Display::display_header(get_lang(ucfirst($tool)));
-
-// Tool introduction
-Display::display_introduction_section(TOOL_NOTEBOOK);
-
-
-// Action handling: Adding a note
+<?php  //$id: $
+
+/* For licensing terms, see /dokeos_license.txt */
+
+/**
+ * @package dokeos.glossary
+ * @author Christian Fasanando, initial version
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium, refactoring and tighter integration in Dokeos
+ */
+
+// name of the language file that needs to be included
+$language_file = array('notebook');
+
+// including the global dokeos file
+require_once '../inc/global.inc.php';
+
+// the section (tabs)
+$this_section=SECTION_COURSES;
+
+
+// notice for unauthorized people.
+api_protect_course_script(true);
+
+// including additional libraries
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
+// additional javascript
+$htmlHeadXtra[] = javascript_notebook();
+
+// setting the tool constants
+$tool = TOOL_NOTEBOOK;
+
+// tracking
+event_access_tool(TOOL_NOTEBOOK);
+
+// tool name
+if ( isset($_GET['action']) && $_GET['action'] == 'addnote')
+{
+	$tool = get_lang('NoteAddNew');
+	$interbreadcrumb[] = array ("url"=>"index.php", "name"=> get_lang('Notebook'));
+}
+if ( isset($_GET['action']) && $_GET['action'] == 'editnote')
+{
+	$tool = get_lang('ModifyNote');
+	$interbreadcrumb[] = array ("url"=>"index.php", "name"=> get_lang('Notebook'));
+}
+
+// displaying the header
+Display::display_header(get_lang(ucfirst($tool)));
+
+// Tool introduction
+Display::display_introduction_section(TOOL_NOTEBOOK);
+
+
+// Action handling: Adding a note
 if (isset($_GET['action']) && $_GET['action'] == 'addnote')
 {
 
-	if (!empty($_GET['isStudentView'])) {
-		display_notes();
+	if (!empty($_GET['isStudentView'])) {
+		display_notes();
 		exit;
 	}
 
-	$_SESSION['notebook_view'] = 'creation_date';
+	$_SESSION['notebook_view'] = 'creation_date';
 
-	// initiate the object
-	$form = new FormValidator('note','post', api_get_self().'?action='.Security::remove_XSS($_GET['action']));
+	// initiate the object
+	$form = new FormValidator('note','post', api_get_self().'?action='.Security::remove_XSS($_GET['action']));
 	// settting the form elements
-	$form->addElement('header', '', get_lang('NoteAddNew'));
-	$form->addElement('text', 'note_title', get_lang('NoteTitle'),array('size'=>'95'));
-	//$form->applyFilter('note_title', 'html_filter');
-	$form->addElement('html_editor', 'note_comment', get_lang('NoteComment'), null, api_is_allowed_to_edit()
-		? array('ToolbarSet' => 'Notebook', 'Width' => '100%', 'Height' => '300')
-		: array('ToolbarSet' => 'NotebookStudent', 'Width' => '100%', 'Height' => '300', 'UserStatus' => 'student')
-	);
+	$form->addElement('header', '', get_lang('NoteAddNew'));
+	$form->addElement('text', 'note_title', get_lang('NoteTitle'),array('size'=>'95'));
+	//$form->applyFilter('note_title', 'html_filter');
+	$form->addElement('html_editor', 'note_comment', get_lang('NoteComment'), null, api_is_allowed_to_edit()
+		? array('ToolbarSet' => 'Notebook', 'Width' => '100%', 'Height' => '300')
+		: array('ToolbarSet' => 'NotebookStudent', 'Width' => '100%', 'Height' => '300', 'UserStatus' => 'student')
+	);
 	$form->addElement('style_submit_button', 'SubmitNote', get_lang('AddNote'), 'class="add"');
 
-	// setting the rules
+	// setting the rules
 	$form->addRule('note_title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
 
-	// The validation or display
+	// The validation or display
 	if ( $form->validate() )
-	{
+	{
 		$check = Security::check_token('post');
 		if ($check)
-		{
+		{
 	   		$values = $form->exportValues();
-	   		save_note($values);
+	   		save_note($values);
 
-		}
+		}
 		Security::clear_token();
 		display_notes();
 	}
 	else
 	{
-		echo '<div class="actions">';
-		echo '<a href="index.php">'.Display::return_icon('back.png').' '.get_lang('BackToNotesList').'</a>';
-		echo '</div>';
-		$token = Security::get_token();
-		$form->addElement('hidden','sec_token');
+		echo '<div class="actions">';
+		echo '<a href="index.php">'.Display::return_icon('back.png').' '.get_lang('BackToNotesList').'</a>';
+		echo '</div>';
+		$token = Security::get_token();
+		$form->addElement('hidden','sec_token');
 		$form->setConstants(array('sec_token' => $token));
-		$form->display();
+		$form->display();
 	}
-}
-
-// Action handling: Editing a note
+}
+
+// Action handling: Editing a note
 else if (isset($_GET['action']) && $_GET['action'] == 'editnote' && is_numeric($_GET['notebook_id']))
-{
+{
 
-	if (!empty($_GET['isStudentView'])) {
-		display_notes();
+	if (!empty($_GET['isStudentView'])) {
+		display_notes();
 		exit;
 	}
 
-	// initiate the object
-	$form = new FormValidator('note','post', api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&notebook_id='.Security::remove_XSS($_GET['notebook_id']));
+	// initiate the object
+	$form = new FormValidator('note','post', api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&notebook_id='.Security::remove_XSS($_GET['notebook_id']));
 	// settting the form elements
-	$form->addElement('header', '', get_lang('ModifyNote'));
-	$form->addElement('hidden', 'notebook_id');
-	$form->addElement('text', 'note_title', get_lang('NoteTitle'),array('size'=>'100'));
-	//$form->applyFilter('note_title', 'html_filter');
-	$form->addElement('html_editor', 'note_comment', get_lang('NoteComment'), null, api_is_allowed_to_edit()
-		? array('ToolbarSet' => 'Notebook', 'Width' => '100%', 'Height' => '300')
-		: array('ToolbarSet' => 'NotebookStudent', 'Width' => '100%', 'Height' => '300', 'UserStatus' => 'student')
-	);
+	$form->addElement('header', '', get_lang('ModifyNote'));
+	$form->addElement('hidden', 'notebook_id');
+	$form->addElement('text', 'note_title', get_lang('NoteTitle'),array('size'=>'100'));
+	//$form->applyFilter('note_title', 'html_filter');
+	$form->addElement('html_editor', 'note_comment', get_lang('NoteComment'), null, api_is_allowed_to_edit()
+		? array('ToolbarSet' => 'Notebook', 'Width' => '100%', 'Height' => '300')
+		: array('ToolbarSet' => 'NotebookStudent', 'Width' => '100%', 'Height' => '300', 'UserStatus' => 'student')
+	);
 	$form->addElement('style_submit_button', 'SubmitNote', get_lang('ModifyNote'), 'class="save"');
 
-	// setting the defaults
-	$defaults = get_note_information(Security::remove_XSS($_GET['notebook_id']));
-	$form->setDefaults($defaults);
+	// setting the defaults
+	$defaults = get_note_information(Security::remove_XSS($_GET['notebook_id']));
+	$form->setDefaults($defaults);
 
-	// setting the rules
+	// setting the rules
 	$form->addRule('note_title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
 
-	// The validation or display
+	// The validation or display
 	if ( $form->validate() )
-	{
+	{
 		$check = Security::check_token('post');
 		if ($check)
-		{
-	   		$values = $form->exportValues();
-	   		update_note($values);
-		}
-		Security::clear_token();
-		display_notes();
+		{
+	   		$values = $form->exportValues();
+	   		update_note($values);
+		}
+		Security::clear_token();
+		display_notes();
 	}
 	else
-	{
-		echo '<div class="actions">';
-		echo '<a href="index.php">'.Display::return_icon('back.png').' '.get_lang('BackToNotesList').'</a>';
+	{
+		echo '<div class="actions">';
+		echo '<a href="index.php">'.Display::return_icon('back.png').' '.get_lang('BackToNotesList').'</a>';
 		echo '</div>';
-		$token = Security::get_token();
-		$form->addElement('hidden','sec_token');
+		$token = Security::get_token();
+		$form->addElement('hidden','sec_token');
 		$form->setConstants(array('sec_token' => $token));
-		$form->display();
+		$form->display();
 	}
-}
-
-// Action handling: deleting a note
+}
+
+// Action handling: deleting a note
 else if (isset($_GET['action']) && $_GET['action'] == 'deletenote' && is_numeric($_GET['notebook_id']))
-{
-	delete_note(Security::remove_XSS($_GET['notebook_id']));
-	display_notes();
-}
-
-// Action handling: changing the view (sorting order)
-else if ($_GET['action'] == 'changeview' AND in_array($_GET['view'],array('creation_date','update_date', 'title')))
-{
-	switch ($_GET['view'])
-	{
-		case 'creation_date':
-			if (!$_GET['direction'] OR $_GET['direction'] == 'ASC')
-			{
-				Display::display_confirmation_message(get_lang('NotesSortedByCreationDateAsc'));
-			}
+{
+	delete_note(Security::remove_XSS($_GET['notebook_id']));
+	display_notes();
+}
+
+// Action handling: changing the view (sorting order)
+else if ($_GET['action'] == 'changeview' AND in_array($_GET['view'],array('creation_date','update_date', 'title')))
+{
+	switch ($_GET['view'])
+	{
+		case 'creation_date':
+			if (!$_GET['direction'] OR $_GET['direction'] == 'ASC')
+			{
+				Display::display_confirmation_message(get_lang('NotesSortedByCreationDateAsc'));
+			}
 			else
-			{
-				Display::display_confirmation_message(get_lang('NotesSortedByCreationDateDESC'));
-			}
-			break;
-		case 'update_date':
-			if (!$_GET['direction'] OR $_GET['direction'] == 'ASC')
-			{
-				Display::display_confirmation_message(get_lang('NotesSortedByUpdateDateAsc'));
-			}
+			{
+				Display::display_confirmation_message(get_lang('NotesSortedByCreationDateDESC'));
+			}
+			break;
+		case 'update_date':
+			if (!$_GET['direction'] OR $_GET['direction'] == 'ASC')
+			{
+				Display::display_confirmation_message(get_lang('NotesSortedByUpdateDateAsc'));
+			}
 			else
-			{
-				Display::display_confirmation_message(get_lang('NotesSortedByUpdateDateDESC'));
-			}
-			break;
-		case 'title':
-			if (!$_GET['direction'] OR $_GET['direction'] == 'ASC')
-			{
-				Display::display_confirmation_message(get_lang('NotesSortedByTitleAsc'));
-			}
+			{
+				Display::display_confirmation_message(get_lang('NotesSortedByUpdateDateDESC'));
+			}
+			break;
+		case 'title':
+			if (!$_GET['direction'] OR $_GET['direction'] == 'ASC')
+			{
+				Display::display_confirmation_message(get_lang('NotesSortedByTitleAsc'));
+			}
 			else
-			{
-				Display::display_confirmation_message(get_lang('NotesSortedByTitleDESC'));
-			}
+			{
+				Display::display_confirmation_message(get_lang('NotesSortedByTitleDESC'));
+			}
 			break;
-	}
+	}
 	$_SESSION['notebook_view'] = $_GET['view'];
-	display_notes();
-} else {
-	display_notes();
-}
-
-
-// footer
-Display::display_footer();
-
-/**
- * a little bit of javascript to display a prettier warning when deleting a note
- *
- * @return unknown
+	display_notes();
+} else {
+	display_notes();
+}
+
+
+// footer
+Display::display_footer();
+
+/**
+ * a little bit of javascript to display a prettier warning when deleting a note
+ *
+ * @return unknown
  *
- * @author Patrick Cool <patrick.cool@ugent.be>, Ghent University, Belgium
- * @version januari 2009, dokeos 1.8.6
- */
+ * @author Patrick Cool <patrick.cool@ugent.be>, Ghent University, Belgium
+ * @version januari 2009, dokeos 1.8.6
+ */
 function javascript_notebook()
-{
-	return "<script type=\"text/javascript\">
-			function confirmation (name)
-			{
-				if (confirm(\" ". get_lang("NoteConfirmDelete") ." \"+ name + \" ?\"))
-					{return true;}
-				else
-					{return false;}
-			}
-			</script>";
-}
-
-/**
- * This functions stores the note in the database
- *
- * @param array $values
+{
+	return "<script type=\"text/javascript\">
+			function confirmation (name)
+			{
+				if (confirm(\" ". get_lang("NoteConfirmDelete") ." \"+ name + \" ?\"))
+					{return true;}
+				else
+					{return false;}
+			}
+			</script>";
+}
+
+/**
+ * This functions stores the note in the database
  *
- * @author Christian Fasanando <christian.fasanando@dokeos.com>
- * @author Patrick Cool <patrick.cool@ugent.be>, Ghent University, Belgium
- * @version januari 2009, dokeos 1.8.6
- */
-function save_note($values) {
-	// Database table definition
-	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
-
-	$sql = "INSERT INTO $t_notebook (user_id, course, session_id, title, description, creation_date,update_date,status)
-			VALUES(
+ * @param array $values
+ *
+ * @author Christian Fasanando <christian.fasanando@dokeos.com>
+ * @author Patrick Cool <patrick.cool@ugent.be>, Ghent University, Belgium
+ * @version januari 2009, dokeos 1.8.6
+ */
+function save_note($values) {
+	// Database table definition
+	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
+
+	$sql = "INSERT INTO $t_notebook (user_id, course, session_id, title, description, creation_date,update_date,status)
+			VALUES(
 				'".Database::escape_string(api_get_user_id())."',
-				'".Database::escape_string(api_get_course_id())."',
-				'".Database::escape_string($_SESSION['id_session'])."',
-				'".Database::escape_string(Security::remove_XSS($values['note_title']))."',
-				'".Database::escape_string(Security::remove_XSS(stripslashes(api_html_entity_decode($values['note_comment'])),COURSEMANAGERLOWSECURITY))."',
+				'".Database::escape_string(api_get_course_id())."',
+				'".Database::escape_string($_SESSION['id_session'])."',
+				'".Database::escape_string(Security::remove_XSS($values['note_title']))."',
+				'".Database::escape_string(Security::remove_XSS(stripslashes(api_html_entity_decode($values['note_comment'])),COURSEMANAGERLOWSECURITY))."',
 				'".Database::escape_string(date('Y-m-d H:i:s'))."',
 				'".Database::escape_string(date('Y-m-d H:i:s'))."',
-				'0')";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	// display the feedback message
+				'0')";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	// display the feedback message
 	Display::display_confirmation_message(get_lang('NoteAdded'));
-}
-
-function get_note_information($notebook_id) {
-	// Database table definition
-	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
+}
+
+function get_note_information($notebook_id) {
+	// Database table definition
+	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
 
 	$sql = "SELECT 	notebook_id 		AS notebook_id,
 					title				AS note_title,
-					description 		AS note_comment
-			   FROM $t_notebook
+					description 		AS note_comment
+			   FROM $t_notebook
 			   WHERE notebook_id = '".Database::escape_string($notebook_id)."' ";
-	$result = Database::query($sql, __FILE__, __LINE__);
+	$result = Database::query($sql, __FILE__, __LINE__);
 	return Database::fetch_array($result);
-}
-
-/**
- * This functions updates the note in the database
- *
- * @param array $values
+}
+
+/**
+ * This functions updates the note in the database
  *
- * @author Christian Fasanando <christian.fasanando@dokeos.com>
- * @author Patrick Cool <patrick.cool@ugent.be>, Ghent University, Belgium
- * @version januari 2009, dokeos 1.8.6
- */
-function update_note($values) {
-	// Database table definition
-	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
-
-	$sql = "UPDATE $t_notebook SET
+ * @param array $values
+ *
+ * @author Christian Fasanando <christian.fasanando@dokeos.com>
+ * @author Patrick Cool <patrick.cool@ugent.be>, Ghent University, Belgium
+ * @version januari 2009, dokeos 1.8.6
+ */
+function update_note($values) {
+	// Database table definition
+	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
+
+	$sql = "UPDATE $t_notebook SET
 				user_id = '".Database::escape_string(api_get_user_id())."',
-				course = '".Database::escape_string(api_get_course_id())."',
-				session_id = '".Database::escape_string($_SESSION['id_session'])."',
-				title = '".Database::escape_string(Security::remove_XSS($values['note_title']))."',
-				description = '".Database::escape_string(Security::remove_XSS(stripslashes(api_html_entity_decode($values['note_comment'])),COURSEMANAGERLOWSECURITY))."',
-				update_date = '".Database::escape_string(date('Y-m-d H:i:s'))."'
-			WHERE notebook_id = '".Database::escape_string($values['notebook_id'])."'";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	// display the feedback message
+				course = '".Database::escape_string(api_get_course_id())."',
+				session_id = '".Database::escape_string($_SESSION['id_session'])."',
+				title = '".Database::escape_string(Security::remove_XSS($values['note_title']))."',
+				description = '".Database::escape_string(Security::remove_XSS(stripslashes(api_html_entity_decode($values['note_comment'])),COURSEMANAGERLOWSECURITY))."',
+				update_date = '".Database::escape_string(date('Y-m-d H:i:s'))."'
+			WHERE notebook_id = '".Database::escape_string($values['notebook_id'])."'";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	// display the feedback message
 	Display::display_confirmation_message(get_lang('NoteUpdated'));
-}
-
-function delete_note($notebook_id) {
-	// Database table definition
-	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
-
-	$sql = "DELETE FROM $t_notebook WHERE notebook_id='".Database::escape_string($notebook_id)."' AND user_id = '".Database::escape_string(api_get_user_id())."'";
+}
+
+function delete_note($notebook_id) {
+	// Database table definition
+	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
+
+	$sql = "DELETE FROM $t_notebook WHERE notebook_id='".Database::escape_string($notebook_id)."' AND user_id = '".Database::escape_string(api_get_user_id())."'";
 	$result = Database::query($sql, __FILE__, __LINE__);
 	Display::display_confirmation_message(get_lang('NoteDeleted'));
-}
-
-function display_notes() {
-
-	if (!$_GET['direction'])
-	{
-		$sort_direction = 'ASC';
-		$link_sort_direction = 'DESC';
-	}
-	elseif ($_GET['direction'] == 'ASC')
-	{
-		$sort_direction = 'ASC';
-		$link_sort_direction = 'DESC';
-	}
+}
+
+function display_notes() {
+
+	if (!$_GET['direction'])
+	{
+		$sort_direction = 'ASC';
+		$link_sort_direction = 'DESC';
+	}
+	elseif ($_GET['direction'] == 'ASC')
+	{
+		$sort_direction = 'ASC';
+		$link_sort_direction = 'DESC';
+	}
 	else
-	{
-		$sort_direction = 'DESC';
-		$link_sort_direction = 'ASC';
-	}
-
-
-	// action links
-	echo '<div class="actions" style="margin-bottom:20px">';
-	//if (api_is_allowed_to_edit())
-	//{
-		if (!api_is_anonymous()) {
-			echo '<a href="index.php?'.api_get_cidreq().'&amp;action=addnote">'.Display::return_icon('filenew.gif',get_lang('NoteAddNew')).get_lang('NoteAddNew').'</a>';
-		} else {
-			echo '<a href="javascript:void(0)">'.Display::return_icon('filenew.gif',get_lang('NoteAddNew')).get_lang('NoteAddNew').'</a>';
-		}
-	//}
-	echo '<a href="index.php?'.api_get_cidreq().'&amp;action=changeview&amp;view=creation_date&amp;direction='.$link_sort_direction.'">'.Display::return_icon('calendar_select.gif',get_lang('OrderByCreationDate')).get_lang('OrderByCreationDate').'</a>';
-	echo '<a href="index.php?'.api_get_cidreq().'&amp;action=changeview&amp;view=update_date&amp;direction='.$link_sort_direction.'">'.Display::return_icon('calendar_select.gif',get_lang('OrderByModificationDate')).get_lang('OrderByModificationDate').'</a>';
-	echo '<a href="index.php?'.api_get_cidreq().'&amp;action=changeview&amp;view=title&amp;direction='.$link_sort_direction.'">'.Display::return_icon('comment.gif',get_lang('OrderByTitle')).get_lang('OrderByTitle').'</a>';
+	{
+		$sort_direction = 'DESC';
+		$link_sort_direction = 'ASC';
+	}
+
+
+	// action links
+	echo '<div class="actions" style="margin-bottom:20px">';
+	//if (api_is_allowed_to_edit())
+	//{
+		if (!api_is_anonymous()) {
+			echo '<a href="index.php?'.api_get_cidreq().'&amp;action=addnote">'.Display::return_icon('filenew.gif',get_lang('NoteAddNew')).get_lang('NoteAddNew').'</a>';
+		} else {
+			echo '<a href="javascript:void(0)">'.Display::return_icon('filenew.gif',get_lang('NoteAddNew')).get_lang('NoteAddNew').'</a>';
+		}
+	//}
+	echo '<a href="index.php?'.api_get_cidreq().'&amp;action=changeview&amp;view=creation_date&amp;direction='.$link_sort_direction.'">'.Display::return_icon('calendar_select.gif',get_lang('OrderByCreationDate')).get_lang('OrderByCreationDate').'</a>';
+	echo '<a href="index.php?'.api_get_cidreq().'&amp;action=changeview&amp;view=update_date&amp;direction='.$link_sort_direction.'">'.Display::return_icon('calendar_select.gif',get_lang('OrderByModificationDate')).get_lang('OrderByModificationDate').'</a>';
+	echo '<a href="index.php?'.api_get_cidreq().'&amp;action=changeview&amp;view=title&amp;direction='.$link_sort_direction.'">'.Display::return_icon('comment.gif',get_lang('OrderByTitle')).get_lang('OrderByTitle').'</a>';
 	echo '</div>';
 
-	if (!in_array($_SESSION['notebook_view'],array('creation_date','update_date', 'title'))) {
-		$_SESSION['notebook_view'] = 'creation_date';
-	}
+	if (!in_array($_SESSION['notebook_view'],array('creation_date','update_date', 'title'))) {
+		$_SESSION['notebook_view'] = 'creation_date';
+	}
 
-	// Database table definition
+	// Database table definition
 	$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
-	$order_by = "";
-	if ($_SESSION['notebook_view'] == 'creation_date' || $_SESSION['notebook_view'] == 'update_date') {
-		$order_by = " ORDER BY ".$_SESSION['notebook_view']." $sort_direction ";
-	} else {
-		$order_by = " ORDER BY ".$_SESSION['notebook_view']." $sort_direction ";
-	}
-
-	$cond_extra = ($_SESSION['notebook_view']== 'update_date')?" AND update_date <> '0000-00-00 00:00:00'":" ";
-
-	$sql = "SELECT * FROM $t_notebook WHERE user_id = '".Database::escape_string(api_get_user_id())."' $cond_extra $order_by";
-	$result = Database::query($sql, __FILE__, __LINE__);
-	while ($row = Database::fetch_array($result)) {
-		echo '<div class="sectiontitle">';
-		echo '<span style="float: right;"> ('.get_lang('CreationDate').': '.date_to_str_ago($row['creation_date']).'&nbsp;&nbsp;<span class="dropbox_date">'.$row['creation_date'].'</span>';
-		if ($row['update_date'] <> $row['creation_date']) {
-			echo ', '.get_lang('UpdateDate').': '.date_to_str_ago($row['update_date']).'&nbsp;&nbsp;<span class="dropbox_date">'.$row['update_date'].'</span>';
-		}
-		echo ')</span>';
-		echo $row['title'];
-		echo '</div>';
-		echo '<div class="sectioncomment">'.$row['description'].'</div>';
-		echo '<div>';
-		echo '<a href="'.api_get_self().'?action=editnote&amp;notebook_id='.$row['notebook_id'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
-		echo '<a href="'.api_get_self().'?action=deletenote&amp;notebook_id='.$row['notebook_id'].'" onclick="return confirmation(\''.$row['title'].'\');">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
-		echo '</div>';
-	}
+	$order_by = "";
+	if ($_SESSION['notebook_view'] == 'creation_date' || $_SESSION['notebook_view'] == 'update_date') {
+		$order_by = " ORDER BY ".$_SESSION['notebook_view']." $sort_direction ";
+	} else {
+		$order_by = " ORDER BY ".$_SESSION['notebook_view']." $sort_direction ";
+	}
+
+	$cond_extra = ($_SESSION['notebook_view']== 'update_date')?" AND update_date <> '0000-00-00 00:00:00'":" ";
+
+	$sql = "SELECT * FROM $t_notebook WHERE user_id = '".Database::escape_string(api_get_user_id())."' $cond_extra $order_by";
+	$result = Database::query($sql, __FILE__, __LINE__);
+	while ($row = Database::fetch_array($result)) {
+		echo '<div class="sectiontitle">';
+		echo '<span style="float: right;"> ('.get_lang('CreationDate').': '.date_to_str_ago($row['creation_date']).'&nbsp;&nbsp;<span class="dropbox_date">'.$row['creation_date'].'</span>';
+		if ($row['update_date'] <> $row['creation_date']) {
+			echo ', '.get_lang('UpdateDate').': '.date_to_str_ago($row['update_date']).'&nbsp;&nbsp;<span class="dropbox_date">'.$row['update_date'].'</span>';
+		}
+		echo ')</span>';
+		echo $row['title'];
+		echo '</div>';
+		echo '<div class="sectioncomment">'.$row['description'].'</div>';
+		echo '<div>';
+		echo '<a href="'.api_get_self().'?action=editnote&amp;notebook_id='.$row['notebook_id'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
+		echo '<a href="'.api_get_self().'?action=deletenote&amp;notebook_id='.$row['notebook_id'].'" onclick="return confirmation(\''.$row['title'].'\');">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
+		echo '</div>';
+	}
 	return $return;
-}
-?>
+}
+?>

+ 161 - 161
main/permissions/blog_permissions.inc.php

@@ -1,175 +1,175 @@
-<?php
-
-/**
-* smartBlogs add-on: it must be possible to change rights for every single blog
-* in a course.
+<?php
+
+/**
+* smartBlogs add-on: it must be possible to change rights for every single blog
+* in a course.
 *
-* @author Toon Keppens
-*/
-// Init
-$rights_full=array("article_add","article_delete","article_edit","article_rate","article_comments_add","article_comments_delete","article_comments_rate","task_management","member_management","role_management");
-$rights_limited=array("Add","Edit","Delete");
-$rights_blog=array("article_add","article_delete","article_edit","article_rate","article_comments_add","article_comments_delete","article_comments_rate","task_management","member_management","role_management");
-$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
-
-// Get all user
-$blog_users = Blog::get_blog_users(mysql_escape_string($_GET['blog_id']));
-
-// Remove the blog creater because he has all the rights automatically
-// and we want to keep it that way.
-$tbl_course_rel_user = $table=Database::get_main_table(TABLE_MAIN_COURSE_USER);
-$sql = "SELECT user_id FROM $tbl_course_rel_user WHERE status = '1' AND course_code = '".$_SESSION['_cid']."'";
-$result = Database::query($sql,__FILE__,__LINE__);
-while ($user = mysql_fetch_assoc($result)) {
+* @author Toon Keppens
+*/
+// Init
+$rights_full=array("article_add","article_delete","article_edit","article_rate","article_comments_add","article_comments_delete","article_comments_rate","task_management","member_management","role_management");
+$rights_limited=array("Add","Edit","Delete");
+$rights_blog=array("article_add","article_delete","article_edit","article_rate","article_comments_add","article_comments_delete","article_comments_rate","task_management","member_management","role_management");
+$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
+
+// Get all user
+$blog_users = Blog::get_blog_users(mysql_escape_string($_GET['blog_id']));
+
+// Remove the blog creater because he has all the rights automatically
+// and we want to keep it that way.
+$tbl_course_rel_user = $table=Database::get_main_table(TABLE_MAIN_COURSE_USER);
+$sql = "SELECT user_id FROM $tbl_course_rel_user WHERE status = '1' AND course_code = '".$_SESSION['_cid']."'";
+$result = Database::query($sql,__FILE__,__LINE__);
+while ($user = mysql_fetch_assoc($result)) {
 	unset($blog_users[$user['user_id']]);
-}
-
-//$user_id=$userIdViewed;
-if ($mainUserInfo['status']==1)
-{
-	$course_admin=1;
-}
-
-include_once('permissions_functions.inc.php');
-include_once(api_get_path(LIBRARY_PATH) . "/groupmanager.lib.php");
-// ---------------------------------------------------
-// 			ACTIONS
-// ---------------------------------------------------
-if (isset($_GET['do']))
-{
-	if ( isset($_GET['permission']) AND isset($_GET['tool']) AND ($_GET['do']=='grant' OR $_GET['do']=='revoke'))
-	{
-		$result_message=store_one_permission('user', $_GET['do'], $_GET['user_id'], $_GET['tool'], $_GET['permission']);
-	}
-	if (isset($_GET['role']) AND ($_GET['do']=='grant' OR $_GET['do']=='revoke'))
-	{
-		$result_message=assign_role('user', $_GET['do'], $user_id, $_GET['role'], $_GET['scope']);
-	}
-}
-/*
-if (isset($result_message))
-{
-	Display::display_normal_message($result_message);
-}
-*/
-
-
-// ------------------------------------------------------------------
-// 			RETRIEVING THE PERMISSIONS OF THE ROLES OF THE USER
-// ------------------------------------------------------------------
-if (api_get_setting('user_roles')=='true')
-{
-	// course roles that are assigned to the user
-	$current_user_role_permissions_of_user=get_roles_permissions('user',$user_id);
-	$inherited_permissions=permission_array_merge($inherited_permissions,$current_user_role_permissions_of_user);
-	// NOTE: deze array moet nog gemerged worden met de $inherited_permissions array
+}
+
+//$user_id=$userIdViewed;
+if ($mainUserInfo['status']==1)
+{
+	$course_admin=1;
+}
+
+include_once('permissions_functions.inc.php');
+include_once(api_get_path(LIBRARY_PATH) . "/groupmanager.lib.php");
+// ---------------------------------------------------
+// 			ACTIONS
+// ---------------------------------------------------
+if (isset($_GET['do']))
+{
+	if ( isset($_GET['permission']) AND isset($_GET['tool']) AND ($_GET['do']=='grant' OR $_GET['do']=='revoke'))
+	{
+		$result_message=store_one_permission('user', $_GET['do'], $_GET['user_id'], $_GET['tool'], $_GET['permission']);
+	}
+	if (isset($_GET['role']) AND ($_GET['do']=='grant' OR $_GET['do']=='revoke'))
+	{
+		$result_message=assign_role('user', $_GET['do'], $user_id, $_GET['role'], $_GET['scope']);
+	}
+}
+/*
+if (isset($result_message))
+{
+	Display::display_normal_message($result_message);
+}
+*/
+
+
+// ------------------------------------------------------------------
+// 			RETRIEVING THE PERMISSIONS OF THE ROLES OF THE USER
+// ------------------------------------------------------------------
+if (api_get_setting('user_roles')=='true')
+{
+	// course roles that are assigned to the user
+	$current_user_role_permissions_of_user=get_roles_permissions('user',$user_id);
+	$inherited_permissions=permission_array_merge($inherited_permissions,$current_user_role_permissions_of_user);
+	// NOTE: deze array moet nog gemerged worden met de $inherited_permissions array
 	// (heet momenteel nog $current_group_permissions_of_user omdat voorlopig enkel de
-	// groepsge�rfde permissions in beschouwing worden genomen
-	// dit moet ook de rol permissies van rollen die toegekend worden aan een gebruiker
-	// en de rol permissies van rollen die toegekend worden aan de groepen van een gebruiker
-	// omvatten.
+	// groepsge�rfde permissions in beschouwing worden genomen
+	// dit moet ook de rol permissies van rollen die toegekend worden aan een gebruiker
+	// en de rol permissies van rollen die toegekend worden aan de groepen van een gebruiker
+	// omvatten.
 	// NOTE: checken als de rollen brol wel degelijk geactiveerd is voordat we dit allemaal
-	// ophalen.
-	// platform roles that are assigned to the user
-	$current_user_role_permissions_of_user=get_roles_permissions('user',$user_id, 'platform');
-	$inherited_permissions=permission_array_merge($inherited_permissions,$current_user_role_permissions_of_user);
-}
-// ------------------------------------------------------------------
-//	RETRIEVING THE PERMISSIONS OF THE ROLES OF THE GROUPS OF THE USER
-// ------------------------------------------------------------------
-if (api_get_setting('group_roles')=='true')
-{
-	// NOTE: DIT MOET NOG VERDER UITGEWERKT WORDEN
-	foreach ($groups_of_user as $group)
-	{
-		$this_current_group_role_permissions_of_user=get_roles_permissions('user',$user_id);
-		//$inherited_permissions[$tool][]=$permission;
-	}
-}
-
-
-echo "<form method=\"post\" action=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."\">";
-
-// ---------------------------------------------------
-// 		DISPLAYING THE ROLES LIST
-// ---------------------------------------------------
-if (api_get_setting('user_roles')=='true')
-{
-	// the list of the roles for the user
-	echo '<strong>'.get_lang('UserRoles').'</strong><br />';
-	$current_user_course_roles=get_roles('user',$user_id);
-	$current_user_platform_roles=get_roles('user',$user_id, 'platform');
-	display_role_list($current_user_course_roles, $current_user_platform_roles);
-	echo '<br />';
-}
-
-// ---------------------------------------------------
-// 			DISPLAYING THE MATRIX (user permissions)
-// ---------------------------------------------------
-echo "<table class=\"data_table\">\n";
-
-// the header
+	// ophalen.
+	// platform roles that are assigned to the user
+	$current_user_role_permissions_of_user=get_roles_permissions('user',$user_id, 'platform');
+	$inherited_permissions=permission_array_merge($inherited_permissions,$current_user_role_permissions_of_user);
+}
+// ------------------------------------------------------------------
+//	RETRIEVING THE PERMISSIONS OF THE ROLES OF THE GROUPS OF THE USER
+// ------------------------------------------------------------------
+if (api_get_setting('group_roles')=='true')
+{
+	// NOTE: DIT MOET NOG VERDER UITGEWERKT WORDEN
+	foreach ($groups_of_user as $group)
+	{
+		$this_current_group_role_permissions_of_user=get_roles_permissions('user',$user_id);
+		//$inherited_permissions[$tool][]=$permission;
+	}
+}
+
+
+echo "<form method=\"post\" action=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."\">";
+
+// ---------------------------------------------------
+// 		DISPLAYING THE ROLES LIST
+// ---------------------------------------------------
+if (api_get_setting('user_roles')=='true')
+{
+	// the list of the roles for the user
+	echo '<strong>'.get_lang('UserRoles').'</strong><br />';
+	$current_user_course_roles=get_roles('user',$user_id);
+	$current_user_platform_roles=get_roles('user',$user_id, 'platform');
+	display_role_list($current_user_course_roles, $current_user_platform_roles);
+	echo '<br />';
+}
+
+// ---------------------------------------------------
+// 			DISPLAYING THE MATRIX (user permissions)
+// ---------------------------------------------------
+echo "<table class=\"data_table\">\n";
+
+// the header
+echo "\t<tr>\n";
+	echo "\t\t<th rowspan=\"2\">".get_lang('Module')."</th>\n";
+	echo "\t\t<th colspan=\"4\">".get_lang('ArticleManager')."</th>\n";
+	echo "\t\t<th colspan=\"3\">".get_lang('CommentManager')."</th>\n";
+	echo "\t\t<th colspan=\"3\">".get_lang('BlogManager')."</th>\n";
+echo "\t</tr>\n";
+
+// Subheader
 echo "\t<tr>\n";
-	echo "\t\t<th rowspan=\"2\">".get_lang('Module')."</th>\n";
-	echo "\t\t<th colspan=\"4\">".get_lang('ArticleManager')."</th>\n";
-	echo "\t\t<th colspan=\"3\">".get_lang('CommentManager')."</th>\n";
-	echo "\t\t<th colspan=\"3\">".get_lang('BlogManager')."</th>\n";
-echo "\t</tr>\n";
-
-// Subheader
-echo "\t<tr>\n";
-	echo "\t\t<th align='center'>".get_lang('Add')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Delete')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Edit')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Rate')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Add')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Delete')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Rate')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Tasks')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Members')."</th>\n";
-	echo "\t\t<th align='center'>".get_lang('Roles')."</th>\n";
-echo "\t</tr>\n";
-
-// the main area with the checkboxes or images
-foreach ($blog_users as $user_id => $user_name) // $blog_users contains all the users in this blog
-{
-	// ---------------------------------------------------
-	// 			RETRIEVING THE PERMISSIONS OF THE USER
-	// ---------------------------------------------------
-	$current_user_permissions = array();
-	$current_user_permissions = get_permissions('user', $user_id);
+	echo "\t\t<th align='center'>".get_lang('Add')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Delete')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Edit')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Rate')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Add')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Delete')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Rate')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Tasks')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Members')."</th>\n";
+	echo "\t\t<th align='center'>".get_lang('Roles')."</th>\n";
+echo "\t</tr>\n";
+
+// the main area with the checkboxes or images
+foreach ($blog_users as $user_id => $user_name) // $blog_users contains all the users in this blog
+{
+	// ---------------------------------------------------
+	// 			RETRIEVING THE PERMISSIONS OF THE USER
+	// ---------------------------------------------------
+	$current_user_permissions = array();
+	$current_user_permissions = get_permissions('user', $user_id);
 
 	echo "\t<tr>\n";
-	echo "\t\t<td>\n";
-		echo $user_name;
+	echo "\t\t<td>\n";
+		echo $user_name;
 	echo "\t\t</td>\n";
 
-	foreach ($rights_full as $key => $value)
-	{
+	foreach ($rights_full as $key => $value)
+	{
 
-		echo "\t\t<td align='center'>\n";
-		if (in_array($value,$rights_blog))
-		{
-			display_image_matrix_for_blogs($current_user_permissions, $user_id, 'BLOG_'.$blog_id, $value,$inherited_permissions, $course_admin);
+		echo "\t\t<td align='center'>\n";
+		if (in_array($value,$rights_blog))
+		{
+			display_image_matrix_for_blogs($current_user_permissions, $user_id, 'BLOG_'.$blog_id, $value,$inherited_permissions, $course_admin);
 		}
-		// note: in a later stage this part will be replaced by a function
-		// so that we can easily switch between a checkbox approach or an image approach
+		// note: in a later stage this part will be replaced by a function
+		// so that we can easily switch between a checkbox approach or an image approach
 		// where every click is in fact a change of status. In the checkbox approach you first have to
 		// do the changes and then store them by clicking the submit button.
-		echo "\t\t</td>\n";
-	}
-	echo "\t</tr>\n";
-}
-
-echo "</table>\n";
-echo "</form><br />";
-
-// ---------------------------------------------------
-// 			LEGEND
-// ---------------------------------------------------
-echo '<strong>'.get_lang('Legend').'</strong><br />';
-echo '<img src="../img/wrong.gif" /> '.get_lang('UserHasPermissionNot').'<br />';
-echo '<img src="../img/checkbox_on2.gif" /> '.get_lang('UserHasPermission').'<br />';
-echo '<img src="../img/checkbox_on3.gif" /> '.get_lang('UserHasPermissionByRoleGroup').'<br />';
-
+		echo "\t\t</td>\n";
+	}
+	echo "\t</tr>\n";
+}
+
+echo "</table>\n";
+echo "</form><br />";
+
+// ---------------------------------------------------
+// 			LEGEND
+// ---------------------------------------------------
+echo '<strong>'.get_lang('Legend').'</strong><br />';
+echo '<img src="../img/wrong.gif" /> '.get_lang('UserHasPermissionNot').'<br />';
+echo '<img src="../img/checkbox_on2.gif" /> '.get_lang('UserHasPermission').'<br />';
+echo '<img src="../img/checkbox_on3.gif" /> '.get_lang('UserHasPermissionByRoleGroup').'<br />';
+
 ?>

+ 647 - 647
main/permissions/permissions_functions.inc.php

@@ -1,678 +1,678 @@
-<?php
-/**
-* This files contains the common functions for the permissions
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-*
-* A list of all the functions (in no particular order)
-* ----------------------------------------------------
-* 	store_permissions($content,$id)
-* 	get_permissions($content,$id)
-*	limited_or_full($current_permissions)
-*/
-
-
-/**
-* This function stores the permissions in the correct table.
-* Since Checkboxes are used we do not know which ones are unchecked.
-* That's why we first delete them all (for the given user/group/role
-* and afterwards we store the checked ones only.
-* @param $content are we storing rights for a user, a group or a role (the database depends on it)
-* @param $id the id of the user, group or role
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function store_permissions($content, $id)
-{
-	// Which database are we using (depending on the $content parameter)
-	if($content=='user')
-	{
-		$table=Database::get_course_table(TABLE_PERMISSION_USER);
-		$id_field = user_id;
-	}
-	if($content=='group')
-	{
-		$table=Database::get_course_table(TABLE_PERMISSION_GROUP);
-		$id_field = group_id;
-	}
-	if($content=='role')
-	{
-		$table=Database::get_course_table(TABLE_ROLE_PERMISSION);
-		$id_field = role_id;
-	}
-
-	// We first delete all the existing permissions for that user/group/role
-	$sql="DELETE FROM $table  WHERE $id_field = '".mysql_real_escape_string($id)."'";
-	$result=Database::query($sql, __FILE__, __LINE__);
-
-	// looping through the post values to find the permission (containing the string permission* )
-	foreach ($_POST as $key => $value)
-	{
-		if(strstr($key,"permission*"))
-		{
-			list($brol,$tool,$action)=explode("*",$key);
-			$sql="INSERT INTO $table ($id_field,tool,action) VALUES ('".mysql_real_escape_string($id)."','".mysql_real_escape_string($tool)."','".mysql_real_escape_string($action)."')";
-			$result=Database::query($sql, __FILE__, __LINE__);
-
-
-		}
-	}
-	return get_lang('PermissionsStored');
-}
-
-/**
-* This function stores one permission in the correct table.
-* @param $content are we storing rights for a user, a group or a role (the database depends on it)
-* @param $action are we granting or revoking a permission?
-* @param $id the id of the user, group or role
+<?php
+/**
+* This files contains the common functions for the permissions
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+*
+* A list of all the functions (in no particular order)
+* ----------------------------------------------------
+* 	store_permissions($content,$id)
+* 	get_permissions($content,$id)
+*	limited_or_full($current_permissions)
+*/
+
+
+/**
+* This function stores the permissions in the correct table.
+* Since Checkboxes are used we do not know which ones are unchecked.
+* That's why we first delete them all (for the given user/group/role
+* and afterwards we store the checked ones only.
+* @param $content are we storing rights for a user, a group or a role (the database depends on it)
+* @param $id the id of the user, group or role
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function store_permissions($content, $id)
+{
+	// Which database are we using (depending on the $content parameter)
+	if($content=='user')
+	{
+		$table=Database::get_course_table(TABLE_PERMISSION_USER);
+		$id_field = user_id;
+	}
+	if($content=='group')
+	{
+		$table=Database::get_course_table(TABLE_PERMISSION_GROUP);
+		$id_field = group_id;
+	}
+	if($content=='role')
+	{
+		$table=Database::get_course_table(TABLE_ROLE_PERMISSION);
+		$id_field = role_id;
+	}
+
+	// We first delete all the existing permissions for that user/group/role
+	$sql="DELETE FROM $table  WHERE $id_field = '".mysql_real_escape_string($id)."'";
+	$result=Database::query($sql, __FILE__, __LINE__);
+
+	// looping through the post values to find the permission (containing the string permission* )
+	foreach ($_POST as $key => $value)
+	{
+		if(strstr($key,"permission*"))
+		{
+			list($brol,$tool,$action)=explode("*",$key);
+			$sql="INSERT INTO $table ($id_field,tool,action) VALUES ('".mysql_real_escape_string($id)."','".mysql_real_escape_string($tool)."','".mysql_real_escape_string($action)."')";
+			$result=Database::query($sql, __FILE__, __LINE__);
+
+
+		}
+	}
+	return get_lang('PermissionsStored');
+}
+
+/**
+* This function stores one permission in the correct table.
+* @param $content are we storing rights for a user, a group or a role (the database depends on it)
+* @param $action are we granting or revoking a permission?
+* @param $id the id of the user, group or role
 * @param $tool the tool
-* @param $permission the permission the user, group or role has been granted or revoked
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function store_one_permission($content, $action, $id, $tool,$permission)
-{
-	global $rights_full;
-	// for some reason I don't know, he can't get to the $rights_full array, so commented the following lines out.
-
-	// check
-	//if(!in_array($permission, $rights_full))
-	//{
-	//	return get_lang('Error');
-	//}
-
-	// Which database are we using (depending on the $content parameter)
-	if($content=='user')
-	{
-		$table=Database::get_course_table(TABLE_PERMISSION_USER);
-		$id_field = user_id;
-	}
-	if($content=='group')
-	{
-		$table=Database::get_course_table(TABLE_PERMISSION_GROUP);
-		$id_field = group_id;
-	}
-	if($content=='role')
-	{
-		$table=Database::get_course_table(TABLE_ROLE_PERMISSION);
-		$id_field = role_id;
-	}
-
-	// grating a right
-	if($action=='grant')
-	{
-		$sql="INSERT INTO $table ($id_field,tool,action) VALUES ('".mysql_real_escape_string($id)."','".mysql_real_escape_string($tool)."','".mysql_real_escape_string($permission)."')";
-		$result=Database::query($sql, __FILE__, __LINE__);
-		if($result)
-		{
-			$result_message=get_lang('PermissionGranted');
-		}
-	}
-	if($action=='revoke')
-	{
-		$sql="DELETE FROM $table WHERE $id_field = '".mysql_real_escape_string($id)."' AND tool='".mysql_real_escape_string($tool)."' AND action='".mysql_real_escape_string($permission)."'";
-		$result=Database::query($sql, __FILE__, __LINE__);
-		if($result)
-		{
-			$result_message=get_lang('PermissionRevoked');
-		}
-	}
-	return $result_message;
-}
-
-/**
-* This function retrieves the existing permissions of a user, group or role.
-* @param $content are we retrieving the rights of a user, a group or a role (the database depends on it)
-* @param $id the id of the user, group or role
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function get_permissions($content, $id)
-{
-	$currentpermissions=array();
-	// Which database are we using (depending on the $content parameter)
-
-	if($content == 'user')
-	{
-		$table=Database::get_course_table(TABLE_PERMISSION_USER);
-		$id_field = user_id;
-	}
-	elseif($content == 'group')
-	{
-		$table=Database::get_course_table(TABLE_PERMISSION_GROUP);
-		$id_field = group_id;
-	}
-	elseif($content == 'role')
-	{
-		$table=Database::get_course_table(TABLE_ROLE_PERMISSION);
-		$id_field = role_id;
-	}
-	elseif($content == 'platform_role')
-	{
-		$table=Database::get_main_table(TABLE_ROLE_PERMISSION);
-		$id_field = role_id;
-	}
-	elseif($content == 'task')
-	{
-		$table=Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
-		$id_field = task_id;
-	}
-
-	// finding all the permissions. We store this in a multidimensional array
-	// where the first dimension is the tool.
-	$sql="
-		SELECT * FROM " . $table . "
-		WHERE " . $id_field . "='" . mysql_real_escape_string($id) . "'";
-	$result = Database::query($sql, __FILE__, __LINE__);
-
-	while($row = mysql_fetch_array($result))
+* @param $permission the permission the user, group or role has been granted or revoked
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function store_one_permission($content, $action, $id, $tool,$permission)
+{
+	global $rights_full;
+	// for some reason I don't know, he can't get to the $rights_full array, so commented the following lines out.
+
+	// check
+	//if(!in_array($permission, $rights_full))
+	//{
+	//	return get_lang('Error');
+	//}
+
+	// Which database are we using (depending on the $content parameter)
+	if($content=='user')
+	{
+		$table=Database::get_course_table(TABLE_PERMISSION_USER);
+		$id_field = user_id;
+	}
+	if($content=='group')
+	{
+		$table=Database::get_course_table(TABLE_PERMISSION_GROUP);
+		$id_field = group_id;
+	}
+	if($content=='role')
+	{
+		$table=Database::get_course_table(TABLE_ROLE_PERMISSION);
+		$id_field = role_id;
+	}
+
+	// grating a right
+	if($action=='grant')
+	{
+		$sql="INSERT INTO $table ($id_field,tool,action) VALUES ('".mysql_real_escape_string($id)."','".mysql_real_escape_string($tool)."','".mysql_real_escape_string($permission)."')";
+		$result=Database::query($sql, __FILE__, __LINE__);
+		if($result)
+		{
+			$result_message=get_lang('PermissionGranted');
+		}
+	}
+	if($action=='revoke')
+	{
+		$sql="DELETE FROM $table WHERE $id_field = '".mysql_real_escape_string($id)."' AND tool='".mysql_real_escape_string($tool)."' AND action='".mysql_real_escape_string($permission)."'";
+		$result=Database::query($sql, __FILE__, __LINE__);
+		if($result)
+		{
+			$result_message=get_lang('PermissionRevoked');
+		}
+	}
+	return $result_message;
+}
+
+/**
+* This function retrieves the existing permissions of a user, group or role.
+* @param $content are we retrieving the rights of a user, a group or a role (the database depends on it)
+* @param $id the id of the user, group or role
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function get_permissions($content, $id)
+{
+	$currentpermissions=array();
+	// Which database are we using (depending on the $content parameter)
+
+	if($content == 'user')
+	{
+		$table=Database::get_course_table(TABLE_PERMISSION_USER);
+		$id_field = user_id;
+	}
+	elseif($content == 'group')
+	{
+		$table=Database::get_course_table(TABLE_PERMISSION_GROUP);
+		$id_field = group_id;
+	}
+	elseif($content == 'role')
+	{
+		$table=Database::get_course_table(TABLE_ROLE_PERMISSION);
+		$id_field = role_id;
+	}
+	elseif($content == 'platform_role')
+	{
+		$table=Database::get_main_table(TABLE_ROLE_PERMISSION);
+		$id_field = role_id;
+	}
+	elseif($content == 'task')
+	{
+		$table=Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
+		$id_field = task_id;
+	}
+
+	// finding all the permissions. We store this in a multidimensional array
+	// where the first dimension is the tool.
+	$sql="
+		SELECT * FROM " . $table . "
+		WHERE " . $id_field . "='" . mysql_real_escape_string($id) . "'";
+	$result = Database::query($sql, __FILE__, __LINE__);
+
+	while($row = mysql_fetch_array($result))
 		$currentpermissions[$row['tool']][] = $row['action'];
 
 	return $currentpermissions;
-}
-
-/**
+}
+
+/**
 * the array that contains the current permission a user, group or role has will now be changed depending on
-* the Dokeos Config Setting for the permissions (limited [add, edit, delete] or full [view, add, edit, delete, move, visibility]
-* @param $content are we retrieving the rights of a user, a group or a role (the database depends on it)
-* @param $id the id of the user, group or role
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
+* the Dokeos Config Setting for the permissions (limited [add, edit, delete] or full [view, add, edit, delete, move, visibility]
+* @param $content are we retrieving the rights of a user, a group or a role (the database depends on it)
+* @param $id the id of the user, group or role
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
 * @todo currently there is a setting user_permissions and group_permissions. We should merge this in one config setting.
-*/
-function limited_or_full($current_permissions)
-{
-	if(api_get_setting('permissions')=='limited')
-	{
-		foreach ($current_permissions as $tool=>$tool_rights)
-		{
-			// we loop through the possible permissions of a tool and unset the entry if it is view
+*/
+function limited_or_full($current_permissions)
+{
+	if(api_get_setting('permissions')=='limited')
+	{
+		foreach ($current_permissions as $tool=>$tool_rights)
+		{
+			// we loop through the possible permissions of a tool and unset the entry if it is view
 			// if it is visibility or move we have to grant the edit right
-			foreach ($tool_rights as $key=>$value)
-			{
-				if($value=='View')
-				{
-					unset($current_permissions[$tool][$key]);
-				}
-				if($value=='Visibility' OR $value=='Move')
-				{
-					if(!in_array('Edit',$current_permissions[$tool]))
-					{
-						$current_permissions[$tool][]='Edit';
-					}
-					unset($current_permissions[$tool][$key]);
-				}
+			foreach ($tool_rights as $key=>$value)
+			{
+				if($value=='View')
+				{
+					unset($current_permissions[$tool][$key]);
+				}
+				if($value=='Visibility' OR $value=='Move')
+				{
+					if(!in_array('Edit',$current_permissions[$tool]))
+					{
+						$current_permissions[$tool][]='Edit';
+					}
+					unset($current_permissions[$tool][$key]);
+				}
 				//else
-				//{
-				//	$current_permissions[$tool][]=$value;
-				//}
-			}
-		}
-		return $current_permissions;
-	}
-	if(api_get_setting('permissions')=='full')
-	{
-		return $current_permissions;
-	}
-}
-/**
-* This function displays a checked or unchecked checkbox. The checkbox will be checked if the
-* user, group or role has the permission for the given tool, unchecked if the user, group or role
-* does not have the right
-* @param $permission_array the array that contains all the permissions of the user, group, role
-* @param $tool the tool we want to check a permission for
-* @param $permission the permission we want to check for
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function display_checkbox_matrix($permission_array, $tool, $permission, $inherited_permissions=array())
-{
-	$checked="";
-	if(is_array($permission_array[$tool]) AND in_array($permission,$permission_array[$tool]))
-	{
-		$checked="checked";
-	}
-	echo "\t\t\t<input type=\"checkbox\" name=\"permission*$tool*$permission\" $checked>\n";
-
-}
-
-/**
-* This function displays a checked or unchecked image. The image will be checked if the
-* user, group or role has the permission for the given tool, unchecked if the user, group or role
-* does not have the right
-* @param $permission_array the array that contains all the permissions of the user, group, role
-* @param $tool the tool we want to check a permission for
-* @param $permission the permission we want to check for
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function display_image_matrix($permission_array, $tool, $permission,$inherited_permissions=array(), $course_admin=false, $editable=true)
-{
-	if($course_admin==true)
-	{
-		echo "\t\t\t<img src=\"../img/checkbox_on3.gif\" border=\"0\"/ title=\"".get_lang('PermissionGrantedByGroupOrRole')."\">";
-	}
+				//{
+				//	$current_permissions[$tool][]=$value;
+				//}
+			}
+		}
+		return $current_permissions;
+	}
+	if(api_get_setting('permissions')=='full')
+	{
+		return $current_permissions;
+	}
+}
+/**
+* This function displays a checked or unchecked checkbox. The checkbox will be checked if the
+* user, group or role has the permission for the given tool, unchecked if the user, group or role
+* does not have the right
+* @param $permission_array the array that contains all the permissions of the user, group, role
+* @param $tool the tool we want to check a permission for
+* @param $permission the permission we want to check for
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function display_checkbox_matrix($permission_array, $tool, $permission, $inherited_permissions=array())
+{
+	$checked="";
+	if(is_array($permission_array[$tool]) AND in_array($permission,$permission_array[$tool]))
+	{
+		$checked="checked";
+	}
+	echo "\t\t\t<input type=\"checkbox\" name=\"permission*$tool*$permission\" $checked>\n";
+
+}
+
+/**
+* This function displays a checked or unchecked image. The image will be checked if the
+* user, group or role has the permission for the given tool, unchecked if the user, group or role
+* does not have the right
+* @param $permission_array the array that contains all the permissions of the user, group, role
+* @param $tool the tool we want to check a permission for
+* @param $permission the permission we want to check for
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function display_image_matrix($permission_array, $tool, $permission,$inherited_permissions=array(), $course_admin=false, $editable=true)
+{
+	if($course_admin==true)
+	{
+		echo "\t\t\t<img src=\"../img/checkbox_on3.gif\" border=\"0\"/ title=\"".get_lang('PermissionGrantedByGroupOrRole')."\">";
+	}
 	else
-	{
-		if(in_array($permission,$inherited_permissions[$tool]))
-		{
-			echo "\t\t\t<img src=\"../img/checkbox_on3.gif\" border=\"0\"/ title=\"".get_lang('PermissionGrantedByGroupOrRole')."\">";
-		}
+	{
+		if(in_array($permission,$inherited_permissions[$tool]))
+		{
+			echo "\t\t\t<img src=\"../img/checkbox_on3.gif\" border=\"0\"/ title=\"".get_lang('PermissionGrantedByGroupOrRole')."\">";
+		}
 		else
-		{
-			if(is_array($permission_array[$tool]) AND in_array($permission,$permission_array[$tool]))
-			{
-				if($editable)
-				{
-					$url=api_get_self();
-					foreach($_GET as $key=>$value)
-					{
-						$parameter[$key]=$value;
-					}
-					$parameter['action']='revoke';
-					$parameter['permission']=$permission;
-					$parameter['tool']=$tool;
-					foreach ($parameter as $key=>$value)
-					{
-						$urlparameters.=$key.'='.$value.'&amp;';
-					}
-					$url=$url.'?'.$urlparameters;
+		{
+			if(is_array($permission_array[$tool]) AND in_array($permission,$permission_array[$tool]))
+			{
+				if($editable)
+				{
+					$url=api_get_self();
+					foreach($_GET as $key=>$value)
+					{
+						$parameter[$key]=$value;
+					}
+					$parameter['action']='revoke';
+					$parameter['permission']=$permission;
+					$parameter['tool']=$tool;
+					foreach ($parameter as $key=>$value)
+					{
+						$urlparameters.=$key.'='.$value.'&amp;';
+					}
+					$url=$url.'?'.$urlparameters;
 
 					echo "\t\t\t <a href=\"".$url."\">";
-				}
-				echo "<img src=\"../img/checkbox_on2.gif\" border=\"0\"/>";
-				if($editable)
-				{
-					echo "</a>";
-				}
-			}
+				}
+				echo "<img src=\"../img/checkbox_on2.gif\" border=\"0\"/>";
+				if($editable)
+				{
+					echo "</a>";
+				}
+			}
 			else
-			{
-				if($editable)
-				{
-					$url=api_get_self();
-					foreach($_GET as $key=>$value)
-					{
-						$parameter[$key]=$value;
-					}
-					$parameter['action']='grant';
-					$parameter['permission']=$permission;
-					$parameter['tool']=$tool;
-					foreach ($parameter as $key=>$value)
-					{
-						$urlparameters.=$key.'='.$value.'&amp;';
-					}
-					$url=$url.'?'.$urlparameters;
-
-					//echo "\t\t\t <a href=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."&amp;action=grant&amp;permission=$permission&amp;tool=$tool\">";
+			{
+				if($editable)
+				{
+					$url=api_get_self();
+					foreach($_GET as $key=>$value)
+					{
+						$parameter[$key]=$value;
+					}
+					$parameter['action']='grant';
+					$parameter['permission']=$permission;
+					$parameter['tool']=$tool;
+					foreach ($parameter as $key=>$value)
+					{
+						$urlparameters.=$key.'='.$value.'&amp;';
+					}
+					$url=$url.'?'.$urlparameters;
+
+					//echo "\t\t\t <a href=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."&amp;action=grant&amp;permission=$permission&amp;tool=$tool\">";
 					echo "\t\t\t <a href=\"".$url."\">";
-				}
-				echo "<img src=\"../img/wrong.gif\" border=\"0\"/>";
-				if($editable)
-				{
-					echo "</a>";
-				}
-			}
-		}
-	}
-}
-
-
-/**
-* Slightly modified:  Toon Keppens
-* This function displays a checked or unchecked image. The image will be checked if the
-* user, group or role has the permission for the given tool, unchecked if the user, group or role
-* does not have the right
-* @param $permission_array the array that contains all the permissions of the user, group, role
-* @param $tool the tool we want to check a permission for
-* @param $permission the permission we want to check for
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function display_image_matrix_for_blogs($permission_array, $user_id, $tool, $permission,$inherited_permissions=array(), $course_admin=false, $editable=true)
-{
-
-	if($course_admin==true)
-	{
-		echo "\t\t\t<img src=\"../img/checkbox_on3.gif\" border=\"0\"/ title=\"".get_lang('PermissionGrantedByGroupOrRole')."\">";
-	}
+				}
+				echo "<img src=\"../img/wrong.gif\" border=\"0\"/>";
+				if($editable)
+				{
+					echo "</a>";
+				}
+			}
+		}
+	}
+}
+
+
+/**
+* Slightly modified:  Toon Keppens
+* This function displays a checked or unchecked image. The image will be checked if the
+* user, group or role has the permission for the given tool, unchecked if the user, group or role
+* does not have the right
+* @param $permission_array the array that contains all the permissions of the user, group, role
+* @param $tool the tool we want to check a permission for
+* @param $permission the permission we want to check for
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function display_image_matrix_for_blogs($permission_array, $user_id, $tool, $permission,$inherited_permissions=array(), $course_admin=false, $editable=true)
+{
+
+	if($course_admin==true)
+	{
+		echo "\t\t\t<img src=\"../img/checkbox_on3.gif\" border=\"0\"/ title=\"".get_lang('PermissionGrantedByGroupOrRole')."\">";
+	}
 	else
-	{
-		if(!empty($inherited_permissions) and in_array($permission,$inherited_permissions[$tool]))
-		{
-			echo "\t\t\t<img src=\"../img/checkbox_on3.gif\" border=\"0\"/ title=\"".get_lang('PermissionGrantedByGroupOrRole')."\">";
-		}
+	{
+		if(!empty($inherited_permissions) and in_array($permission,$inherited_permissions[$tool]))
+		{
+			echo "\t\t\t<img src=\"../img/checkbox_on3.gif\" border=\"0\"/ title=\"".get_lang('PermissionGrantedByGroupOrRole')."\">";
+		}
 		else
-		{
-			if(is_array($permission_array[$tool]) AND in_array($permission,$permission_array[$tool]))
-			{
-				if($editable)
-				{
-					$url=api_get_self();
-					foreach($_GET as $key=>$value)
-					{
-						$parameter[$key]=$value;
-					}
-					$parameter['action']='manage_rights';
-					$parameter['do']='revoke';
-					$parameter['permission']=$permission;
-					$parameter['tool']=$tool;
-					$parameter['user_id']=$user_id;
-					foreach ($parameter as $key=>$value)
-					{
-						$urlparameters.=$key.'='.$value.'&amp;';
-					}
-					$url=$url.'?'.$urlparameters;
+		{
+			if(is_array($permission_array[$tool]) AND in_array($permission,$permission_array[$tool]))
+			{
+				if($editable)
+				{
+					$url=api_get_self();
+					foreach($_GET as $key=>$value)
+					{
+						$parameter[$key]=$value;
+					}
+					$parameter['action']='manage_rights';
+					$parameter['do']='revoke';
+					$parameter['permission']=$permission;
+					$parameter['tool']=$tool;
+					$parameter['user_id']=$user_id;
+					foreach ($parameter as $key=>$value)
+					{
+						$urlparameters.=$key.'='.$value.'&amp;';
+					}
+					$url=$url.'?'.$urlparameters;
 
 					echo "\t\t\t <a href=\"".$url."\">";
-				}
-				echo "<img src=\"../img/checkbox_on2.gif\" border=\"0\"/ title=\"".get_lang('UserHasPermission')."\">";
-				if($editable)
-				{
-					echo "</a>";
-				}
-			}
+				}
+				echo "<img src=\"../img/checkbox_on2.gif\" border=\"0\"/ title=\"".get_lang('UserHasPermission')."\">";
+				if($editable)
+				{
+					echo "</a>";
+				}
+			}
 			else
-			{
-				if($editable)
-				{
-					$url=api_get_self();
-					foreach($_GET as $key=>$value)
-					{
-						$parameter[$key]=$value;
-					}
-					$parameter['action']='manage_rights';
-					$parameter['do']='grant';
-					$parameter['permission']=$permission;
-					$parameter['tool']=$tool;
-					$parameter['user_id']=$user_id;
-					foreach ($parameter as $key=>$value)
-					{
-						$urlparameters.=$key.'='.$value.'&amp;';
-					}
-					$url=$url.'?'.$urlparameters;
-
-					//echo "\t\t\t <a href=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."&amp;action=grant&amp;permission=$permission&amp;tool=$tool\">";
+			{
+				if($editable)
+				{
+					$url=api_get_self();
+					foreach($_GET as $key=>$value)
+					{
+						$parameter[$key]=$value;
+					}
+					$parameter['action']='manage_rights';
+					$parameter['do']='grant';
+					$parameter['permission']=$permission;
+					$parameter['tool']=$tool;
+					$parameter['user_id']=$user_id;
+					foreach ($parameter as $key=>$value)
+					{
+						$urlparameters.=$key.'='.$value.'&amp;';
+					}
+					$url=$url.'?'.$urlparameters;
+
+					//echo "\t\t\t <a href=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."&amp;action=grant&amp;permission=$permission&amp;tool=$tool\">";
 					echo "\t\t\t <a href=\"".$url."\">";
-				}
-				echo "<img src=\"../img/wrong.gif\" border=\"0\"/ title=\"".get_lang('UserHasPermissionNot')."\">";
-				if($editable)
-				{
-					echo "</a>";
-				}
-			}
-		}
-	}
-}
-
-
-/**
-* This function displays a list off all the roles of the course (and those defined by the platform admin)
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function display_role_list($current_course_roles, $current_platform_roles)
-{
+				}
+				echo "<img src=\"../img/wrong.gif\" border=\"0\"/ title=\"".get_lang('UserHasPermissionNot')."\">";
+				if($editable)
+				{
+					echo "</a>";
+				}
+			}
+		}
+	}
+}
+
+
+/**
+* This function displays a list off all the roles of the course (and those defined by the platform admin)
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function display_role_list($current_course_roles, $current_platform_roles)
+{
 	global $setting_visualisation;
 
-	$coures_roles_table=Database::get_course_table(TABLE_ROLE);
-	$platform_roles_table=Database::get_main_table(TABLE_ROLE);
-
-	// platform roles
-	$sql="SELECT * FROM $platform_roles_table";
-	$result=Database::query($sql, __FILE__, __LINE__);
-	while ($row=mysql_fetch_array($result))
-	{
-		if(in_array($row['role_id'], $current_platform_roles))
-		{
-			$checked='checked';
-			$image='checkbox_on2.gif';
-			$action='revoke';
-		}
+	$coures_roles_table=Database::get_course_table(TABLE_ROLE);
+	$platform_roles_table=Database::get_main_table(TABLE_ROLE);
+
+	// platform roles
+	$sql="SELECT * FROM $platform_roles_table";
+	$result=Database::query($sql, __FILE__, __LINE__);
+	while ($row=mysql_fetch_array($result))
+	{
+		if(in_array($row['role_id'], $current_platform_roles))
+		{
+			$checked='checked';
+			$image='checkbox_on2.gif';
+			$action='revoke';
+		}
 		else
-		{
-			$checked='';
-			$image='wrong.gif';
-			$action='grant';
-		}
-		if($setting_visualisation=='checkbox')
-		{
-			echo "<input type=\"checkbox\" name=\"role*platform*".$row['role_id']."\" $checked>";
-		}
-		if($setting_visualisation=='image')
-		{
-			echo "<a href=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."&amp;action=$action&amp;role=".$row['role_id']."&amp;scope=platform\"><img src=\"../img/".$image."\" border=\"0\"/></a>";
-		}
-		echo $row['role_name']."<br />\n";
-		echo $row['role_comment']."<br />\n";
-	}
-
-	// course roles
-	$sql="SELECT * FROM $coures_roles_table";
-	$result=Database::query($sql, __FILE__, __LINE__);
-	while ($row=mysql_fetch_array($result))
-	{
-		if(in_array($row['role_id'], $current_course_roles))
-		{
-			$checked='checked';
-			$image='checkbox_on2.gif';
-			$action='revoke';
-		}
+		{
+			$checked='';
+			$image='wrong.gif';
+			$action='grant';
+		}
+		if($setting_visualisation=='checkbox')
+		{
+			echo "<input type=\"checkbox\" name=\"role*platform*".$row['role_id']."\" $checked>";
+		}
+		if($setting_visualisation=='image')
+		{
+			echo "<a href=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."&amp;action=$action&amp;role=".$row['role_id']."&amp;scope=platform\"><img src=\"../img/".$image."\" border=\"0\"/></a>";
+		}
+		echo $row['role_name']."<br />\n";
+		echo $row['role_comment']."<br />\n";
+	}
+
+	// course roles
+	$sql="SELECT * FROM $coures_roles_table";
+	$result=Database::query($sql, __FILE__, __LINE__);
+	while ($row=mysql_fetch_array($result))
+	{
+		if(in_array($row['role_id'], $current_course_roles))
+		{
+			$checked='checked';
+			$image='checkbox_on2.gif';
+			$action='revoke';
+		}
 		else
-		{
-			$checked='';
-			$image='wrong.gif';
-			$action='grant';
-		}
-		if($setting_visualisation=='checkbox')
-		{
-			echo "<input type=\"checkbox\" name=\"role*course*".$row['role_id']."\" $checked>";
-		}
-		if($setting_visualisation=='image')
-		{
-			echo "<a href=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."&amp;action=$action&amp;role=".$row['role_id']."&amp;scope=course\"><img src=\"../img/".$image."\" border=\"0\"/></a>";
-		}
-
-
-		echo $row['role_name']." <a href=\"../permissions/roles.php?role_id=".$row['role_id']."&amp;scope=course\"><img src=\"../img/edit.gif\" /></a><br />\n";
-		echo $row['role_comment']."<br />\n";
-	}
-}
-
-/**
-* This function gets all the current roles of the user or group
-* @param $content are we finding the roles for a user or a group (the database depends on it)
-* @param $id the id of the user or group
-* @return array that contains the name of the roles the user has
+		{
+			$checked='';
+			$image='wrong.gif';
+			$action='grant';
+		}
+		if($setting_visualisation=='checkbox')
+		{
+			echo "<input type=\"checkbox\" name=\"role*course*".$row['role_id']."\" $checked>";
+		}
+		if($setting_visualisation=='image')
+		{
+			echo "<a href=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."&amp;action=$action&amp;role=".$row['role_id']."&amp;scope=course\"><img src=\"../img/".$image."\" border=\"0\"/></a>";
+		}
+
+
+		echo $row['role_name']." <a href=\"../permissions/roles.php?role_id=".$row['role_id']."&amp;scope=course\"><img src=\"../img/edit.gif\" /></a><br />\n";
+		echo $row['role_comment']."<br />\n";
+	}
+}
+
+/**
+* This function gets all the current roles of the user or group
+* @param $content are we finding the roles for a user or a group (the database depends on it)
+* @param $id the id of the user or group
+* @return array that contains the name of the roles the user has
 * @todo consider having a separate table that contains only an id and a name of the role.
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function get_roles($content,$id, $scope='course')
-{
-	if($content=='user')
-	{
-		$table=Database::get_course_table(TABLE_ROLE_USER);
-		$id_field = user_id;
-	}
-	if($content=='group')
-	{
-		$table=Database::get_course_table(TABLE_ROLE_GROUP);
-		$id_field = group_id;
-	}
-	$table_role=Database::get_course_table(TABLE_ROLE);
-
-	$current_roles=array();
-	//$sql="SELECT role.role_id FROM $table role_group_user, $table_role role WHERE role_group_user.$id_field = '$id' AND role_group_user.role_id=role.role_id AND role_group_user.scope='".$scope."'";$sql="SELECT role.role_id FROM $table role_group_user, $table_role role WHERE role_group_user.$id_field = '$id' AND role_group_user.role_id=role.role_id AND role_group_user.scope='".$scope."'";
-	$sql="SELECT role_id FROM $table WHERE $id_field = '$id' AND scope='".$scope."'";
-	$result=Database::query($sql, __FILE__, __LINE__);
-	while ($row=mysql_fetch_array($result))
-	{
-		$current_roles[]=$row['role_id'];
-	}
-
-	return $current_roles;
-}
-
-/**
-* This function gets all the current roles of the user or group
-* @return array that contains the name of the roles the user has
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function get_all_roles($content='course')
-{
-	if($content=='course')
-	{
-		$table_role=Database::get_course_table(TABLE_ROLE);
-	}
-	if($content=='platform')
-	{
-		$table_role=Database::get_main_table(TABLE_ROLE);
-	}
-
-	$current_roles=array();
-	$sql="SELECT * FROM $table_role";
-	$result=Database::query($sql, __FILE__, __LINE__);
-	while ($row=mysql_fetch_array($result))
-	{
-		$roles[]=$row;
-	}
-
-	return $roles;
-}
-
-
-/**
-* This function gets all the roles that are defined
-* @param $content are we finding the roles for a user or a group (the database depends on it)
-* @param $id the id of the user or group
-* @param string	Deprecated parameter allowing use of 'platform' scope - the corresponding tables don't exist anymore so the scope is always set to 'course'
-* @return array that contains the name of the roles the user has
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function get_roles($content,$id, $scope='course')
+{
+	if($content=='user')
+	{
+		$table=Database::get_course_table(TABLE_ROLE_USER);
+		$id_field = user_id;
+	}
+	if($content=='group')
+	{
+		$table=Database::get_course_table(TABLE_ROLE_GROUP);
+		$id_field = group_id;
+	}
+	$table_role=Database::get_course_table(TABLE_ROLE);
+
+	$current_roles=array();
+	//$sql="SELECT role.role_id FROM $table role_group_user, $table_role role WHERE role_group_user.$id_field = '$id' AND role_group_user.role_id=role.role_id AND role_group_user.scope='".$scope."'";$sql="SELECT role.role_id FROM $table role_group_user, $table_role role WHERE role_group_user.$id_field = '$id' AND role_group_user.role_id=role.role_id AND role_group_user.scope='".$scope."'";
+	$sql="SELECT role_id FROM $table WHERE $id_field = '$id' AND scope='".$scope."'";
+	$result=Database::query($sql, __FILE__, __LINE__);
+	while ($row=mysql_fetch_array($result))
+	{
+		$current_roles[]=$row['role_id'];
+	}
+
+	return $current_roles;
+}
+
+/**
+* This function gets all the current roles of the user or group
+* @return array that contains the name of the roles the user has
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function get_all_roles($content='course')
+{
+	if($content=='course')
+	{
+		$table_role=Database::get_course_table(TABLE_ROLE);
+	}
+	if($content=='platform')
+	{
+		$table_role=Database::get_main_table(TABLE_ROLE);
+	}
+
+	$current_roles=array();
+	$sql="SELECT * FROM $table_role";
+	$result=Database::query($sql, __FILE__, __LINE__);
+	while ($row=mysql_fetch_array($result))
+	{
+		$roles[]=$row;
+	}
+
+	return $roles;
+}
+
+
+/**
+* This function gets all the roles that are defined
+* @param $content are we finding the roles for a user or a group (the database depends on it)
+* @param $id the id of the user or group
+* @param string	Deprecated parameter allowing use of 'platform' scope - the corresponding tables don't exist anymore so the scope is always set to 'course'
+* @return array that contains the name of the roles the user has
 * @todo consider having a separate table that contains only an id and a name of the role.
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-* @version 1.0
-*/
-function get_roles_permissions($content,$id, $scope='course')
-{
-	if($content == 'user')
-	{
-		$table=Database::get_course_table(TABLE_ROLE_USER);
-		$id_field = user_id;
-	}
-
-	if($content == 'group')
-	{
-		$table = Database::get_course_table(TABLE_ROLE_GROUP);
-		$id_field = group_id;
-	}
-
-	// course roles or platform roles
-	$scope = 'course';
-	if($scope == 'course')
-	{
-		$table_role = Database::get_course_table(TABLE_ROLE);
-		$table_role_permissions = Database::get_course_table(TABLE_ROLE_PERMISSION);
-	}
-
-	if($scope == 'platform')
-	{
-		$table_role = Database::get_main_table(TABLE_ROLE);
-		$table_role_permissions = Database::get_main_table(TABLE_ROLE_PERMISSION);
-	}
-
-	$current_roles = array();
-
-	$sql = "
-		SELECT *
-		FROM
-			" . $table . " role_group_user,
-			" . $table_role . " role,
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+* @version 1.0
+*/
+function get_roles_permissions($content,$id, $scope='course')
+{
+	if($content == 'user')
+	{
+		$table=Database::get_course_table(TABLE_ROLE_USER);
+		$id_field = user_id;
+	}
+
+	if($content == 'group')
+	{
+		$table = Database::get_course_table(TABLE_ROLE_GROUP);
+		$id_field = group_id;
+	}
+
+	// course roles or platform roles
+	$scope = 'course';
+	if($scope == 'course')
+	{
+		$table_role = Database::get_course_table(TABLE_ROLE);
+		$table_role_permissions = Database::get_course_table(TABLE_ROLE_PERMISSION);
+	}
+
+	if($scope == 'platform')
+	{
+		$table_role = Database::get_main_table(TABLE_ROLE);
+		$table_role_permissions = Database::get_main_table(TABLE_ROLE_PERMISSION);
+	}
+
+	$current_roles = array();
+
+	$sql = "
+		SELECT *
+		FROM
+			" . $table . " role_group_user,
+			" . $table_role . " role,
 			" . $table_role_permissions . " role_permissions
-		WHERE
-			role_group_user.scope = '" . $scope . "' AND
-			role_group_user." . $id_field . " = '" . $id . "' AND
-			role_group_user.role_id = role.role_id AND
-			role.role_id = role_permissions.role_id";
-
-	$result = Database::query($sql, __FILE__, __LINE__);
-
-	while($row=mysql_fetch_array($result))
-		$current_role_permissions[$row['tool']][]=$row['action'];
-
-	return $current_role_permissions;
-}
-
-/**
-* This function is called when we assign a role to a user or a group
-* @param $content are we assigning a role to a group or a user
-* @param $action we can grant a role to a group or user or revoke it
-* @param $id the user_id of the user or the group_id of the group
-* @param $role_id the id of the role we are giving to a user or a group.
-* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
-*/
-
-function assign_role($content, $action, $id, $role_id, $scope='course')
-{
-	// Which database are we using (depending on the $content parameter)
-	if($content=='user')
-	{
-		$table=Database::get_course_table(TABLE_ROLE_USER);
-		$id_field = user_id;
-	}
-	elseif($content=='group')
-	{
-		$table=Database::get_course_table(TABLE_ROLE_GROUP);
-		$id_field = group_id;
-	}
+		WHERE
+			role_group_user.scope = '" . $scope . "' AND
+			role_group_user." . $id_field . " = '" . $id . "' AND
+			role_group_user.role_id = role.role_id AND
+			role.role_id = role_permissions.role_id";
+
+	$result = Database::query($sql, __FILE__, __LINE__);
+
+	while($row=mysql_fetch_array($result))
+		$current_role_permissions[$row['tool']][]=$row['action'];
+
+	return $current_role_permissions;
+}
+
+/**
+* This function is called when we assign a role to a user or a group
+* @param $content are we assigning a role to a group or a user
+* @param $action we can grant a role to a group or user or revoke it
+* @param $id the user_id of the user or the group_id of the group
+* @param $role_id the id of the role we are giving to a user or a group.
+* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
+*/
+
+function assign_role($content, $action, $id, $role_id, $scope='course')
+{
+	// Which database are we using (depending on the $content parameter)
+	if($content=='user')
+	{
+		$table=Database::get_course_table(TABLE_ROLE_USER);
+		$id_field = user_id;
+	}
+	elseif($content=='group')
+	{
+		$table=Database::get_course_table(TABLE_ROLE_GROUP);
+		$id_field = group_id;
+	}
 	else
-	{
-		return  get_lang('Error');
-	}
-
-	// grating a right
-	if($action=='grant')
-	{
-		$sql="INSERT INTO $table (role_id, scope,  $id_field) VALUES ('".mysql_real_escape_string($role_id)."','".mysql_real_escape_string($scope)."','".mysql_real_escape_string($id)."')";
-		$result=Database::query($sql, __FILE__, __LINE__);
-		if($result)
-		{
-			$result_message=get_lang('RoleGranted');
-		}
-	}
-	if($action=='revoke')
-	{
-		$sql="DELETE FROM $table WHERE $id_field = '".mysql_real_escape_string($id)."' AND role_id='".mysql_real_escape_string($role_id)."'";
-		$result=Database::query($sql, __FILE__, __LINE__);
-		if($result)
-		{
-			$result_message=get_lang('RoleRevoked');
-		}
-	}
-	return $result_message;
-}
-
-
-/**
-* This function merges permission arrays. Each permission array has the following structure
-* a permission array has a tool contanst as a key and an array as a value. This value array consists of all the permissions that are granted in that tool.
-*/
-function permission_array_merge($array1, $array2)
-{
-	foreach ($array2 as $tool=>$permissions)
-	{
-		foreach ($permissions as $permissionkey=>$permissionvalue)
-		{
+	{
+		return  get_lang('Error');
+	}
+
+	// grating a right
+	if($action=='grant')
+	{
+		$sql="INSERT INTO $table (role_id, scope,  $id_field) VALUES ('".mysql_real_escape_string($role_id)."','".mysql_real_escape_string($scope)."','".mysql_real_escape_string($id)."')";
+		$result=Database::query($sql, __FILE__, __LINE__);
+		if($result)
+		{
+			$result_message=get_lang('RoleGranted');
+		}
+	}
+	if($action=='revoke')
+	{
+		$sql="DELETE FROM $table WHERE $id_field = '".mysql_real_escape_string($id)."' AND role_id='".mysql_real_escape_string($role_id)."'";
+		$result=Database::query($sql, __FILE__, __LINE__);
+		if($result)
+		{
+			$result_message=get_lang('RoleRevoked');
+		}
+	}
+	return $result_message;
+}
+
+
+/**
+* This function merges permission arrays. Each permission array has the following structure
+* a permission array has a tool contanst as a key and an array as a value. This value array consists of all the permissions that are granted in that tool.
+*/
+function permission_array_merge($array1, $array2)
+{
+	foreach ($array2 as $tool=>$permissions)
+	{
+		foreach ($permissions as $permissionkey=>$permissionvalue)
+		{
 			$array1[$tool][]=$permissionvalue;
-		}
-	}
+		}
+	}
 	return $array1;
-}
-
-
-function my_print_r($array)
-{
-	echo '<pre>';
-	print_r($array);
-	echo '</pre>';
-}
+}
+
+
+function my_print_r($array)
+{
+	echo '<pre>';
+	print_r($array);
+	echo '</pre>';
+}
 ?>

+ 248 - 248
main/permissions/roles.php

@@ -1,272 +1,272 @@
 <?php
 include("../inc/claro_init_global.inc.php");
-include_once('permissions_functions.inc.php');
-include_once('all_permissions.inc.php');
-
+include_once('permissions_functions.inc.php');
+include_once('all_permissions.inc.php');
+
 $tool_name = get_lang('Roles'); // title of the page (should come from the language file)
-
-Display::display_header($tool_name);
-// ===================================================
-// 			ACTIONS
-// ===================================================
-
-// storing all the permission for a given role when the checkbox approach is used
-if ($_POST['StoreRolePermissions'])
-{
-	if (!empty($_POST['role_name']))
-	{
-		$table_role=Database::get_course_table(TABLE_ROLE);
+
+Display::display_header($tool_name);
+// ===================================================
+// 			ACTIONS
+// ===================================================
+
+// storing all the permission for a given role when the checkbox approach is used
+if ($_POST['StoreRolePermissions'])
+{
+	if (!empty($_POST['role_name']))
+	{
+		$table_role=Database::get_course_table(TABLE_ROLE);
 		$sql="INSERT INTO $table_role (role_name, role_comment, default_role)
-					VALUES ('".mysql_real_escape_string($_POST['role_name'])."','".mysql_real_escape_string($_POST['role_comment'])."','".mysql_real_escape_string($_POST['default_role'])."')";
-		$result=mysql_query($sql) or die(mysql_error());
-		$role_id=mysql_insert_id();
-		$result_message=store_permissions('role', $role_id);
-	}
+					VALUES ('".mysql_real_escape_string($_POST['role_name'])."','".mysql_real_escape_string($_POST['role_comment'])."','".mysql_real_escape_string($_POST['default_role'])."')";
+		$result=mysql_query($sql) or die(mysql_error());
+		$role_id=mysql_insert_id();
+		$result_message=store_permissions('role', $role_id);
+	}
 	else
-	{
-		$result_message=get_lang('ErrorPleaseGiveRoleName');
-	}
-}
-// storing a permission for a given role when the image approach is used
-if (isset($_GET['action']) AND isset($_GET['permission']) AND isset($_GET['tool']))
-{
-	if ($_GET['action']=='grant' OR $_GET['action']=='revoke')
-	{
-		$result_message=store_one_permission('role', $_GET['action'], $role_id, $_GET['tool'], $_GET['permission']);
-	}
-}
-
-// deleting a role
-if (isset($_GET['action']) AND isset($_GET['role_id']) AND $_GET['action']=='delete')
-{
-	//deleting the assignments fo this role: users
-	$table=Database::get_course_table(TABLE_ROLE_USER);
-	$sql="DELETE FROM $table WHERE role_id='".mysql_real_escape_string($_GET['role_id'])."'";
-	$result=Database::query($sql, __LINE__, __FILE__);
-
-	// deleting the assignments of this role: groups
-	$table=Database::get_course_table(TABLE_ROLE_GROUP);
-	$sql="DELETE FROM $table WHERE role_id='".mysql_real_escape_string($_GET['role_id'])."'";
-	$result=Database::query($sql, __LINE__, __FILE__);
-
-	// deleting the permissions of this role
-	$table=Database::get_course_table(TABLE_ROLE_PERMISSION);
-	$sql="DELETE FROM $table WHERE role_id='".mysql_real_escape_string($_GET['role_id'])."'";
-	$result=Database::query($sql, __LINE__, __FILE__);
-
-	// deleting the role
-	$table_role=Database::get_course_table(TABLE_ROLE);
-	$sql="DELETE FROM $table_role WHERE role_id='".mysql_real_escape_string($_GET['role_id'])."'";
-	$result=Database::query($sql, __LINE__, __FILE__);
-
-	$result_message=get_lang('RoleDeleted');
-}
-
-// displaying the return message of the actions
-if (isset($result_message))
-{
-	Display::display_normal_message($result_message);
-}
-
-// ===================================================
-// 		ADDING A NEW ROLE (FORM AND LINK)
-// ===================================================
-echo '<img src="../img/add.png" /> <a href="roles.php?action=add">'.get_lang('AddRole').'</a>';
-
-if ($_GET['action']=='add')
-{
-	echo "<form method=\"post\" action=\"".api_get_self()."\">";
-	echo "\n<table>";
-	echo "\n\t<tr>";
-	echo "\n\t\t<td>";
-	echo get_lang('RoleName');
-	echo "\n\t\t</td>";
-	echo "\n\t\t<td>";
-	echo "\n\t\t\t<input type='text' name='role_name'>";
-	echo "\n\t\t</td>";
-	echo "\n\t</tr>";
-	echo "\n\t<tr>";
-	echo "\n\t\t<td>";
-	echo get_lang('RoleComment');
-	echo "\n\t\t</td>";
-	echo "\n\t\t<td>";
-	echo "\n\t\t\t<textarea name='role_comment'></textarea>";
+	{
+		$result_message=get_lang('ErrorPleaseGiveRoleName');
+	}
+}
+// storing a permission for a given role when the image approach is used
+if (isset($_GET['action']) AND isset($_GET['permission']) AND isset($_GET['tool']))
+{
+	if ($_GET['action']=='grant' OR $_GET['action']=='revoke')
+	{
+		$result_message=store_one_permission('role', $_GET['action'], $role_id, $_GET['tool'], $_GET['permission']);
+	}
+}
+
+// deleting a role
+if (isset($_GET['action']) AND isset($_GET['role_id']) AND $_GET['action']=='delete')
+{
+	//deleting the assignments fo this role: users
+	$table=Database::get_course_table(TABLE_ROLE_USER);
+	$sql="DELETE FROM $table WHERE role_id='".mysql_real_escape_string($_GET['role_id'])."'";
+	$result=Database::query($sql, __LINE__, __FILE__);
+
+	// deleting the assignments of this role: groups
+	$table=Database::get_course_table(TABLE_ROLE_GROUP);
+	$sql="DELETE FROM $table WHERE role_id='".mysql_real_escape_string($_GET['role_id'])."'";
+	$result=Database::query($sql, __LINE__, __FILE__);
+
+	// deleting the permissions of this role
+	$table=Database::get_course_table(TABLE_ROLE_PERMISSION);
+	$sql="DELETE FROM $table WHERE role_id='".mysql_real_escape_string($_GET['role_id'])."'";
+	$result=Database::query($sql, __LINE__, __FILE__);
+
+	// deleting the role
+	$table_role=Database::get_course_table(TABLE_ROLE);
+	$sql="DELETE FROM $table_role WHERE role_id='".mysql_real_escape_string($_GET['role_id'])."'";
+	$result=Database::query($sql, __LINE__, __FILE__);
+
+	$result_message=get_lang('RoleDeleted');
+}
+
+// displaying the return message of the actions
+if (isset($result_message))
+{
+	Display::display_normal_message($result_message);
+}
+
+// ===================================================
+// 		ADDING A NEW ROLE (FORM AND LINK)
+// ===================================================
+echo '<img src="../img/add.png" /> <a href="roles.php?action=add">'.get_lang('AddRole').'</a>';
+
+if ($_GET['action']=='add')
+{
+	echo "<form method=\"post\" action=\"".api_get_self()."\">";
+	echo "\n<table>";
+	echo "\n\t<tr>";
+	echo "\n\t\t<td>";
+	echo get_lang('RoleName');
+	echo "\n\t\t</td>";
+	echo "\n\t\t<td>";
+	echo "\n\t\t\t<input type='text' name='role_name'>";
+	echo "\n\t\t</td>";
+	echo "\n\t</tr>";
+	echo "\n\t<tr>";
+	echo "\n\t\t<td>";
+	echo get_lang('RoleComment');
+	echo "\n\t\t</td>";
+	echo "\n\t\t<td>";
+	echo "\n\t\t\t<textarea name='role_comment'></textarea>";
+	echo "\n\t\t</td>";
+	echo "\n\t</tr>";
+	echo "\n\t<tr>";
+	echo "\n\t\t<td>";
+	echo get_lang('DefaultRole');
 	echo "\n\t\t</td>";
-	echo "\n\t</tr>";
-	echo "\n\t<tr>";
-	echo "\n\t\t<td>";
-	echo get_lang('DefaultRole');
-	echo "\n\t\t</td>";
-	echo "\n\t\t<td>";
-	echo "\n\t\t\t<input type=\"checkbox\" name=\"default_role\" value=\"1\">";
+	echo "\n\t\t<td>";
+	echo "\n\t\t\t<input type=\"checkbox\" name=\"default_role\" value=\"1\">";
 	echo "\n\t\t</td>";
 	echo "\n\t</tr>";
-	echo "\n</table>";
-	echo "<table class=\"data_table\">\n";
-
-	// the header
-	if (api_get_setting('permissions')=='limited')
-	{
-		$header_array=$rights_limited;
-	}
-	if (api_get_setting('permissions')=='full')
-	{
-		$header_array=$rights_full;
+	echo "\n</table>";
+	echo "<table class=\"data_table\">\n";
+
+	// the header
+	if (api_get_setting('permissions')=='limited')
+	{
+		$header_array=$rights_limited;
+	}
+	if (api_get_setting('permissions')=='full')
+	{
+		$header_array=$rights_full;
 	}
 	echo "\t<tr>\n";
-	echo "\t\t<th>".get_lang('Module')."</th>\n";
-	foreach ($header_array as $header_key=>$header_value)
-	{
-		echo "\t\t<th>".get_lang($header_value)."</th>\n";
-	}
-	echo "\t</tr>\n";
-
-	// the main area with the checkboxes or images
-	foreach ($tool_rights as $tool=>$rights) // $tool_rights contains all the possible tools and their rights
-	{
+	echo "\t\t<th>".get_lang('Module')."</th>\n";
+	foreach ($header_array as $header_key=>$header_value)
+	{
+		echo "\t\t<th>".get_lang($header_value)."</th>\n";
+	}
+	echo "\t</tr>\n";
+
+	// the main area with the checkboxes or images
+	foreach ($tool_rights as $tool=>$rights) // $tool_rights contains all the possible tools and their rights
+	{
 		echo "\t<tr>\n";
-		echo "\t\t<td>\n";
-		echo get_lang($tool);
+		echo "\t\t<td>\n";
+		echo get_lang($tool);
 		echo "\t\t</td>\n";
 
-		foreach ($header_array as $key=>$value)
-		{
-			echo "\t\t<td align='center'>\n";
-			display_checkbox_matrix(array(), $tool, $value);
-			echo "\t\t</td>\n";
-		}
-		echo "\t</tr>\n";
-	}
-
-	echo "</table>\n";
-
-	echo "<input type=\"Submit\" name=\"StoreRolePermissions\" value=\"".get_lang('StorePermissions')."\">";
-	echo "</form>";
-
-}
-
-
-
-// ===================================================
-// 		DISPLAYING THE EXISTING ROLES
-// ===================================================
-// platform roles
-$all_roles=get_all_roles('platform');
-foreach ($all_roles as $role)
-{
-	echo '<div><a href="roles.php?action=view&amp;role_id='.$role['role_id'].'&amp;scope=platform">'.$role['role_name'].'</a></div>';
-	echo '<div>'.$role['role_comment'].'</div><br />';
-	if ($role['role_id']==$_GET['role_id'])
-	{
-		$current_role_info=$role;
-	}
-}
-// course roles
-$all_roles=get_all_roles();
-foreach ($all_roles as $role)
-{
-	echo '<div><a href="roles.php?action=view&amp;role_id='.$role['role_id'].'">'.$role['role_name'].'</a><a href="roles.php?action=delete&amp;role_id='.$role['role_id'].'"><img src="../img/delete.gif" /></a></div>';
-	echo '<div>'.$role['role_comment'].'</div><br />';
-	if ($role['role_id']==$_GET['role_id'])
-	{
-		$current_role_info=$role;
-	}
-}
-
-// ===================================================
-// 		DISPLAYING THE PERMISSIONS OF A GIVEN ROLE
-// ===================================================
-if ($_GET['role_id'])
-{
-	$current_role_permissions=get_permissions('role',$_GET['role_id']);
-
-	// ---------------------------------------------------
-	// 			LIMITED OR FULL
-	// ---------------------------------------------------
-	$current_role_permissions=limited_or_full($current_role_permissions);
-	if (api_get_setting('permissions')=='limited')
-	{
-		$header_array=$rights_limited;
-	}
-	if (api_get_setting('permissions')=='full')
-	{
-		$header_array=$rights_full;
-	}
-	// ---------------------------------------------------
-	// 			DISPLAYING THE MATRIX
-	// ---------------------------------------------------
-	echo "<form method=\"post\" action=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."\">";
-
-	// the list of the roles for the user
-	echo get_lang('PermissionsOfRole').':'.$current_role_info['role_name'].'<br />';
-	if ($_GET['scope']=='platform')
-	{
-		echo get_lang('IsPlatformRoleNotEditable').'<br />';
-	}
-
-	echo "<table class=\"data_table\">\n";
-
-	// the header
+		foreach ($header_array as $key=>$value)
+		{
+			echo "\t\t<td align='center'>\n";
+			display_checkbox_matrix(array(), $tool, $value);
+			echo "\t\t</td>\n";
+		}
+		echo "\t</tr>\n";
+	}
+
+	echo "</table>\n";
+
+	echo "<input type=\"Submit\" name=\"StoreRolePermissions\" value=\"".get_lang('StorePermissions')."\">";
+	echo "</form>";
+
+}
+
+
+
+// ===================================================
+// 		DISPLAYING THE EXISTING ROLES
+// ===================================================
+// platform roles
+$all_roles=get_all_roles('platform');
+foreach ($all_roles as $role)
+{
+	echo '<div><a href="roles.php?action=view&amp;role_id='.$role['role_id'].'&amp;scope=platform">'.$role['role_name'].'</a></div>';
+	echo '<div>'.$role['role_comment'].'</div><br />';
+	if ($role['role_id']==$_GET['role_id'])
+	{
+		$current_role_info=$role;
+	}
+}
+// course roles
+$all_roles=get_all_roles();
+foreach ($all_roles as $role)
+{
+	echo '<div><a href="roles.php?action=view&amp;role_id='.$role['role_id'].'">'.$role['role_name'].'</a><a href="roles.php?action=delete&amp;role_id='.$role['role_id'].'"><img src="../img/delete.gif" /></a></div>';
+	echo '<div>'.$role['role_comment'].'</div><br />';
+	if ($role['role_id']==$_GET['role_id'])
+	{
+		$current_role_info=$role;
+	}
+}
+
+// ===================================================
+// 		DISPLAYING THE PERMISSIONS OF A GIVEN ROLE
+// ===================================================
+if ($_GET['role_id'])
+{
+	$current_role_permissions=get_permissions('role',$_GET['role_id']);
+
+	// ---------------------------------------------------
+	// 			LIMITED OR FULL
+	// ---------------------------------------------------
+	$current_role_permissions=limited_or_full($current_role_permissions);
+	if (api_get_setting('permissions')=='limited')
+	{
+		$header_array=$rights_limited;
+	}
+	if (api_get_setting('permissions')=='full')
+	{
+		$header_array=$rights_full;
+	}
+	// ---------------------------------------------------
+	// 			DISPLAYING THE MATRIX
+	// ---------------------------------------------------
+	echo "<form method=\"post\" action=\"".str_replace('&', '&amp;', $_SERVER['REQUEST_URI'])."\">";
+
+	// the list of the roles for the user
+	echo get_lang('PermissionsOfRole').':'.$current_role_info['role_name'].'<br />';
+	if ($_GET['scope']=='platform')
+	{
+		echo get_lang('IsPlatformRoleNotEditable').'<br />';
+	}
+
+	echo "<table class=\"data_table\">\n";
+
+	// the header
 	echo "\t<tr>\n";
-	echo "\t\t<th>".get_lang('Module')."</th>\n";
-	foreach ($header_array as $header_key=>$header_value)
-	{
-		echo "\t\t<th>".get_lang($header_value)."</th>\n";
-	}
-	echo "\t</tr>\n";
-
-	// the main area with the checkboxes or images
-	foreach ($tool_rights as $tool=>$rights) // $tool_rights contains all the possible tools and their rights
-	{
+	echo "\t\t<th>".get_lang('Module')."</th>\n";
+	foreach ($header_array as $header_key=>$header_value)
+	{
+		echo "\t\t<th>".get_lang($header_value)."</th>\n";
+	}
+	echo "\t</tr>\n";
+
+	// the main area with the checkboxes or images
+	foreach ($tool_rights as $tool=>$rights) // $tool_rights contains all the possible tools and their rights
+	{
 		echo "\t<tr>\n";
-		echo "\t\t<td>\n";
-		echo get_lang($tool);
+		echo "\t\t<td>\n";
+		echo get_lang($tool);
 		echo "\t\t</td>\n";
 
-		foreach ($header_array as $key=>$value)
-		{
-			echo "\t\t<td align='center'>\n";
-			if (in_array($value,$rights))
+		foreach ($header_array as $key=>$value)
+		{
+			echo "\t\t<td align='center'>\n";
+			if (in_array($value,$rights))
 			{
-				if ($setting_visualisation=='checkbox')
-				{
-					display_checkbox_matrix($current_role_permissions, $tool, $value);
-				}
-				if ($setting_visualisation=='image')
-				{
-					if ($_GET['scope']=='platform')
-					{
+				if ($setting_visualisation=='checkbox')
+				{
+					display_checkbox_matrix($current_role_permissions, $tool, $value);
+				}
+				if ($setting_visualisation=='image')
+				{
+					if ($_GET['scope']=='platform')
+					{
 						$roles_editable=false;
-					}
+					}
 					else
-					{
+					{
 						$roles_editable=true;
-					}
-					display_image_matrix($current_role_permissions, $tool, $value, '','',$roles_editable);
-				}
-			}
-			echo "\t\t</td>\n";
-		}
-		echo "\t</tr>\n";
-	}
-
-	echo "</table>\n";
-	if ($setting_visualisation=='checkbox')
-	{
-		echo "<input type=\"Submit\" name=\"StoreRolePermissions\" value=\"".get_lang('StorePermissions')."\">";
-	}
-	echo "</form>";
-
-
-}
-
-
-
-
-/*
-==============================================================================
+					}
+					display_image_matrix($current_role_permissions, $tool, $value, '','',$roles_editable);
+				}
+			}
+			echo "\t\t</td>\n";
+		}
+		echo "\t</tr>\n";
+	}
+
+	echo "</table>\n";
+	if ($setting_visualisation=='checkbox')
+	{
+		echo "<input type=\"Submit\" name=\"StoreRolePermissions\" value=\"".get_lang('StorePermissions')."\">";
+	}
+	echo "</form>";
+
+
+}
+
+
+
+
+/*
+==============================================================================
 		FOOTER
-==============================================================================
+==============================================================================
 */
-Display::display_footer();
+Display::display_footer();
 ?>

+ 85 - 85
main/plugin/hotspot/jsmethods.js

@@ -1,86 +1,86 @@
-// Globals
-// Major version of Flash required
-var requiredMajorVersion = 7;
-// Minor version of Flash required
-var requiredMinorVersion = 0;
-// Minor version of Flash required
-var requiredRevision = 0;
-// the version of javascript supported
-var jsVersion = 1.0;
+// Globals
+// Major version of Flash required
+var requiredMajorVersion = 7;
+// Minor version of Flash required
+var requiredMinorVersion = 0;
+// Minor version of Flash required
+var requiredRevision = 0;
+// the version of javascript supported
+var jsVersion = 1.0;
 //
-
-var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
-var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
-var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
-jsVersion = 1.1;
-// JavaScript helper required to detect Flash Player PlugIn version information
-function JSGetSwfVer(i){
-	// NS/Opera version >= 3 check for Flash plugin in plugin array
-	if (navigator.plugins != null && navigator.plugins.length > 0) {
-		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
-			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
-      		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
-			descArray = flashDescription.split(" ");
-			tempArrayMajor = descArray[2].split(".");
-			versionMajor = tempArrayMajor[0];
-			versionMinor = tempArrayMajor[1];
-			if ( descArray[3] != "" ) {
-				tempArrayMinor = descArray[3].split("r");
-			} else {
-				tempArrayMinor = descArray[4].split("r");
-			}
-      		versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
-            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
-      	} else {
-			flashVer = -1;
-		}
-	}
-	// MSN/WebTV 2.6 supports Flash 4
-	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
-	// WebTV 2.5 supports Flash 3
-	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
-	// older WebTV supports Flash 2
-	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
-	// Can\'t detect in all other cases
-	else {
-
-		flashVer = -1;
-	}
-	return flashVer;
-}
-// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
-function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
-{
- 	reqVer = parseFloat(reqMajorVer + "." + reqRevision);
-   	// loop backwards through the versions until we find the newest version
-	for (i=25;i>0;i--) {
-		if (isIE && isWin && !isOpera) {
-			versionStr = VBGetSwfVer(i);
-		} else {
-			versionStr = JSGetSwfVer(i);
-		}
-		if (versionStr == -1 ) {
-			return false;
-		} else if (versionStr != 0) {
-			if(isIE && isWin && !isOpera) {
-				tempArray         = versionStr.split(" ");
-				tempString        = tempArray[1];
-				versionArray      = tempString .split(",");
-			} else {
-				versionArray      = versionStr.split(".");
-			}
-			versionMajor      = versionArray[0];
-			versionMinor      = versionArray[1];
-			versionRevision   = versionArray[2];
-
-			versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
-			versionNum        = parseFloat(versionString);
-        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
-			if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
-				return true;
-			} else {
-				return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
-			}
-		}
-	}
-}
+
+var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
+var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
+var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
+jsVersion = 1.1;
+// JavaScript helper required to detect Flash Player PlugIn version information
+function JSGetSwfVer(i){
+	// NS/Opera version >= 3 check for Flash plugin in plugin array
+	if (navigator.plugins != null && navigator.plugins.length > 0) {
+		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
+			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
+      		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
+			descArray = flashDescription.split(" ");
+			tempArrayMajor = descArray[2].split(".");
+			versionMajor = tempArrayMajor[0];
+			versionMinor = tempArrayMajor[1];
+			if ( descArray[3] != "" ) {
+				tempArrayMinor = descArray[3].split("r");
+			} else {
+				tempArrayMinor = descArray[4].split("r");
+			}
+      		versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
+            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
+      	} else {
+			flashVer = -1;
+		}
+	}
+	// MSN/WebTV 2.6 supports Flash 4
+	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
+	// WebTV 2.5 supports Flash 3
+	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
+	// older WebTV supports Flash 2
+	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
+	// Can\'t detect in all other cases
+	else {
+
+		flashVer = -1;
+	}
+	return flashVer;
+}
+// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
+function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
+{
+ 	reqVer = parseFloat(reqMajorVer + "." + reqRevision);
+   	// loop backwards through the versions until we find the newest version
+	for (i=25;i>0;i--) {
+		if (isIE && isWin && !isOpera) {
+			versionStr = VBGetSwfVer(i);
+		} else {
+			versionStr = JSGetSwfVer(i);
+		}
+		if (versionStr == -1 ) {
+			return false;
+		} else if (versionStr != 0) {
+			if(isIE && isWin && !isOpera) {
+				tempArray         = versionStr.split(" ");
+				tempString        = tempArray[1];
+				versionArray      = tempString .split(",");
+			} else {
+				versionArray      = versionStr.split(".");
+			}
+			versionMajor      = versionArray[0];
+			versionMinor      = versionArray[1];
+			versionRevision   = versionArray[2];
+
+			versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
+			versionNum        = parseFloat(versionString);
+        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
+			if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
+				return true;
+			} else {
+				return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
+			}
+		}
+	}
+}

+ 6 - 6
main/reservation/index.html

@@ -1,7 +1,7 @@
-<html>
-<head>
-<meta http-equiv="refresh" content="0; url=mysubscriptions.php">
-</head>
-<body>
-</body>
+<html>
+<head>
+<meta http-equiv="refresh" content="0; url=mysubscriptions.php">
+</head>
+<body>
+</body>
 </html>

+ 146 - 146
main/reservation/m_category.php

@@ -1,149 +1,149 @@
-<?php
-// $Id: m_category.php,v 1.2 2006/05/09 08:51:14 kvansteenkiste Exp $
-/*
-==============================================================================
-    Dokeos - elearning and course management software
-
-    Copyright (c) 2004-2008 Dokeos SPRL
-    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
-    Copyright (c) Kristof Van Steenkiste
-    Copyright (c) Julio Montoya Armas
-
-    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
-==============================================================================
-*/
+<?php
+// $Id: m_category.php,v 1.2 2006/05/09 08:51:14 kvansteenkiste Exp $
+/*
+==============================================================================
+    Dokeos - elearning and course management software
+
+    Copyright (c) 2004-2008 Dokeos SPRL
+    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
+    Copyright (c) Kristof Van Steenkiste
+    Copyright (c) Julio Montoya Armas
+
+    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
+==============================================================================
+*/
+/**
+    ---------------------------------------------------------------------
+                Category-manager (add, edit & delete)
+    ---------------------------------------------------------------------
+ */
+require_once('rsys.php');
+
+$language_file = 'admin';
+$cidReset = true;
+require ('../inc/global.inc.php');
+$this_section = SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+
+Rsys :: protect_script('m_category');
+$tool_name = get_lang('BookingSystem');
+$interbreadcrumb[] = array ("url" => "../admin/index.php", "name" => get_lang('PlatformAdmin'));
+
+/**
+    ---------------------------------------------------------------------
+ */
+
 /**
-    ---------------------------------------------------------------------
-                Category-manager (add, edit & delete)
-    ---------------------------------------------------------------------
- */
-require_once('rsys.php');
-
-$language_file = 'admin';
-$cidReset = true;
-require ('../inc/global.inc.php');
-$this_section = SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script();
-
-Rsys :: protect_script('m_category');
-$tool_name = get_lang('BookingSystem');
-$interbreadcrumb[] = array ("url" => "../admin/index.php", "name" => get_lang('PlatformAdmin'));
-
-/**
-    ---------------------------------------------------------------------
- */
-
-/**
- *  Filter to display the modify-buttons
+ *  Filter to display the modify-buttons
  *
- *  @param - int $id The ResourceType-id
- */
-function modify_filter($id) {
-	return '<a href="m_category.php?action=edit&amp;id='.$id.'" title="'.get_lang("EditResourceType").'"><img alt="" src="../img/edit.gif" /></a>'.' <a href="m_category.php?action=delete&amp;id='.$id.'" title="'.get_lang("DeleteResourceType").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteResourceType")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-switch ($_GET['action']) {
-	case 'add' :
-		$interbreadcrumb[] = array ("url" => "m_category.php", "name" => $tool_name);
-		Display :: display_header(get_lang('AddNewResourceType'));
-		api_display_tool_title(get_lang('AddNewResourceType'));
-		$form = new FormValidator('category', 'post', 'm_category.php?action=add');
-		$form->add_textfield('name', get_lang('ResourceTypeName'), true, array ('maxlength' => '128'));
-		$form->addElement('style_submit_button', 'submit', get_lang('CreateResourceType'),'class="add"');
-		if ($form->validate()) {
-			$values = $form->exportValues();
-			if (Rsys :: add_category($values['name']))
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceTypeAdded'), "m_category.php", $tool_name),false);
-			else
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceTypeExist'), "m_category.php?action=add", get_lang('AddNewResourceType')),false);
-		} else
-			$form->display();
-		break;
-	case 'edit' :
-		$interbreadcrumb[] = array ("url" => "m_category.php", "name" => $tool_name);
-		Display :: display_header(get_lang('EditResourceType'));
-		api_display_tool_title(get_lang('EditResourceType'));
-		$form = new FormValidator('category', 'post', 'm_category.php?action=edit');
-		$form->add_textfield('name', get_lang('ResourceTypeName'), true, array ('maxlength' => '128'));
-		$form->addElement('hidden', 'id', $_GET['id']);
-		$form->addElement('style_submit_button', 'submit', get_lang('ModifyResourceType'),'class="save"');
-		$form->setDefaults(Rsys :: get_category($_GET['id']));
-		if ($form->validate()) {
-			$values = $form->exportValues();
-			if (Rsys :: edit_category($values['id'], $values['name']))
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceTypeEdited'), "m_category.php", $tool_name),false);
-			else
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceTypeExist'), "m_category.php?action=edit&id=".$values['id'], get_lang('EditRight')),false);
-		} else
-			$form->display();
-		break;
-	case 'delete' :
-		$result = Rsys :: delete_category($_GET['id']);
-		ob_start();
-		if ($result == 0)
-			Display :: display_normal_message(get_lang('ResourceTypeDeleted'),false);
-		else
-			Display :: display_normal_message(str_replace('#NUM#', $result, get_lang('ResourceTypeHasItems')),false);
-		$msg = ob_get_contents();
-		ob_end_clean();
-	default :
-		$NoSearchResults = get_lang('NoCategories');
-		Display :: display_header($tool_name);
-		api_display_tool_title($tool_name);
+ *  @param - int $id The ResourceType-id
+ */
+function modify_filter($id) {
+	return '<a href="m_category.php?action=edit&amp;id='.$id.'" title="'.get_lang("EditResourceType").'"><img alt="" src="../img/edit.gif" /></a>'.' <a href="m_category.php?action=delete&amp;id='.$id.'" title="'.get_lang("DeleteResourceType").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteResourceType")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+switch ($_GET['action']) {
+	case 'add' :
+		$interbreadcrumb[] = array ("url" => "m_category.php", "name" => $tool_name);
+		Display :: display_header(get_lang('AddNewResourceType'));
+		api_display_tool_title(get_lang('AddNewResourceType'));
+		$form = new FormValidator('category', 'post', 'm_category.php?action=add');
+		$form->add_textfield('name', get_lang('ResourceTypeName'), true, array ('maxlength' => '128'));
+		$form->addElement('style_submit_button', 'submit', get_lang('CreateResourceType'),'class="add"');
+		if ($form->validate()) {
+			$values = $form->exportValues();
+			if (Rsys :: add_category($values['name']))
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceTypeAdded'), "m_category.php", $tool_name),false);
+			else
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceTypeExist'), "m_category.php?action=add", get_lang('AddNewResourceType')),false);
+		} else
+			$form->display();
+		break;
+	case 'edit' :
+		$interbreadcrumb[] = array ("url" => "m_category.php", "name" => $tool_name);
+		Display :: display_header(get_lang('EditResourceType'));
+		api_display_tool_title(get_lang('EditResourceType'));
+		$form = new FormValidator('category', 'post', 'm_category.php?action=edit');
+		$form->add_textfield('name', get_lang('ResourceTypeName'), true, array ('maxlength' => '128'));
+		$form->addElement('hidden', 'id', $_GET['id']);
+		$form->addElement('style_submit_button', 'submit', get_lang('ModifyResourceType'),'class="save"');
+		$form->setDefaults(Rsys :: get_category($_GET['id']));
+		if ($form->validate()) {
+			$values = $form->exportValues();
+			if (Rsys :: edit_category($values['id'], $values['name']))
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceTypeEdited'), "m_category.php", $tool_name),false);
+			else
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceTypeExist'), "m_category.php?action=edit&id=".$values['id'], get_lang('EditRight')),false);
+		} else
+			$form->display();
+		break;
+	case 'delete' :
+		$result = Rsys :: delete_category($_GET['id']);
+		ob_start();
+		if ($result == 0)
+			Display :: display_normal_message(get_lang('ResourceTypeDeleted'),false);
+		else
+			Display :: display_normal_message(str_replace('#NUM#', $result, get_lang('ResourceTypeHasItems')),false);
+		$msg = ob_get_contents();
+		ob_end_clean();
+	default :
+		$NoSearchResults = get_lang('NoCategories');
+		Display :: display_header($tool_name);
+		api_display_tool_title($tool_name);
+
+		echo $msg;
+		echo '<div class="actions">';
+		echo '<a href="m_category.php?action=add"><img src="../img/view_more_stats.gif" border="0" alt="" title="'.get_lang('AddNewBookingPeriod').'"/>'.get_lang('AddNewResourceType').'</a><br />';
+		echo '</div>';
+		if (isset ($_POST['action'])) {
+			switch ($_POST['action']) {
+				case 'delete_categories' :
+					$ids = $_POST['categories'];
+					if (count($ids) > 0) {
+						foreach ($ids as $index => $id) {
+							$result = Rsys :: delete_category($id);
+							if ($result != 0)
+								$warning = true;
+						}
+					}
+					if ($warning) {
+						ob_start();
+						Display :: display_normal_message(get_lang('ResourceTypeNotDeleted'),false);
+						$msg2 = ob_get_contents();
+						ob_end_clean();
+					}
+					break;
+			}
+		}
+		echo $msg2;
+		$table = new SortableTable('category', array ('Rsys', 'get_num_categories'), array ('Rsys', 'get_table_categories'), 1);
+		$table->set_header(0, '', false, array ('style' => 'width:10px'));
+		$table->set_header(1, '', false);
+		$table->set_header(2, '', false, array ('style' => 'width:50px;'));
+		$table->set_column_filter(2, 'modify_filter');
+		$table->set_form_actions(array ('delete_categories' => get_lang('DeleteSelectedCategories')), 'categories');
+		$table->display();
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
 
-		echo $msg;
-		echo '<div class="actions">';
-		echo '<a href="m_category.php?action=add"><img src="../img/view_more_stats.gif" border="0" alt="" title="'.get_lang('AddNewBookingPeriod').'"/>'.get_lang('AddNewResourceType').'</a><br />';
-		echo '</div>';
-		if (isset ($_POST['action'])) {
-			switch ($_POST['action']) {
-				case 'delete_categories' :
-					$ids = $_POST['categories'];
-					if (count($ids) > 0) {
-						foreach ($ids as $index => $id) {
-							$result = Rsys :: delete_category($id);
-							if ($result != 0)
-								$warning = true;
-						}
-					}
-					if ($warning) {
-						ob_start();
-						Display :: display_normal_message(get_lang('ResourceTypeNotDeleted'),false);
-						$msg2 = ob_get_contents();
-						ob_end_clean();
-					}
-					break;
-			}
-		}
-		echo $msg2;
-		$table = new SortableTable('category', array ('Rsys', 'get_num_categories'), array ('Rsys', 'get_table_categories'), 1);
-		$table->set_header(0, '', false, array ('style' => 'width:10px'));
-		$table->set_header(1, '', false);
-		$table->set_header(2, '', false, array ('style' => 'width:50px;'));
-		$table->set_column_filter(2, 'modify_filter');
-		$table->set_form_actions(array ('delete_categories' => get_lang('DeleteSelectedCategories')), 'categories');
-		$table->display();
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-Display :: display_footer();
-?>
+Display :: display_footer();
+?>

+ 474 - 474
main/reservation/m_item.php

@@ -1,478 +1,478 @@
-<?php
-// $Id: m_item.php,v 1.13 2006/05/11 14:29:52 sjacobs Exp $
-/*
-==============================================================================
-    Dokeos - elearning and course management software
-
-    Copyright (c) 2004-2008 Dokeos SPRL
-    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
-    Copyright (c) Kristof Van Steenkiste
-    Copyright (c) Julio Montoya Armas
-
-    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
-==============================================================================
-*/
-/**
-    ---------------------------------------------------------------------
-                Item-manager (add, edit & delete)
-    ---------------------------------------------------------------------
- */
-require_once ('rsys.php');
-Rsys :: protect_script('m_item');
-$tool_name = get_lang('ResourceList');
-//$interbreadcrumb[] = array ("url" => "../admin/index.php", "name" => get_lang('PlatformAdmin'));
-
-/**
-    ---------------------------------------------------------------------
- */
-
-/**
- *  Filter to display the modify-buttons
- *
- *  @param  -   int     $id     The item-id
- */
-function modify_filter($id) {
-    $str='';
+<?php
+// $Id: m_item.php,v 1.13 2006/05/11 14:29:52 sjacobs Exp $
+/*
+==============================================================================
+    Dokeos - elearning and course management software
+
+    Copyright (c) 2004-2008 Dokeos SPRL
+    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
+    Copyright (c) Kristof Van Steenkiste
+    Copyright (c) Julio Montoya Armas
+
+    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
+==============================================================================
+*/
+/**
+    ---------------------------------------------------------------------
+                Item-manager (add, edit & delete)
+    ---------------------------------------------------------------------
+ */
+require_once ('rsys.php');
+Rsys :: protect_script('m_item');
+$tool_name = get_lang('ResourceList');
+//$interbreadcrumb[] = array ("url" => "../admin/index.php", "name" => get_lang('PlatformAdmin'));
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+/**
+ *  Filter to display the modify-buttons
+ *
+ *  @param  -   int     $id     The item-id
+ */
+function modify_filter($id) {
+    $str='';
 	$outtt=false;
-	if(Rsys::item_allow($id,'edit')){
-        $number = Rsys :: get_item($id);
-        //checking the status
-        if ($number[5]==1) {
-        	$str.= ' <a href="m_item.php?action=blackout&amp;id='.$id.'" title="'.get_lang('Inactive').'"><img alt="" src="../img/wrong.gif" /></a>';
+	if(Rsys::item_allow($id,'edit')){
+        $number = Rsys :: get_item($id);
+        //checking the status
+        if ($number[5]==1) {
+        	$str.= ' <a href="m_item.php?action=blackout&amp;id='.$id.'" title="'.get_lang('Inactive').'"><img alt="" src="../img/wrong.gif" /></a>';
         } else {
-        	$str.= ' <a href="m_item.php?action=blackout&amp;id='.$id.'" title="'.get_lang('Active').'"><img alt="" src="../img/right.gif" /></a>';
-        }
-    }
-
-    if(Rsys::item_allow($id,'edit')){
-        $str.='<a href="m_item.php?action=edit&amp;id='.$id.'" title="'.get_lang("EditItem2").'"><img alt="" src="../img/edit.gif" /></a>';
-    }
-    //if(Rsys::item_allow($id,'m_rights')) $str.=' &nbsp;<a href="m_item.php?action=m_rights&amp;item_id='.$id.'" title="'.get_lang("MRights").'"><img alt="" src="../img/info_small.gif" /></a>';
-    if(Rsys::item_allow($id,'delete')) $str.=' <a href="m_item.php?action=delete&amp;id='.$id.'" title="'.get_lang('DeleteResource').'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteResource")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
-
-    return $str;
-}
-
-/**
- *  Filter to display the modify-buttons
- *
- *  @param  -   int     $id     The item-rights-id's
- */
-function modify_rights_filter($id) {
-	return ' <a href="m_item.php?action=m_rights&amp;subaction=delete&amp;item_id='.substr($id, 0, strpos($id, '-')).'&amp;class_id='.substr($id, strrpos($id, '-') + 1).'" title="'.get_lang("RemoveClassRights").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteResource")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-if (isset ($_POST['action'])) {
-	switch ($_POST['action']) {
-		case 'delete_items' :
-			$ids = $_POST['items'];
-			$warning = false;
-			if (count($ids) > 0) {
-				foreach ($ids as $id) {
-					$result = Rsys :: delete_item($id);
-					if ($result != 0 && $warning <> true)
-						$warning = true;
-				}
-				ob_start();
-				if ($warning) {
-					Display :: display_normal_message(get_lang('ItemNotDeleted'), false);
-
-				} else {
-
-					Display :: display_normal_message(get_lang('ResourceDeleted'), false);
-				}
-				$msg = ob_get_contents();
-				ob_end_clean();
-			}
-			break;
-		case 'delete_itemrights' :
-			$ids = $_POST['itemrights'];
-			if (count($ids) > 0) {
-				foreach ($ids as $id)
-					Rsys :: delete_item_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1));
-				ob_start();
-				Display :: display_normal_message(get_lang('ItemRightDeleted'),false);
-				$msg = ob_get_contents();
-				ob_end_clean();
-				$_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-			} else {
-				header("Location: ".$_SERVER['HTTP_REFERER']);
-				exit ();
-			}
-			$_GET['action'] = 'm_rights';
-			break;
-        case 'set_r_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 1);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-       case 'unset_r_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 0);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-      case 'set_edit_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 1);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'unset_edit_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 0);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'set_delete_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 1);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'unset_delete_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 0);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'set_mres_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 1);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'unset_mres_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 0);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-       case 'set_all_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id){
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 1);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 1);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 1);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 1);
-                }
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'unset_all_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id){
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 0);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 0);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 0);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 0);
-                }
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-	}
-}
-switch ($_GET['action']) {
-	case 'm_rights' :
-        if(!Rsys::item_allow($_GET['item_id'],'m_rights')) die('No Access!');
-		switch ($_GET['subaction']) {
-			case 'edit' :
-				$item = Rsys :: get_item($_GET['item_id']);
-				$classDB = Rsys :: get_class_group($_GET['class_id']);
-				$item_rights = Rsys :: get_item_rights($_GET['item_id'], $_GET['class_id']);
-
-				$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-
-				$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
-				$interbreadcrumb[] = array ("url" => "m_item.php?&action=m_rights&id=".$item['id'], "name" => str_replace('#ITEM#', $item['name'], get_lang('MItemRights')));
-
-				Display :: display_header(get_lang('EditRight'));
-				api_display_tool_title(get_lang('EditRight'));
-				$form = new FormValidator('itemright', 'post', "m_item.php?id=".$item['id']."&action=m_rights&subaction=edit");
-
-				$form->add_textfield('classn', get_lang('Class'), true, array ('readonly' => 'readonly'));
-
-				$form->addElement('checkbox', 'edit_right', get_lang('EditRight'));
-				$form->addElement('checkbox', 'delete_right', get_lang('DeleteRight'));
-				$form->addElement('checkbox', 'm_reservation', get_lang('MReservationRight'));
-
-				$form->addElement('hidden', 'item_id', $item['id']);
-				$form->addElement('hidden', 'class_id', $_GET['class_id']);
-
-				$item_right['classn'] = $classDB[0]['name'];
-				$item_right['edit_right'] = $item_rights[0]['edit_right'];
-				$item_right['delete_right'] = $item_rights[0]['delete_right'];
-				$item_right['m_reservation'] = $item_rights[0]['m_reservation'];
-				$form->setDefaults($item_right);
-
-				$form->addElement('style_submit_button', 'submit', get_lang('Ok'),'class="save"');
-				if ($form->validate()) {
-					$values = $form->exportValues();
-					Rsys :: edit_item_right($values['item_id'], $values['class_id'], $values['edit_right'], $values['delete_right'], $values['m_reservation']);
-					Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemRightEdited'), "m_item.php?id=".$_GET['id']."&action=m_rights", str_replace('#ITEM#', $item['name'], get_lang('MItemRights'))),false);
-				} else
-					$form->display();
-				break;
-			case 'delete' :
-				Rsys :: delete_item_right($_GET['item_id'], $_GET['class_id']);
-				ob_start();
-				Display :: display_normal_message(get_lang('ItemRightDeleted'),false);
-				$msg = ob_get_contents();
-				ob_end_clean();
-			case 'switch' :
-				switch ($_GET['switch']) {
-					case 'edit' :
-						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'edit_right', $_GET['set']);
-						break;
-					case 'delete' :
-						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'delete_right', $_GET['set']);
-						break;
-					case 'manage' :
-						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'm_reservation', $_GET['set']);
-						break;
-					case 'view' :
-                        Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'view_right', $_GET['set']);
-                        break;
-				}
-			default :
-				$item = Rsys :: get_item($_GET['item_id']);
-				$NoSearchResults = get_lang('NoRights');
-
-
-				$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-				$interbreadcrumb[] = array ("url" => "m_item.php", "name" => get_lang('ManageResources'));
-				Display :: display_header(str_replace('#ITEM#', $item['name'], get_lang('MItemRights')));
-
-				api_display_tool_title(get_lang('MItemRights2'));
-
-				echo $msg;
-				$_s_item['id'] = $_GET['item_id'];
-				$_s_item['name'] = $item['name'];
-				api_session_register('_s_item');
-				//api_session_register('s_item_name');
-				//echo "<a href=\"m_item.php?action=add_classgroup\">".get_lang('MAddClassgroup')."</a>";
-				$table = new SortableTable('itemrights', array ('Rsys', 'get_num_itemrights'), array ('Rsys', 'get_table_itemrights'), 1);
-				$table->set_header(0, '', false, array ('style' => 'width:10px'));
-				$table->set_additional_parameters(array('action'=>'m_rights','item_id'=>$_GET['item_id']));
-				$table->set_header(1, get_lang('Class'), false);
-                $table->set_header(2, get_lang('EditItemRight'), false);
-				$table->set_header(3, get_lang('DeleteItemRight'), false);
-				$table->set_header(4, get_lang('MBookingPeriodsRight'), false);
-                $table->set_header(5, get_lang('ViewItemRight'), false);
-				$table->set_header(6, '', false, array ('style' => 'width:50px;'));
-				$table->set_column_filter(6, 'modify_rights_filter');
-				$table->set_form_actions(array (
-                                        'delete_itemrights'     => get_lang('DeleteSelectedItemRights'),
-                                        'set_edit_rights'       => get_lang('SetEditRights'),
-                                        'unset_edit_rights'     => get_lang('UnsetEditRights'),
-                                        'set_delete_rights'     => get_lang('SetDeleteRights'),
-                                        'unset_delete_rights'   => get_lang('UnsetDeleteRights'),
-                                        'set_mres_rights'       => get_lang('SetMresRights'),
-                                        'unset_mres_rights'     => get_lang('UnsetMresRights'),
-                                        'set_r_rights'          => get_lang('SetViewRights'),
-                                        'unset_r_rights'        => get_lang('UnsetViewRights'),
-                                        'set_all_rights'        => get_lang('SetAllRights'),
-                                        'unset_all_rights'      => get_lang('UnsetAllRights')
-                                        ), 'itemrights');
-				$table->display();
-		}
-		break;
-	case 'add' :
-
-		$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-
-		$interbreadcrumb[] = array ("url" => "m_item.php", "name" => get_lang('ManageResources'));
-
-		//$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
-		Display :: display_header(get_lang('AddNewResource'));
-		api_display_tool_title(get_lang('AddNewResource'));
-		$form = new FormValidator('item', 'post', 'm_item.php?action=add');
-		$cats = Rsys :: get_category();
-		foreach ($cats as $cat)
-			$catOptions[$cat['id']] = $cat['name'];
-		$form->addElement('select', 'category', get_lang('ResourceType'), $catOptions);
-		$form->add_textfield('name', get_lang('ResourceName'), true, array ('maxlength' => '128'));
-		$form->addElement('textarea', 'description', get_lang('Description'), array ('rows' => '3', 'cols' => '40'));
-		$form->addRule('category', get_lang('ThisFieldIsRequired'), 'required');
-
-		// TODO: get list of courses (to link it to the item)
-		//$form->addElement('select', 'course_code', get_lang('ItemCourse'),array(''=>'','value'=>'tag'));
-		//$form->addRule('course', get_lang('ThisFieldIsRequired'), 'required');
-
-		$form->addElement('style_submit_button', 'submit', get_lang('AddNewResource'),'class="add"');
-		if ($form->validate()) {
-			$values = $form->exportValues();
-			if (Rsys :: add_item($values['name'], $values['description'], $values['category'], $values['course_code']))
-			{
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceAdded'), "m_item.php?action=m_rights&item_id=".Rsys :: get_item_id($values['name']), get_lang('MItemRight').' '.$values['name']),false);
-			}
-			else
-			{
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceExist'), "m_item.php?action=add", get_lang('AddNewResource')),false);
-			}
-		} else
-			$form->display();
-		break;
-	case 'edit' :
-		$item = Rsys :: get_item($_GET['id']);
-		$cats = Rsys :: get_category();
-		foreach ($cats as $cat)
-			$catOptions[$cat['id']] = $cat['name'];
-
-		$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-
-		$interbreadcrumb[] = array ("url" => "m_item.php", "name" => get_lang('ManageResources'));
-
-		Display :: display_header(str_replace('#ITEM#', $item['name'], get_lang('EditResource')));
-		api_display_tool_title(get_lang('EditResource'));
-		$form = new FormValidator('item', 'post', 'm_item.php?action=edit');
-		$form->addElement('select', 'category_id', get_lang('ResourceType'), $catOptions);
-		$form->add_textfield('name', get_lang('ResourceName'), array ('maxlength' => '128'));
-		$form->addElement('textarea', 'description', get_lang('Description'), array ('rows' => '3', 'cols' => '40'));
-		$form->addRule('category_id', get_lang('ThisFieldIsRequired'), 'required');
-		$form->addElement('hidden', 'id', $item['id']);
-		$form->addElement('style_submit_button', 'submit', get_lang('EditResource'),'class="save"');
-		$form->setDefaults($item);
-		if ($form->validate()) {
-			$values = $form->exportValues();
-			if (Rsys :: edit_item($values['id'], $values['name'], $values['description'], $values['category_id'], $values['course_id']))
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceEdited'), "m_item.php", $tool_name),false);
-			else
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceExist'), "m_item.php?action=edit&id=".$values['id'], get_lang('EditItem2')),false);
-		} else
-			$form->display();
-		break;
-	case 'delete' :
-		$result = Rsys :: delete_item($_GET['id']);
-		ob_start();
-		if($result == '0'){
-			Display :: display_normal_message(get_lang('ResourceDeleted'),false);}
-		else
-			Display :: display_normal_message(str_replace('#NUM#', $result, get_lang('ItemHasReservations')),false);
-		$msg = ob_get_contents();
-		ob_end_clean();
-	default :
+        	$str.= ' <a href="m_item.php?action=blackout&amp;id='.$id.'" title="'.get_lang('Active').'"><img alt="" src="../img/right.gif" /></a>';
+        }
+    }
+
+    if(Rsys::item_allow($id,'edit')){
+        $str.='<a href="m_item.php?action=edit&amp;id='.$id.'" title="'.get_lang("EditItem2").'"><img alt="" src="../img/edit.gif" /></a>';
+    }
+    //if(Rsys::item_allow($id,'m_rights')) $str.=' &nbsp;<a href="m_item.php?action=m_rights&amp;item_id='.$id.'" title="'.get_lang("MRights").'"><img alt="" src="../img/info_small.gif" /></a>';
+    if(Rsys::item_allow($id,'delete')) $str.=' <a href="m_item.php?action=delete&amp;id='.$id.'" title="'.get_lang('DeleteResource').'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteResource")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
+
+    return $str;
+}
+
+/**
+ *  Filter to display the modify-buttons
+ *
+ *  @param  -   int     $id     The item-rights-id's
+ */
+function modify_rights_filter($id) {
+	return ' <a href="m_item.php?action=m_rights&amp;subaction=delete&amp;item_id='.substr($id, 0, strpos($id, '-')).'&amp;class_id='.substr($id, strrpos($id, '-') + 1).'" title="'.get_lang("RemoveClassRights").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteResource")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+if (isset ($_POST['action'])) {
+	switch ($_POST['action']) {
+		case 'delete_items' :
+			$ids = $_POST['items'];
+			$warning = false;
+			if (count($ids) > 0) {
+				foreach ($ids as $id) {
+					$result = Rsys :: delete_item($id);
+					if ($result != 0 && $warning <> true)
+						$warning = true;
+				}
+				ob_start();
+				if ($warning) {
+					Display :: display_normal_message(get_lang('ItemNotDeleted'), false);
+
+				} else {
+
+					Display :: display_normal_message(get_lang('ResourceDeleted'), false);
+				}
+				$msg = ob_get_contents();
+				ob_end_clean();
+			}
+			break;
+		case 'delete_itemrights' :
+			$ids = $_POST['itemrights'];
+			if (count($ids) > 0) {
+				foreach ($ids as $id)
+					Rsys :: delete_item_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1));
+				ob_start();
+				Display :: display_normal_message(get_lang('ItemRightDeleted'),false);
+				$msg = ob_get_contents();
+				ob_end_clean();
+				$_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+			} else {
+				header("Location: ".$_SERVER['HTTP_REFERER']);
+				exit ();
+			}
+			$_GET['action'] = 'm_rights';
+			break;
+        case 'set_r_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 1);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+       case 'unset_r_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 0);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+      case 'set_edit_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 1);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'unset_edit_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 0);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'set_delete_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 1);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'unset_delete_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 0);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'set_mres_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 1);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'unset_mres_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 0);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+       case 'set_all_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id){
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 1);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 1);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 1);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 1);
+                }
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'unset_all_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id){
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 0);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 0);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 0);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 0);
+                }
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+	}
+}
+switch ($_GET['action']) {
+	case 'm_rights' :
+        if(!Rsys::item_allow($_GET['item_id'],'m_rights')) die('No Access!');
+		switch ($_GET['subaction']) {
+			case 'edit' :
+				$item = Rsys :: get_item($_GET['item_id']);
+				$classDB = Rsys :: get_class_group($_GET['class_id']);
+				$item_rights = Rsys :: get_item_rights($_GET['item_id'], $_GET['class_id']);
+
+				$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
+
+				$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
+				$interbreadcrumb[] = array ("url" => "m_item.php?&action=m_rights&id=".$item['id'], "name" => str_replace('#ITEM#', $item['name'], get_lang('MItemRights')));
+
+				Display :: display_header(get_lang('EditRight'));
+				api_display_tool_title(get_lang('EditRight'));
+				$form = new FormValidator('itemright', 'post', "m_item.php?id=".$item['id']."&action=m_rights&subaction=edit");
+
+				$form->add_textfield('classn', get_lang('Class'), true, array ('readonly' => 'readonly'));
+
+				$form->addElement('checkbox', 'edit_right', get_lang('EditRight'));
+				$form->addElement('checkbox', 'delete_right', get_lang('DeleteRight'));
+				$form->addElement('checkbox', 'm_reservation', get_lang('MReservationRight'));
+
+				$form->addElement('hidden', 'item_id', $item['id']);
+				$form->addElement('hidden', 'class_id', $_GET['class_id']);
+
+				$item_right['classn'] = $classDB[0]['name'];
+				$item_right['edit_right'] = $item_rights[0]['edit_right'];
+				$item_right['delete_right'] = $item_rights[0]['delete_right'];
+				$item_right['m_reservation'] = $item_rights[0]['m_reservation'];
+				$form->setDefaults($item_right);
+
+				$form->addElement('style_submit_button', 'submit', get_lang('Ok'),'class="save"');
+				if ($form->validate()) {
+					$values = $form->exportValues();
+					Rsys :: edit_item_right($values['item_id'], $values['class_id'], $values['edit_right'], $values['delete_right'], $values['m_reservation']);
+					Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemRightEdited'), "m_item.php?id=".$_GET['id']."&action=m_rights", str_replace('#ITEM#', $item['name'], get_lang('MItemRights'))),false);
+				} else
+					$form->display();
+				break;
+			case 'delete' :
+				Rsys :: delete_item_right($_GET['item_id'], $_GET['class_id']);
+				ob_start();
+				Display :: display_normal_message(get_lang('ItemRightDeleted'),false);
+				$msg = ob_get_contents();
+				ob_end_clean();
+			case 'switch' :
+				switch ($_GET['switch']) {
+					case 'edit' :
+						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'edit_right', $_GET['set']);
+						break;
+					case 'delete' :
+						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'delete_right', $_GET['set']);
+						break;
+					case 'manage' :
+						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'm_reservation', $_GET['set']);
+						break;
+					case 'view' :
+                        Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'view_right', $_GET['set']);
+                        break;
+				}
+			default :
+				$item = Rsys :: get_item($_GET['item_id']);
+				$NoSearchResults = get_lang('NoRights');
+
+
+				$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
+				$interbreadcrumb[] = array ("url" => "m_item.php", "name" => get_lang('ManageResources'));
+				Display :: display_header(str_replace('#ITEM#', $item['name'], get_lang('MItemRights')));
+
+				api_display_tool_title(get_lang('MItemRights2'));
+
+				echo $msg;
+				$_s_item['id'] = $_GET['item_id'];
+				$_s_item['name'] = $item['name'];
+				api_session_register('_s_item');
+				//api_session_register('s_item_name');
+				//echo "<a href=\"m_item.php?action=add_classgroup\">".get_lang('MAddClassgroup')."</a>";
+				$table = new SortableTable('itemrights', array ('Rsys', 'get_num_itemrights'), array ('Rsys', 'get_table_itemrights'), 1);
+				$table->set_header(0, '', false, array ('style' => 'width:10px'));
+				$table->set_additional_parameters(array('action'=>'m_rights','item_id'=>$_GET['item_id']));
+				$table->set_header(1, get_lang('Class'), false);
+                $table->set_header(2, get_lang('EditItemRight'), false);
+				$table->set_header(3, get_lang('DeleteItemRight'), false);
+				$table->set_header(4, get_lang('MBookingPeriodsRight'), false);
+                $table->set_header(5, get_lang('ViewItemRight'), false);
+				$table->set_header(6, '', false, array ('style' => 'width:50px;'));
+				$table->set_column_filter(6, 'modify_rights_filter');
+				$table->set_form_actions(array (
+                                        'delete_itemrights'     => get_lang('DeleteSelectedItemRights'),
+                                        'set_edit_rights'       => get_lang('SetEditRights'),
+                                        'unset_edit_rights'     => get_lang('UnsetEditRights'),
+                                        'set_delete_rights'     => get_lang('SetDeleteRights'),
+                                        'unset_delete_rights'   => get_lang('UnsetDeleteRights'),
+                                        'set_mres_rights'       => get_lang('SetMresRights'),
+                                        'unset_mres_rights'     => get_lang('UnsetMresRights'),
+                                        'set_r_rights'          => get_lang('SetViewRights'),
+                                        'unset_r_rights'        => get_lang('UnsetViewRights'),
+                                        'set_all_rights'        => get_lang('SetAllRights'),
+                                        'unset_all_rights'      => get_lang('UnsetAllRights')
+                                        ), 'itemrights');
+				$table->display();
+		}
+		break;
+	case 'add' :
+
+		$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
+
+		$interbreadcrumb[] = array ("url" => "m_item.php", "name" => get_lang('ManageResources'));
+
+		//$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
+		Display :: display_header(get_lang('AddNewResource'));
+		api_display_tool_title(get_lang('AddNewResource'));
+		$form = new FormValidator('item', 'post', 'm_item.php?action=add');
+		$cats = Rsys :: get_category();
+		foreach ($cats as $cat)
+			$catOptions[$cat['id']] = $cat['name'];
+		$form->addElement('select', 'category', get_lang('ResourceType'), $catOptions);
+		$form->add_textfield('name', get_lang('ResourceName'), true, array ('maxlength' => '128'));
+		$form->addElement('textarea', 'description', get_lang('Description'), array ('rows' => '3', 'cols' => '40'));
+		$form->addRule('category', get_lang('ThisFieldIsRequired'), 'required');
+
+		// TODO: get list of courses (to link it to the item)
+		//$form->addElement('select', 'course_code', get_lang('ItemCourse'),array(''=>'','value'=>'tag'));
+		//$form->addRule('course', get_lang('ThisFieldIsRequired'), 'required');
+
+		$form->addElement('style_submit_button', 'submit', get_lang('AddNewResource'),'class="add"');
+		if ($form->validate()) {
+			$values = $form->exportValues();
+			if (Rsys :: add_item($values['name'], $values['description'], $values['category'], $values['course_code']))
+			{
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceAdded'), "m_item.php?action=m_rights&item_id=".Rsys :: get_item_id($values['name']), get_lang('MItemRight').' '.$values['name']),false);
+			}
+			else
+			{
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceExist'), "m_item.php?action=add", get_lang('AddNewResource')),false);
+			}
+		} else
+			$form->display();
+		break;
+	case 'edit' :
+		$item = Rsys :: get_item($_GET['id']);
+		$cats = Rsys :: get_category();
+		foreach ($cats as $cat)
+			$catOptions[$cat['id']] = $cat['name'];
+
+		$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
+
+		$interbreadcrumb[] = array ("url" => "m_item.php", "name" => get_lang('ManageResources'));
+
+		Display :: display_header(str_replace('#ITEM#', $item['name'], get_lang('EditResource')));
+		api_display_tool_title(get_lang('EditResource'));
+		$form = new FormValidator('item', 'post', 'm_item.php?action=edit');
+		$form->addElement('select', 'category_id', get_lang('ResourceType'), $catOptions);
+		$form->add_textfield('name', get_lang('ResourceName'), array ('maxlength' => '128'));
+		$form->addElement('textarea', 'description', get_lang('Description'), array ('rows' => '3', 'cols' => '40'));
+		$form->addRule('category_id', get_lang('ThisFieldIsRequired'), 'required');
+		$form->addElement('hidden', 'id', $item['id']);
+		$form->addElement('style_submit_button', 'submit', get_lang('EditResource'),'class="save"');
+		$form->setDefaults($item);
+		if ($form->validate()) {
+			$values = $form->exportValues();
+			if (Rsys :: edit_item($values['id'], $values['name'], $values['description'], $values['category_id'], $values['course_id']))
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceEdited'), "m_item.php", $tool_name),false);
+			else
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ResourceExist'), "m_item.php?action=edit&id=".$values['id'], get_lang('EditItem2')),false);
+		} else
+			$form->display();
+		break;
+	case 'delete' :
+		$result = Rsys :: delete_item($_GET['id']);
+		ob_start();
+		if($result == '0'){
+			Display :: display_normal_message(get_lang('ResourceDeleted'),false);}
+		else
+			Display :: display_normal_message(str_replace('#NUM#', $result, get_lang('ItemHasReservations')),false);
+		$msg = ob_get_contents();
+		ob_end_clean();
+	default :
 		$NoSearchResults = get_lang('NoItems');
 		$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-		//$interbreadcrumb[] = array ("url" => "m_item.php", "name" => get_lang('ManageResources'));
-
-		Display :: display_header(get_lang('ManageResources'));
-		api_display_tool_title(get_lang('ResourceList'));
-
-		echo $msg;
-
-		if($_GET['action'] == 'blackout'){
-			$result = Rsys :: black_out_changer($_GET['id']);
-			if ($result==1) {
-				Display :: display_normal_message(get_lang('ResourceInactivated'),false);
-			}
-			else {
-				Display :: display_normal_message(get_lang('ResourceActivated'),false);
-			}
-		}
-
-		echo '<form id="cat_form" action="m_item.php" method="get">';
-		echo '<div class="actions">';
-		echo '<a href="m_item.php?action=add"><img src="../img/view_more_stats.gif" border="0" alt="" title="'.get_lang('AddNewBookingPeriod').'"/>'.get_lang('AddNewResource').'</a>';
-		echo '</div>';
-		echo '<div style="text-align: right;">'.get_lang('ResourceFilter').': ';
-		echo '<select name="cat" onchange="this.form.submit();"><option value="0"> '.get_lang('All').' </option>';
-		$cats = Rsys :: get_category_with_items_manager();
-		foreach ($cats as $cat)
-			echo '<option value="'.$cat['id'].'"'. ($cat['id'] == $_GET['cat'] ? ' selected="selected"' : '').'>'.$cat['name'].'</option>';
-		echo '</select></div></form>';
-
-		$table = new SortableTable('item', array ('Rsys', 'get_num_items'), array ('Rsys', 'get_table_items'), 1);
-		$table->set_additional_parameters(array('cat'=>$_GET['cat']));
-		$table->set_header(0, '', false, array ('style' => 'width:10px'));
-		$table->set_header(1, get_lang('ResourceName'), true);
-		$table->set_header(2, get_lang('Description'), true);
-		$table->set_header(3, get_lang('ResourceType'), true);
-		$table->set_header(4, get_lang('Owner'), true);
-		$table->set_header(5, '', false, array ('style' => 'width:100px;'));
-		$table->set_column_filter(5, 'modify_filter');
-		$table->set_form_actions(array ('delete_items' => get_lang('DeleteSelectedResources')), 'items');
-		$table->display();
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-Display :: display_footer();
-?>
-
+		//$interbreadcrumb[] = array ("url" => "m_item.php", "name" => get_lang('ManageResources'));
+
+		Display :: display_header(get_lang('ManageResources'));
+		api_display_tool_title(get_lang('ResourceList'));
+
+		echo $msg;
+
+		if($_GET['action'] == 'blackout'){
+			$result = Rsys :: black_out_changer($_GET['id']);
+			if ($result==1) {
+				Display :: display_normal_message(get_lang('ResourceInactivated'),false);
+			}
+			else {
+				Display :: display_normal_message(get_lang('ResourceActivated'),false);
+			}
+		}
+
+		echo '<form id="cat_form" action="m_item.php" method="get">';
+		echo '<div class="actions">';
+		echo '<a href="m_item.php?action=add"><img src="../img/view_more_stats.gif" border="0" alt="" title="'.get_lang('AddNewBookingPeriod').'"/>'.get_lang('AddNewResource').'</a>';
+		echo '</div>';
+		echo '<div style="text-align: right;">'.get_lang('ResourceFilter').': ';
+		echo '<select name="cat" onchange="this.form.submit();"><option value="0"> '.get_lang('All').' </option>';
+		$cats = Rsys :: get_category_with_items_manager();
+		foreach ($cats as $cat)
+			echo '<option value="'.$cat['id'].'"'. ($cat['id'] == $_GET['cat'] ? ' selected="selected"' : '').'>'.$cat['name'].'</option>';
+		echo '</select></div></form>';
+
+		$table = new SortableTable('item', array ('Rsys', 'get_num_items'), array ('Rsys', 'get_table_items'), 1);
+		$table->set_additional_parameters(array('cat'=>$_GET['cat']));
+		$table->set_header(0, '', false, array ('style' => 'width:10px'));
+		$table->set_header(1, get_lang('ResourceName'), true);
+		$table->set_header(2, get_lang('Description'), true);
+		$table->set_header(3, get_lang('ResourceType'), true);
+		$table->set_header(4, get_lang('Owner'), true);
+		$table->set_header(5, '', false, array ('style' => 'width:100px;'));
+		$table->set_column_filter(5, 'modify_filter');
+		$table->set_form_actions(array ('delete_items' => get_lang('DeleteSelectedResources')), 'items');
+		$table->display();
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+Display :: display_footer();
+?>
+

+ 433 - 433
main/reservation/m_item_origineel.php

@@ -1,433 +1,433 @@
-<?php
-// $Id: m_item.php,v 1.13 2006/05/11 14:29:52 sjacobs Exp $
-/*
-==============================================================================
-    Dokeos - elearning and course management software
-
-    Copyright (c) 2004-2008 Dokeos SPRL
-    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
-    Copyright (c) Kristof Van Steenkiste
-    Copyright (c) Julio Montoya Armas
-
-    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
-==============================================================================
-*/
-/**
-    ---------------------------------------------------------------------
-                Item-manager (add, edit & delete)
-    ---------------------------------------------------------------------
- */
-require_once('rsys.php');
-
-Rsys :: protect_script('m_item');
-$tool_name = get_lang('ItemManagerHeader');
-//$interbreadcrumb[] = array ("url" => "../admin/index.php", "name" => get_lang('PlatformAdmin'));
-
-/**
-    ---------------------------------------------------------------------
- */
-
-/**
- *  Filter to display the modify-buttons
- *
- *  @param  -   int     $id     The item-id
- */
-function modify_filter($id) {
-    $str='';
-	$outtt=false;
-    if(Rsys::item_allow($id,'edit')){
-        $str.='<a href="m_item.php?action=edit&amp;id='.$id.'" title="'.get_lang("EditItem2").'"><img alt="" src="../img/edit.gif" /></a>';
-    }
-    if(Rsys::item_allow($id,'m_rights')) $str.=' &nbsp;<a href="m_item.php?action=m_rights&amp;item_id='.$id.'" title="'.get_lang("MRights").'"><img alt="" src="../img/info_small.gif" /></a>';
-    if(Rsys::item_allow($id,'delete')) $str.=' <a href="m_item.php?action=delete&amp;id='.$id.'" title="'.get_lang("DeleteItem").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteItem")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
-    if(Rsys::item_allow($id,'edit')){
-        $number = Rsys :: get_item($id);
-        $str.= ' <a href="m_item.php?action=blackout&amp;id='.$id.'" title="'.get_lang("Blackout").'"><img alt="" src="../img/blackout'.$number[5].'.gif" /></a>';
-    }
-    return $str;
-}
-
-/**
- *  Filter to display the modify-buttons
- *
- *  @param  -   int     $id     The item-rights-id's
- */
-function modify_rights_filter($id) {
-	return ' <a href="m_item.php?action=m_rights&amp;subaction=delete&amp;item_id='.substr($id, 0, strpos($id, '-')).'&amp;class_id='.substr($id, strrpos($id, '-') + 1).'" title="'.get_lang("RemoveClassRights").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteItem"), ENT_QUOTES, api_get_system_encoding()))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-if (isset ($_POST['action'])) {
-	switch ($_POST['action']) {
-		case 'delete_items' :
-			$ids = $_POST['items'];
-			$warning = false;
-			if (count($ids) > 0) {
-				foreach ($ids as $id) {
-					$result = Rsys :: delete_item($id);
-					if ($result != 0 && $warning <> true)
-						$warning = true;
-				}
-				ob_start();
-				if ($warning) {
-					Display :: display_normal_message(get_lang('ItemNotDeleted'), false);
-
-				} else {
-
-					Display :: display_normal_message(get_lang('ItemDeleted'),false);
-				}
-				$msg = ob_get_contents();
-				ob_end_clean();
-			}
-			break;
-		case 'delete_itemrights' :
-			$ids = $_POST['itemrights'];
-			if (count($ids) > 0) {
-				foreach ($ids as $id)
-					Rsys :: delete_item_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1));
-				ob_start();
-				Display :: display_normal_message(get_lang('ItemRightDeleted'),false);
-				$msg = ob_get_contents();
-				ob_end_clean();
-				$_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-			} else {
-				header("Location: ".$_SERVER['HTTP_REFERER']);
-				exit ();
-			}
-			$_GET['action'] = 'm_rights';
-			break;
-        case 'set_r_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 1);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-       case 'unset_r_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 0);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-      case 'set_edit_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 1);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'unset_edit_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 0);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'set_delete_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 1);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'unset_delete_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 0);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'set_mres_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 1);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'unset_mres_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id)
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 0);
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-       case 'set_all_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id){
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 1);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 1);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 1);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 1);
-                }
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-        case 'unset_all_rights' :
-            $ids = $_POST['itemrights'];
-            if (count($ids) > 0) {
-                foreach ($ids as $id){
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 0);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 0);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 0);
-                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 0);
-                }
-                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
-            } else {
-                header("Location: ".$_SERVER['HTTP_REFERER']);
-                exit ();
-            }
-            $_GET['action'] = 'm_rights';
-            break;
-	}
-}
-switch ($_GET['action']) {
-	case 'm_rights' :
-        if(!Rsys::item_allow($_GET['item_id'],'m_rights')) die('No Access!');
-		switch ($_GET['subaction']) {
-			case 'edit' :
-				$item = Rsys :: get_item($_GET['item_id']);
-				$classDB = Rsys :: get_class_group($_GET['class_id']);
-				$item_rights = Rsys :: get_item_rights($_GET['item_id'], $_GET['class_id']);
-
-				$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
-				$interbreadcrumb[] = array ("url" => "m_item.php?&action=m_rights&id=".$item['id'], "name" => str_replace('#ITEM#', $item['name'], get_lang('MItemRights')));
-				Display :: display_header(get_lang('EditRight'));
-				api_display_tool_title(get_lang('EditRight'));
-				$form = new FormValidator('itemright', 'post', "m_item.php?id=".$item['id']."&action=m_rights&subaction=edit");
-
-				$form->add_textfield('classn', get_lang('LangClass'), true, array ('readonly' => 'readonly'));
-
-				$form->addElement('checkbox', 'edit_right', get_lang('EditRight'));
-				$form->addElement('checkbox', 'delete_right', get_lang('DeleteRight'));
-				$form->addElement('checkbox', 'm_reservation', get_lang('MReservationRight'));
-
-				$form->addElement('hidden', 'item_id', $item['id']);
-				$form->addElement('hidden', 'class_id', $_GET['class_id']);
-
-				$item_right['classn'] = $classDB[0]['name'];
-				$item_right['edit_right'] = $item_rights[0]['edit_right'];
-				$item_right['delete_right'] = $item_rights[0]['delete_right'];
-				$item_right['m_reservation'] = $item_rights[0]['m_reservation'];
-				$form->setDefaults($item_right);
-
-				$form->addElement('submit', 'submit', get_lang('Ok'));
-				if ($form->validate()) {
-					$values = $form->exportValues();
-					Rsys :: edit_item_right($values['item_id'], $values['class_id'], $values['edit_right'], $values['delete_right'], $values['m_reservation']);
-					Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemRightEdited'), "m_item.php?id=".$_GET['id']."&action=m_rights", str_replace('#ITEM#', $item['name'], get_lang('MItemRights'))),false);
-				} else
-					$form->display();
-				break;
-			case 'delete' :
-				Rsys :: delete_item_right($_GET['item_id'], $_GET['class_id']);
-				ob_start();
-				Display :: display_normal_message(get_lang('itemRightDeleted'),false);
-				$msg = ob_get_contents();
-				ob_end_clean();
-			case 'switch' :
-				switch ($_GET['switch']) {
-					case 'edit' :
-						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'edit_right', $_GET['set']);
-						break;
-					case 'delete' :
-						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'delete_right', $_GET['set']);
-						break;
-					case 'manage' :
-						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'm_reservation', $_GET['set']);
-						break;
-					case 'view' :
-                        Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'view_right', $_GET['set']);
-                        break;
-				}
-			default :
-				$item = Rsys :: get_item($_GET['item_id']);
-				$NoSearchResults = get_lang('NoRights');
-				$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
-				Display :: display_header(str_replace('#ITEM#', $item['name'], get_lang('MItemRights')));
-				api_display_tool_title(get_lang('MItemRights2'));
-				echo $msg;
-				$table = new SortableTable('itemrights', array ('Rsys', 'get_num_itemrights'), array ('Rsys', 'get_table_itemrights'), 1);
-				$table->set_header(0, '', false, array ('style' => 'width:10px'));
-				$table->set_additional_parameters(array('action'=>'m_rights','item_id'=>$_GET['item_id']));
-				$table->set_header(1, get_lang('LangClass'), false);
-                $table->set_header(2, get_lang('EditItemRight'), false);
-				$table->set_header(3, get_lang('DeleteItemRight'), false);
-				$table->set_header(4, get_lang('MReservationPeriodsRight'), false);
-                $table->set_header(5, get_lang('ViewItemRight'), false);
-				$table->set_header(6, '', false, array ('style' => 'width:50px;'));
-				$table->set_column_filter(6, 'modify_rights_filter');
-				$table->set_form_actions(array (
-                                        'delete_itemrights'     => get_lang('DeleteSelectedItemRights'),
-                                        'set_edit_rights'       => get_lang('SetEditRights'),
-                                        'unset_edit_rights'     => get_lang('UnsetEditRights'),
-                                        'set_delete_rights'     => get_lang('SetDeleteRights'),
-                                        'unset_delete_rights'   => get_lang('UnsetDeleteRights'),
-                                        'set_mres_rights'       => get_lang('SetMresRights'),
-                                        'unset_mres_rights'     => get_lang('UnsetMresRights'),
-                                        'set_r_rights'          => get_lang('SetViewRights'),
-                                        'unset_r_rights'        => get_lang('UnsetViewRights'),
-                                        'set_all_rights'        => get_lang('SetAllRights'),
-                                        'unset_all_rights'      => get_lang('UnsetAllRights')
-                                        ), 'itemrights');
-				$table->display();
-		}
-		break;
-	case 'add' :
-		$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
-		Display :: display_header(get_lang('AddNewItem'));
-		api_display_tool_title(get_lang('AddNewItem'));
-		$form = new FormValidator('item', 'post', 'm_item.php?action=add');
-		$cats = Rsys :: get_category();
-		foreach ($cats as $cat)
-			$catOptions[$cat['id']] = $cat['name'];
-		$form->addElement('select', 'category', get_lang('Category'), $catOptions);
-		$form->add_textfield('name', get_lang('ItemName'), true, array ('maxlength' => '128'));
-		$form->addElement('textarea', 'description', get_lang('ItemDescription'), array ('rows' => '3', 'cols' => '40'));
-		$form->addRule('category', get_lang('ThisFieldIsRequired'), 'required');
-
-		// TODO: get list of courses (to link it to the item)
-		//$form->addElement('select', 'course_code', get_lang('ItemCourse'),array(''=>'','value'=>'tag'));
-		//$form->addRule('course', get_lang('ThisFieldIsRequired'), 'required');
-
-		$form->addElement('submit', 'submit', get_lang('Ok'));
-		if ($form->validate()) {
-			$values = $form->exportValues();
-			if (Rsys :: add_item($values['name'], $values['description'], $values['category'], $values['course_code']))
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemAdded'), "m_item.php", $tool_name),false);
-			else
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemExist'), "m_item.php?action=add", get_lang('AddNewItem')),false);
-		} else
-			$form->display();
-		break;
-	case 'edit' :
-		$item = Rsys :: get_item($_GET['id']);
-		$cats = Rsys :: get_category();
-		foreach ($cats as $cat)
-			$catOptions[$cat['id']] = $cat['name'];
-		$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
-		Display :: display_header(str_replace('#ITEM#', $item['name'], get_lang('EditItem')));
-		api_display_tool_title(get_lang('EditItem2'));
-		$form = new FormValidator('item', 'post', 'm_item.php?action=edit');
-		$form->addElement('select', 'category_id', get_lang('Category'), $catOptions);
-		$form->add_textfield('name', get_lang('ItemName'), array ('maxlength' => '128'));
-		$form->addElement('textarea', 'description', get_lang('ItemDescription'), array ('rows' => '3', 'cols' => '40'));
-		$form->addRule('category_id', get_lang('ThisFieldIsRequired'), 'required');
-		$form->addElement('hidden', 'id', $item['id']);
-		$form->addElement('submit', 'submit', get_lang('Ok'));
-		$form->setDefaults($item);
-		if ($form->validate()) {
-			$values = $form->exportValues();
-			if (Rsys :: edit_item($values['id'], $values['name'], $values['description'], $values['category_id'], $values['course_id']))
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemEdited'), "m_item.php", $tool_name),false);
-			else
-				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemExist'), "m_item.php?action=edit&id=".$values['id'], get_lang('EditItem2')),false);
-		} else
-			$form->display();
-		break;
-	case 'delete' :
-		$result = Rsys :: delete_item($_GET['id']);
-		ob_start();
-		if($result == '0'){
-			Display :: display_normal_message(get_lang('ItemDeleted'),false);}
-		else
-			Display :: display_normal_message(str_replace('#NUM#', $result, get_lang('ItemHasReservations')),false);
-		$msg = ob_get_contents();
-		ob_end_clean();
-	default :
-		$NoSearchResults = get_lang('noItems');
-		Display :: display_header($tool_name);
-		api_display_tool_title($tool_name);
-
-		echo $msg;
-
-		if($_GET['action'] == 'blackout'){
-			$result = Rsys :: black_out_changer($_GET['id']);
-			Display :: display_normal_message(get_lang('BlackoutPage'.$result),false);
-		}
-
-		echo '<form id="cat_form" action="m_item.php" method="get"><div style="float: left;"><a href="m_item.php?action=add">'.get_lang('AddNewItem').'</a></div><div style="text-align: right;">'.get_lang('CategoryFilter').': <select name="cat" onchange="this.form.submit();"><option value="0">*** '.get_lang('All').' ***</option>';
-		$cats = Rsys :: get_category_with_items_manager();
-		foreach ($cats as $cat)
-			echo '<option value="'.$cat['id'].'"'. ($cat['id'] == $_GET['cat'] ? ' selected="selected"' : '').'>'.$cat['name'].'</option>';
-		echo '</select></div></form>';
-		echo "hier";
-		$table = new SortableTable('item', array ('Rsys', 'get_num_items'), array ('Rsys', 'get_table_items'), 1);
-		echo "hier2";
-		$table->set_additional_parameters(array('cat'=>$_GET['cat']));
-		$table->set_header(0, '', false, array ('style' => 'width:10px'));
-		$table->set_header(1, get_lang('ItemName'), true);
-		$table->set_header(2, get_lang('ItemDescription'), true);
-		$table->set_header(3, get_lang('Category'), true);
-		$table->set_header(4, get_lang('ItemCreator'), true);
-		$table->set_header(5, '', false, array ('style' => 'width:100px;'));
-		$table->set_column_filter(5, 'modify_filter');
-		$table->set_form_actions(array ('delete_items' => get_lang('DeleteSelectedItems')), 'items');
-		$table->display();
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-Display :: display_footer();
-?>
+<?php
+// $Id: m_item.php,v 1.13 2006/05/11 14:29:52 sjacobs Exp $
+/*
+==============================================================================
+    Dokeos - elearning and course management software
+
+    Copyright (c) 2004-2008 Dokeos SPRL
+    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
+    Copyright (c) Kristof Van Steenkiste
+    Copyright (c) Julio Montoya Armas
+
+    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
+==============================================================================
+*/
+/**
+    ---------------------------------------------------------------------
+                Item-manager (add, edit & delete)
+    ---------------------------------------------------------------------
+ */
+require_once('rsys.php');
+
+Rsys :: protect_script('m_item');
+$tool_name = get_lang('ItemManagerHeader');
+//$interbreadcrumb[] = array ("url" => "../admin/index.php", "name" => get_lang('PlatformAdmin'));
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+/**
+ *  Filter to display the modify-buttons
+ *
+ *  @param  -   int     $id     The item-id
+ */
+function modify_filter($id) {
+    $str='';
+	$outtt=false;
+    if(Rsys::item_allow($id,'edit')){
+        $str.='<a href="m_item.php?action=edit&amp;id='.$id.'" title="'.get_lang("EditItem2").'"><img alt="" src="../img/edit.gif" /></a>';
+    }
+    if(Rsys::item_allow($id,'m_rights')) $str.=' &nbsp;<a href="m_item.php?action=m_rights&amp;item_id='.$id.'" title="'.get_lang("MRights").'"><img alt="" src="../img/info_small.gif" /></a>';
+    if(Rsys::item_allow($id,'delete')) $str.=' <a href="m_item.php?action=delete&amp;id='.$id.'" title="'.get_lang("DeleteItem").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteItem")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
+    if(Rsys::item_allow($id,'edit')){
+        $number = Rsys :: get_item($id);
+        $str.= ' <a href="m_item.php?action=blackout&amp;id='.$id.'" title="'.get_lang("Blackout").'"><img alt="" src="../img/blackout'.$number[5].'.gif" /></a>';
+    }
+    return $str;
+}
+
+/**
+ *  Filter to display the modify-buttons
+ *
+ *  @param  -   int     $id     The item-rights-id's
+ */
+function modify_rights_filter($id) {
+	return ' <a href="m_item.php?action=m_rights&amp;subaction=delete&amp;item_id='.substr($id, 0, strpos($id, '-')).'&amp;class_id='.substr($id, strrpos($id, '-') + 1).'" title="'.get_lang("RemoveClassRights").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteItem"), ENT_QUOTES, api_get_system_encoding()))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+if (isset ($_POST['action'])) {
+	switch ($_POST['action']) {
+		case 'delete_items' :
+			$ids = $_POST['items'];
+			$warning = false;
+			if (count($ids) > 0) {
+				foreach ($ids as $id) {
+					$result = Rsys :: delete_item($id);
+					if ($result != 0 && $warning <> true)
+						$warning = true;
+				}
+				ob_start();
+				if ($warning) {
+					Display :: display_normal_message(get_lang('ItemNotDeleted'), false);
+
+				} else {
+
+					Display :: display_normal_message(get_lang('ItemDeleted'),false);
+				}
+				$msg = ob_get_contents();
+				ob_end_clean();
+			}
+			break;
+		case 'delete_itemrights' :
+			$ids = $_POST['itemrights'];
+			if (count($ids) > 0) {
+				foreach ($ids as $id)
+					Rsys :: delete_item_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1));
+				ob_start();
+				Display :: display_normal_message(get_lang('ItemRightDeleted'),false);
+				$msg = ob_get_contents();
+				ob_end_clean();
+				$_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+			} else {
+				header("Location: ".$_SERVER['HTTP_REFERER']);
+				exit ();
+			}
+			$_GET['action'] = 'm_rights';
+			break;
+        case 'set_r_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 1);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+       case 'unset_r_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 0);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+      case 'set_edit_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 1);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'unset_edit_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 0);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'set_delete_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 1);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'unset_delete_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 0);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'set_mres_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 1);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'unset_mres_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id)
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 0);
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+       case 'set_all_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id){
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 1);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 1);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 1);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 1);
+                }
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+        case 'unset_all_rights' :
+            $ids = $_POST['itemrights'];
+            if (count($ids) > 0) {
+                foreach ($ids as $id){
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'm_reservation', 0);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'edit_right', 0);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'delete_right', 0);
+                    Rsys :: set_new_right(substr($id, 0, strpos($id, '-')), substr($id, strrpos($id, '-') + 1), 'view_right', 0);
+                }
+                $_GET['item_id'] = substr($id, 0, strpos($id, '-'));
+            } else {
+                header("Location: ".$_SERVER['HTTP_REFERER']);
+                exit ();
+            }
+            $_GET['action'] = 'm_rights';
+            break;
+	}
+}
+switch ($_GET['action']) {
+	case 'm_rights' :
+        if(!Rsys::item_allow($_GET['item_id'],'m_rights')) die('No Access!');
+		switch ($_GET['subaction']) {
+			case 'edit' :
+				$item = Rsys :: get_item($_GET['item_id']);
+				$classDB = Rsys :: get_class_group($_GET['class_id']);
+				$item_rights = Rsys :: get_item_rights($_GET['item_id'], $_GET['class_id']);
+
+				$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
+				$interbreadcrumb[] = array ("url" => "m_item.php?&action=m_rights&id=".$item['id'], "name" => str_replace('#ITEM#', $item['name'], get_lang('MItemRights')));
+				Display :: display_header(get_lang('EditRight'));
+				api_display_tool_title(get_lang('EditRight'));
+				$form = new FormValidator('itemright', 'post', "m_item.php?id=".$item['id']."&action=m_rights&subaction=edit");
+
+				$form->add_textfield('classn', get_lang('LangClass'), true, array ('readonly' => 'readonly'));
+
+				$form->addElement('checkbox', 'edit_right', get_lang('EditRight'));
+				$form->addElement('checkbox', 'delete_right', get_lang('DeleteRight'));
+				$form->addElement('checkbox', 'm_reservation', get_lang('MReservationRight'));
+
+				$form->addElement('hidden', 'item_id', $item['id']);
+				$form->addElement('hidden', 'class_id', $_GET['class_id']);
+
+				$item_right['classn'] = $classDB[0]['name'];
+				$item_right['edit_right'] = $item_rights[0]['edit_right'];
+				$item_right['delete_right'] = $item_rights[0]['delete_right'];
+				$item_right['m_reservation'] = $item_rights[0]['m_reservation'];
+				$form->setDefaults($item_right);
+
+				$form->addElement('submit', 'submit', get_lang('Ok'));
+				if ($form->validate()) {
+					$values = $form->exportValues();
+					Rsys :: edit_item_right($values['item_id'], $values['class_id'], $values['edit_right'], $values['delete_right'], $values['m_reservation']);
+					Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemRightEdited'), "m_item.php?id=".$_GET['id']."&action=m_rights", str_replace('#ITEM#', $item['name'], get_lang('MItemRights'))),false);
+				} else
+					$form->display();
+				break;
+			case 'delete' :
+				Rsys :: delete_item_right($_GET['item_id'], $_GET['class_id']);
+				ob_start();
+				Display :: display_normal_message(get_lang('itemRightDeleted'),false);
+				$msg = ob_get_contents();
+				ob_end_clean();
+			case 'switch' :
+				switch ($_GET['switch']) {
+					case 'edit' :
+						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'edit_right', $_GET['set']);
+						break;
+					case 'delete' :
+						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'delete_right', $_GET['set']);
+						break;
+					case 'manage' :
+						Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'm_reservation', $_GET['set']);
+						break;
+					case 'view' :
+                        Rsys :: set_new_right($_GET['item_id'], $_GET['class_id'], 'view_right', $_GET['set']);
+                        break;
+				}
+			default :
+				$item = Rsys :: get_item($_GET['item_id']);
+				$NoSearchResults = get_lang('NoRights');
+				$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
+				Display :: display_header(str_replace('#ITEM#', $item['name'], get_lang('MItemRights')));
+				api_display_tool_title(get_lang('MItemRights2'));
+				echo $msg;
+				$table = new SortableTable('itemrights', array ('Rsys', 'get_num_itemrights'), array ('Rsys', 'get_table_itemrights'), 1);
+				$table->set_header(0, '', false, array ('style' => 'width:10px'));
+				$table->set_additional_parameters(array('action'=>'m_rights','item_id'=>$_GET['item_id']));
+				$table->set_header(1, get_lang('LangClass'), false);
+                $table->set_header(2, get_lang('EditItemRight'), false);
+				$table->set_header(3, get_lang('DeleteItemRight'), false);
+				$table->set_header(4, get_lang('MReservationPeriodsRight'), false);
+                $table->set_header(5, get_lang('ViewItemRight'), false);
+				$table->set_header(6, '', false, array ('style' => 'width:50px;'));
+				$table->set_column_filter(6, 'modify_rights_filter');
+				$table->set_form_actions(array (
+                                        'delete_itemrights'     => get_lang('DeleteSelectedItemRights'),
+                                        'set_edit_rights'       => get_lang('SetEditRights'),
+                                        'unset_edit_rights'     => get_lang('UnsetEditRights'),
+                                        'set_delete_rights'     => get_lang('SetDeleteRights'),
+                                        'unset_delete_rights'   => get_lang('UnsetDeleteRights'),
+                                        'set_mres_rights'       => get_lang('SetMresRights'),
+                                        'unset_mres_rights'     => get_lang('UnsetMresRights'),
+                                        'set_r_rights'          => get_lang('SetViewRights'),
+                                        'unset_r_rights'        => get_lang('UnsetViewRights'),
+                                        'set_all_rights'        => get_lang('SetAllRights'),
+                                        'unset_all_rights'      => get_lang('UnsetAllRights')
+                                        ), 'itemrights');
+				$table->display();
+		}
+		break;
+	case 'add' :
+		$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
+		Display :: display_header(get_lang('AddNewItem'));
+		api_display_tool_title(get_lang('AddNewItem'));
+		$form = new FormValidator('item', 'post', 'm_item.php?action=add');
+		$cats = Rsys :: get_category();
+		foreach ($cats as $cat)
+			$catOptions[$cat['id']] = $cat['name'];
+		$form->addElement('select', 'category', get_lang('Category'), $catOptions);
+		$form->add_textfield('name', get_lang('ItemName'), true, array ('maxlength' => '128'));
+		$form->addElement('textarea', 'description', get_lang('ItemDescription'), array ('rows' => '3', 'cols' => '40'));
+		$form->addRule('category', get_lang('ThisFieldIsRequired'), 'required');
+
+		// TODO: get list of courses (to link it to the item)
+		//$form->addElement('select', 'course_code', get_lang('ItemCourse'),array(''=>'','value'=>'tag'));
+		//$form->addRule('course', get_lang('ThisFieldIsRequired'), 'required');
+
+		$form->addElement('submit', 'submit', get_lang('Ok'));
+		if ($form->validate()) {
+			$values = $form->exportValues();
+			if (Rsys :: add_item($values['name'], $values['description'], $values['category'], $values['course_code']))
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemAdded'), "m_item.php", $tool_name),false);
+			else
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemExist'), "m_item.php?action=add", get_lang('AddNewItem')),false);
+		} else
+			$form->display();
+		break;
+	case 'edit' :
+		$item = Rsys :: get_item($_GET['id']);
+		$cats = Rsys :: get_category();
+		foreach ($cats as $cat)
+			$catOptions[$cat['id']] = $cat['name'];
+		$interbreadcrumb[] = array ("url" => "m_item.php", "name" => $tool_name);
+		Display :: display_header(str_replace('#ITEM#', $item['name'], get_lang('EditItem')));
+		api_display_tool_title(get_lang('EditItem2'));
+		$form = new FormValidator('item', 'post', 'm_item.php?action=edit');
+		$form->addElement('select', 'category_id', get_lang('Category'), $catOptions);
+		$form->add_textfield('name', get_lang('ItemName'), array ('maxlength' => '128'));
+		$form->addElement('textarea', 'description', get_lang('ItemDescription'), array ('rows' => '3', 'cols' => '40'));
+		$form->addRule('category_id', get_lang('ThisFieldIsRequired'), 'required');
+		$form->addElement('hidden', 'id', $item['id']);
+		$form->addElement('submit', 'submit', get_lang('Ok'));
+		$form->setDefaults($item);
+		if ($form->validate()) {
+			$values = $form->exportValues();
+			if (Rsys :: edit_item($values['id'], $values['name'], $values['description'], $values['category_id'], $values['course_id']))
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemEdited'), "m_item.php", $tool_name),false);
+			else
+				Display :: display_normal_message(Rsys :: get_return_msg(get_lang('ItemExist'), "m_item.php?action=edit&id=".$values['id'], get_lang('EditItem2')),false);
+		} else
+			$form->display();
+		break;
+	case 'delete' :
+		$result = Rsys :: delete_item($_GET['id']);
+		ob_start();
+		if($result == '0'){
+			Display :: display_normal_message(get_lang('ItemDeleted'),false);}
+		else
+			Display :: display_normal_message(str_replace('#NUM#', $result, get_lang('ItemHasReservations')),false);
+		$msg = ob_get_contents();
+		ob_end_clean();
+	default :
+		$NoSearchResults = get_lang('noItems');
+		Display :: display_header($tool_name);
+		api_display_tool_title($tool_name);
+
+		echo $msg;
+
+		if($_GET['action'] == 'blackout'){
+			$result = Rsys :: black_out_changer($_GET['id']);
+			Display :: display_normal_message(get_lang('BlackoutPage'.$result),false);
+		}
+
+		echo '<form id="cat_form" action="m_item.php" method="get"><div style="float: left;"><a href="m_item.php?action=add">'.get_lang('AddNewItem').'</a></div><div style="text-align: right;">'.get_lang('CategoryFilter').': <select name="cat" onchange="this.form.submit();"><option value="0">*** '.get_lang('All').' ***</option>';
+		$cats = Rsys :: get_category_with_items_manager();
+		foreach ($cats as $cat)
+			echo '<option value="'.$cat['id'].'"'. ($cat['id'] == $_GET['cat'] ? ' selected="selected"' : '').'>'.$cat['name'].'</option>';
+		echo '</select></div></form>';
+		echo "hier";
+		$table = new SortableTable('item', array ('Rsys', 'get_num_items'), array ('Rsys', 'get_table_items'), 1);
+		echo "hier2";
+		$table->set_additional_parameters(array('cat'=>$_GET['cat']));
+		$table->set_header(0, '', false, array ('style' => 'width:10px'));
+		$table->set_header(1, get_lang('ItemName'), true);
+		$table->set_header(2, get_lang('ItemDescription'), true);
+		$table->set_header(3, get_lang('Category'), true);
+		$table->set_header(4, get_lang('ItemCreator'), true);
+		$table->set_header(5, '', false, array ('style' => 'width:100px;'));
+		$table->set_column_filter(5, 'modify_filter');
+		$table->set_form_actions(array ('delete_items' => get_lang('DeleteSelectedItems')), 'items');
+		$table->display();
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+Display :: display_footer();
+?>

+ 538 - 538
main/reservation/m_reservation.php

@@ -1,607 +1,607 @@
-<?php
-// $Id: m_reservation.php,v 1.26 2006/05/12 08:38:34 kvansteenkiste Exp $
-/*
-==============================================================================
-    Dokeos - elearning and course management software
-
-    Copyright (c) 2004-2008 Dokeos SPRL
-    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
-    Copyright (c) Kristof Van Steenkiste
-    Copyright (c) Julio Montoya Armas
-
-    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
-==============================================================================
-*/
-/**
-    ---------------------------------------------------------------------
-                Reservation-manager (add, edit & delete)
-    ---------------------------------------------------------------------
- */
-require_once('rsys.php');
-
-Rsys :: protect_script('m_reservation', $_GET['item_id']);
-$tool_name = get_lang('BookingPeriodList');
-
-/**
-    ---------------------------------------------------------------------
- */
-
-/**
- *  Filter to display the modify-buttons
+<?php
+// $Id: m_reservation.php,v 1.26 2006/05/12 08:38:34 kvansteenkiste Exp $
+/*
+==============================================================================
+    Dokeos - elearning and course management software
+
+    Copyright (c) 2004-2008 Dokeos SPRL
+    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
+    Copyright (c) Kristof Van Steenkiste
+    Copyright (c) Julio Montoya Armas
+
+    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
+==============================================================================
+*/
+/**
+    ---------------------------------------------------------------------
+                Reservation-manager (add, edit & delete)
+    ---------------------------------------------------------------------
+ */
+require_once('rsys.php');
+
+Rsys :: protect_script('m_reservation', $_GET['item_id']);
+$tool_name = get_lang('BookingPeriodList');
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+/**
+ *  Filter to display the modify-buttons
  *
- *  @param  -   int     $id     The reservation-id
- */
-function modify_filter($id) {
-		$out = ' <a href="m_reservation.php?action=accept&amp;rid='.$id.'" alt="'.get_lang('AutoAccept').'"><img title="'.get_lang('AutoAccept').'"  alt="'.get_lang('AutoAccept').'" src="../img/students.gif" /></a>';
+ *  @param  -   int     $id     The reservation-id
+ */
+function modify_filter($id) {
+		$out = ' <a href="m_reservation.php?action=accept&amp;rid='.$id.'" alt="'.get_lang('AutoAccept').'"><img title="'.get_lang('AutoAccept').'"  alt="'.get_lang('AutoAccept').'" src="../img/students.gif" /></a>';
 		$out .= '<a href="m_reservation.php?action=edit&amp;id='.$id.'" alt="'.get_lang('EditBookingPeriod').'"><img title="'.get_lang('EditBookingPeriod').'" alt="'.get_lang('EditBookingPeriod').'" src="../img/edit.gif" /></a>';
-		$out .= ' <a href="m_reservation.php?action=delete&amp;id='.$id.'" alt="'.get_lang('DeleteBookingPeriod').'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteBookingPeriod")))."'".')) return false;"><img title="'.get_lang('DeleteBookingPeriod').'" alt="'.get_lang('DeleteBookingPeriod').'" src="../img/delete.gif" /></a>';
-
-	return $out;
-}
-
-if (isset ($_POST['action'])) {
-	switch ($_POST['action']) {
-		case 'accept_users' :
-			$ids = $_POST['accepting'];
-			//echo count($ids);
-			if (count($ids) > 0) {
-				foreach ($ids as $id) {
-					//echo $id;
-					$result = Rsys :: set_accepted($id, 1);
-				}
-			}
-			$_GET['action'] = 'accept';
-			break;
-		case 'unaccept_users' :
-			$ids = $_POST['accepting'];
-			//echo count($ids);
-			if (count($ids) > 0) {
-				foreach ($ids as $id) {
-					//echo $id;
-					$result = Rsys :: set_accepted($id, 0);
-				}
-			}
-			$_GET['action'] = 'accept';
-			break;
-		case 'delete_subscriptions' :
-			$res_id = $_GET['rid'];
-			$ids = $_POST['accepting'];
-			//echo count($ids);
-			if (count($ids) > 0) {
-				foreach ($ids as $id) {
-					$result = Rsys :: delete_subscription($res_id,$id);
-				}
-			}
-			$_GET['action'] = 'accept';
-			break;
-	}
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-switch ($_GET['action']) {
+		$out .= ' <a href="m_reservation.php?action=delete&amp;id='.$id.'" alt="'.get_lang('DeleteBookingPeriod').'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteBookingPeriod")))."'".')) return false;"><img title="'.get_lang('DeleteBookingPeriod').'" alt="'.get_lang('DeleteBookingPeriod').'" src="../img/delete.gif" /></a>';
+
+	return $out;
+}
+
+if (isset ($_POST['action'])) {
+	switch ($_POST['action']) {
+		case 'accept_users' :
+			$ids = $_POST['accepting'];
+			//echo count($ids);
+			if (count($ids) > 0) {
+				foreach ($ids as $id) {
+					//echo $id;
+					$result = Rsys :: set_accepted($id, 1);
+				}
+			}
+			$_GET['action'] = 'accept';
+			break;
+		case 'unaccept_users' :
+			$ids = $_POST['accepting'];
+			//echo count($ids);
+			if (count($ids) > 0) {
+				foreach ($ids as $id) {
+					//echo $id;
+					$result = Rsys :: set_accepted($id, 0);
+				}
+			}
+			$_GET['action'] = 'accept';
+			break;
+		case 'delete_subscriptions' :
+			$res_id = $_GET['rid'];
+			$ids = $_POST['accepting'];
+			//echo count($ids);
+			if (count($ids) > 0) {
+				foreach ($ids as $id) {
+					$result = Rsys :: delete_subscription($res_id,$id);
+				}
+			}
+			$_GET['action'] = 'accept';
+			break;
+	}
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+switch ($_GET['action']) {
 	case 'overviewsubscriptions' :
 		$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
 		$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
 
-		Display :: display_header(get_lang('OverviewSubscriptions'));
-		api_display_tool_title(get_lang('Overview'));
+		Display :: display_header(get_lang('OverviewSubscriptions'));
+		api_display_tool_title(get_lang('Overview'));
 
 		echo '<div class="actions">';
 		echo '<form id="cat_form" action="m_reservation.php" method="get">';
-		echo '<input type="hidden" name="action" value="overviewsubscriptions"/>';
-		echo '<input type="text" name="keyword" /><button type="submit" class="search" value="'.get_lang('Search').'" >'.get_lang('Search').'</button></form>';
+		echo '<input type="hidden" name="action" value="overviewsubscriptions"/>';
+		echo '<input type="text" name="keyword" /><button type="submit" class="search" value="'.get_lang('Search').'" >'.get_lang('Search').'</button></form>';
 		echo '</div><br>';
 
 		$table = new SortableTable('reservation', array ('Rsys', 'get_num_subscriptions_overview'), array ('Rsys', 'get_table_subcribed_reservations'), 1);
-		$table->set_additional_parameters(array ('action' => 'overviewsubscriptions','keyword' => $_GET['keyword']));
-		$table->set_header(0, get_lang('ResourceName'), true);
-		$table->set_header(1, get_lang('ResourceTypeName'), true);
-		$table->set_header(2, get_lang('StartDate'), true);
-		$table->set_header(3, get_lang('EndDate'), true);
-		$table->set_header(4, get_lang('SubscribedPerson'), true);
-		$table->set_header(5, get_lang('SubscribedStartDate'), true);
-		$table->set_header(6, get_lang('SubscribedEndDate'), true);
-		$table->set_header(7, get_lang('Accept'), true);
-		$table->display();
-		break;
-	case 'accept' :
-		$NoSearchResults = get_lang('NoReservation');
-
-		if (empty ($_GET['rid'])) {
-			$_GET['rid'] = $_POST['rid'];
-		}
-		if ($_GET['switch'] == 'edit') {
-			Rsys :: set_accepted($_GET['dummy'], $_GET['set']);
-		}
-		if ($_GET['switch'] == 'delete') {
-			Rsys :: delete_subscription($_GET['rid'],$_GET['dummy']);
-		}
-
+		$table->set_additional_parameters(array ('action' => 'overviewsubscriptions','keyword' => $_GET['keyword']));
+		$table->set_header(0, get_lang('ResourceName'), true);
+		$table->set_header(1, get_lang('ResourceTypeName'), true);
+		$table->set_header(2, get_lang('StartDate'), true);
+		$table->set_header(3, get_lang('EndDate'), true);
+		$table->set_header(4, get_lang('SubscribedPerson'), true);
+		$table->set_header(5, get_lang('SubscribedStartDate'), true);
+		$table->set_header(6, get_lang('SubscribedEndDate'), true);
+		$table->set_header(7, get_lang('Accept'), true);
+		$table->display();
+		break;
+	case 'accept' :
+		$NoSearchResults = get_lang('NoReservation');
+
+		if (empty ($_GET['rid'])) {
+			$_GET['rid'] = $_POST['rid'];
+		}
+		if ($_GET['switch'] == 'edit') {
+			Rsys :: set_accepted($_GET['dummy'], $_GET['set']);
+		}
+		if ($_GET['switch'] == 'delete') {
+			Rsys :: delete_subscription($_GET['rid'],$_GET['dummy']);
+		}
+
 		$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-		$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
-
-
-		Display :: display_header(get_lang('AutoAccept'));
-		api_display_tool_title(get_lang('AutoAccept'));
-
-		$table = new SortableTable('accepting', array ('Rsys', 'get_num_waiting_users'), array ('Rsys', 'get_table_waiting_users'), 1);
-		$table->set_additional_parameters(array ('rid' => $_GET['rid'], 'action' => 'accept'));
-		$table->set_header(0, '', false, array ('style' => 'width:10px'));
-		$table->set_header(1, get_lang('SubscribedPerson'), true);
-		$table->set_header(2, get_lang('Class'), true);
-		$table->set_header(3, get_lang('SubscribedStartDate'), false);
+		$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
+
+
+		Display :: display_header(get_lang('AutoAccept'));
+		api_display_tool_title(get_lang('AutoAccept'));
+
+		$table = new SortableTable('accepting', array ('Rsys', 'get_num_waiting_users'), array ('Rsys', 'get_table_waiting_users'), 1);
+		$table->set_additional_parameters(array ('rid' => $_GET['rid'], 'action' => 'accept'));
+		$table->set_header(0, '', false, array ('style' => 'width:10px'));
+		$table->set_header(1, get_lang('SubscribedPerson'), true);
+		$table->set_header(2, get_lang('Class'), true);
+		$table->set_header(3, get_lang('SubscribedStartDate'), false);
 		$table->set_header(4, get_lang('SubscribedEndDate'), false);
-		$table->set_header(5, get_lang('Accept'), false, array ('style' => 'width:30px;'));
-		$table->set_header(6, get_lang('Delete'), false, array ('style' => 'width:30px;'));
-		$table->set_form_actions(array ('accept_users' => get_lang('AcceptUsers'), 'unaccept_users' => get_lang('UnacceptedUsers'), 'delete_subscriptions' => get_lang('Delete_subscriptions')), 'accepting');
-		//$table->set_form_actions(array ('accept_users' => get_lang('AcceptUsers'), 'unaccept_users' => get_lang('UnacceptedUsers')), 'accepting');
-		$table->display();
-		break;
-	case 'add' :
-		if (!isset ($_GET['cat_id']))
-			$_GET['cat_id'] = 0;
-
+		$table->set_header(5, get_lang('Accept'), false, array ('style' => 'width:30px;'));
+		$table->set_header(6, get_lang('Delete'), false, array ('style' => 'width:30px;'));
+		$table->set_form_actions(array ('accept_users' => get_lang('AcceptUsers'), 'unaccept_users' => get_lang('UnacceptedUsers'), 'delete_subscriptions' => get_lang('Delete_subscriptions')), 'accepting');
+		//$table->set_form_actions(array ('accept_users' => get_lang('AcceptUsers'), 'unaccept_users' => get_lang('UnacceptedUsers')), 'accepting');
+		$table->display();
+		break;
+	case 'add' :
+		if (!isset ($_GET['cat_id']))
+			$_GET['cat_id'] = 0;
+
 		$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-		$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
+		$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
+
+
+		Display :: display_header(get_lang('AddNewBookingPeriod'));
+		api_display_tool_title(get_lang('AddNewBookingPeriod'));
 
+		ob_start();
 
-		Display :: display_header(get_lang('AddNewBookingPeriod'));
-		api_display_tool_title(get_lang('AddNewBookingPeriod'));
-
-		ob_start();
-
-		$cats = Rsys :: get_category_rights();
+		$cats = Rsys :: get_category_rights();
 		echo '<form id="cat_form" action="m_reservation.php" method="get">';
 		echo '<input type="hidden" name="action" value="add"/>';
 		echo '<div class="row">';
-			echo '<div class="label">'.get_lang('ResourceType').': </div>';
-			echo '<div class="formw">';
+			echo '<div class="label">'.get_lang('ResourceType').': </div>';
+			echo '<div class="formw">';
 
 			echo '<select name="cat_id" onchange="this.form.submit();">';
-			echo '<option value="0">&nbsp;</option>';
-			foreach ($cats as $catid => $cat)
-				echo '<option value="'.$catid.'"'. ($catid == $_GET['cat_id'] ? ' selected="selected"' : '').'>'.$cat.'</option>';
+			echo '<option value="0">&nbsp;</option>';
+			foreach ($cats as $catid => $cat)
+				echo '<option value="'.$catid.'"'. ($catid == $_GET['cat_id'] ? ' selected="selected"' : '').'>'.$cat.'</option>';
 			echo '</select></div>';
-		echo '</div></form>';
+		echo '</div></form>';
 
-		$itemlist = Rsys :: get_cat_r_items($_GET['cat_id']);
-		$form = new FormValidator('reservation', 'post', 'm_reservation.php?action=add&cat_id='.$_GET['cat_id']);
-		$choices[] = $form->createElement('radio', 'forever', '', get_lang('NoPeriod'), 0, array ('onclick' => 'javascript:window_hide(\'forever_timewindow\')'));
-		$choices[] = $form->createElement('radio', 'forever', '', get_lang('FixedPeriod'), 1 , array ('onclick' => 'javascript:window_show(\'forever_timewindow\')'));
-		$form->addElement('select', 'itemid', get_lang('Resource'), $itemlist);
+		$itemlist = Rsys :: get_cat_r_items($_GET['cat_id']);
+		$form = new FormValidator('reservation', 'post', 'm_reservation.php?action=add&cat_id='.$_GET['cat_id']);
+		$choices[] = $form->createElement('radio', 'forever', '', get_lang('NoPeriod'), 0, array ('onclick' => 'javascript:window_hide(\'forever_timewindow\')'));
+		$choices[] = $form->createElement('radio', 'forever', '', get_lang('FixedPeriod'), 1 , array ('onclick' => 'javascript:window_show(\'forever_timewindow\')'));
+		$form->addElement('select', 'itemid', get_lang('Resource'), $itemlist);
 
 		$form->add_timewindow('start', 'end', get_lang('StartDate'), get_lang('EndDate'));
-		$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('TimePickerLimitation').'</div></div><br />');
+		$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('TimePickerLimitation').'</div></div><br />');
 
 		$form->addElement('text', 'maxuser', get_lang('MaxUsers'));
-		$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('TimePickerMaxUsers').'</div></div><br />');
+		$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('TimePickerMaxUsers').'</div></div><br />');
 
-		$form->addGroup($choices, null, get_lang('SubscriptionPeriod'), '<br />', false);
-		$form->addElement('html', '<div style="margin-left:25px;display:block;" id="forever_timewindow">');
-		$form->add_timewindow('subscribe_from', 'subscribe_until', '', '');
-		$form->addElement('html', '</div>');
+		$form->addGroup($choices, null, get_lang('SubscriptionPeriod'), '<br />', false);
+		$form->addElement('html', '<div style="margin-left:25px;display:block;" id="forever_timewindow">');
+		$form->add_timewindow('subscribe_from', 'subscribe_until', '', '');
+		$form->addElement('html', '</div>');
 
-		$form->addElement('checkbox', 'auto_accept', get_lang('AutoAccept'));
-		//$form->addElement('checkbox', 'timepicker', get_lang('TimePicker'));
-		$timepicker_arr[] = $form->createElement('radio', 'timepicker', '', get_lang('NoTimePicker'), 0, array ('onclick' => 'javascript:window_hide(\'timepicker_timewindow\')'));
-		$timepicker_arr[] = $form->createElement('radio', 'timepicker', '', get_lang('TimePicker'), 1 , array ('onclick' => 'javascript:window_show(\'timepicker_timewindow\')'));
-		$form->addGroup($timepicker_arr, null, get_lang('TimePicker'), '<br />', false);
-		$form->addElement('html', '<div style="margin-left:25px;display:block;" id="timepicker_timewindow">');
+		$form->addElement('checkbox', 'auto_accept', get_lang('AutoAccept'));
+		//$form->addElement('checkbox', 'timepicker', get_lang('TimePicker'));
+		$timepicker_arr[] = $form->createElement('radio', 'timepicker', '', get_lang('NoTimePicker'), 0, array ('onclick' => 'javascript:window_hide(\'timepicker_timewindow\')'));
+		$timepicker_arr[] = $form->createElement('radio', 'timepicker', '', get_lang('TimePicker'), 1 , array ('onclick' => 'javascript:window_show(\'timepicker_timewindow\')'));
+		$form->addGroup($timepicker_arr, null, get_lang('TimePicker'), '<br />', false);
+		$form->addElement('html', '<div style="margin-left:25px;display:block;" id="timepicker_timewindow">');
 
-   		$min_arr = array();
+   		$min_arr = array();
    		//todo this will be fixed
-   		$min_arr[10] = 10;
-   		$min_arr[20] = 20;
-   		$min_arr[30] = 30;
-   		$min_arr[40] = 40;
-   		$min_arr[50] = 50;
+   		$min_arr[10] = 10;
+   		$min_arr[20] = 20;
+   		$min_arr[30] = 30;
+   		$min_arr[40] = 40;
+   		$min_arr[50] = 50;
    		$min_arr[60] = 60;
 
-		for ($i = 0; $i < 1441; $i++) {
-      		//$min_arr[$i] = $i;
-   		}
+		for ($i = 0; $i < 1441; $i++) {
+      		//$min_arr[$i] = $i;
+   		}
 
-		$max_arr = $min_arr;
+		$max_arr = $min_arr;
 
-		$form->addElement('select',min,get_lang('Minimum'),$min_arr);
-		$form->addElement('select',max,get_lang('Maximum'),$max_arr);
+		$form->addElement('select',min,get_lang('Minimum'),$min_arr);
+		$form->addElement('select',max,get_lang('Maximum'),$max_arr);
 
 		$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('TimePickerMinMaxNull').'</div></div><br />');
-		$form->addElement('html', '</div>');
-
-		$recurrence[] = $form->createElement('radio', 'recurrence_c', '', get_lang('NoRecurrence'), 0, array ('onclick' => 'javascript:window_hide(\'recurrence_timewindow\')'));
-		$recurrence[] = $form->createElement('radio', 'recurrence_c', '', get_lang('UntilRecurrence'), 1 , array ('onclick' => 'javascript:window_show(\'recurrence_timewindow\')'));
-		$form->addGroup($recurrence, null, get_lang('Recurrence'), '<br />', false);
-		$form->addElement('html', '<div style="margin-left:25px;display:block;" id="recurrence_timewindow">');
-		$list_time = Rsys:: recurrence_list();
-		$period[] = $form->createElement('text','repeater','',array('size'=>'3'));
-		$period[] = $form->createElement('select','recurrence_selector','',$list_time);
-		$form->addGroup($period, null, get_lang('RepeatFor'), '   ', false);
-		$form->add_datepicker('recurrence_until',get_lang('RepeatUntil'));
-		$form->addElement('html', '</div>');
-		$form->addElement('textarea', 'notes', get_lang('Notes'), array ('cols' => 40, 'rows' => 4));
-		$form->addElement('style_submit_button', 'submit', get_lang('AddNewBookingPeriod'),'class="add"');
-		$str='';
-
-		if(!$_POST['forever']) $str.="window_hide('forever_timewindow');";
-		if(!$_POST['recurrence_c']) $str.="window_hide('recurrence_timewindow');";
-		if(!$_POST['timepicker']) $str.="window_hide('timepicker_timewindow');";
-
-		$form->addElement('html', "<script type=\"text/javascript\">
-											/* <![CDATA[ */
-											".$str."
-											function window_show(item) {
-											el = document.getElementById(item);
-											el.style.display='';
-											}
-											function window_hide(item) {
-											el = document.getElementById(item);
-											el.style.display='none';
-											}
-											/* ]]> */
-											</script>\n");
-		if (count($itemlist) > 0) {
-			// here we set the default start and end time that we will see in the form 1h 30m after now()
-
-			// 1h after now
-			$date_defaults_start = array(
+		$form->addElement('html', '</div>');
+
+		$recurrence[] = $form->createElement('radio', 'recurrence_c', '', get_lang('NoRecurrence'), 0, array ('onclick' => 'javascript:window_hide(\'recurrence_timewindow\')'));
+		$recurrence[] = $form->createElement('radio', 'recurrence_c', '', get_lang('UntilRecurrence'), 1 , array ('onclick' => 'javascript:window_show(\'recurrence_timewindow\')'));
+		$form->addGroup($recurrence, null, get_lang('Recurrence'), '<br />', false);
+		$form->addElement('html', '<div style="margin-left:25px;display:block;" id="recurrence_timewindow">');
+		$list_time = Rsys:: recurrence_list();
+		$period[] = $form->createElement('text','repeater','',array('size'=>'3'));
+		$period[] = $form->createElement('select','recurrence_selector','',$list_time);
+		$form->addGroup($period, null, get_lang('RepeatFor'), '   ', false);
+		$form->add_datepicker('recurrence_until',get_lang('RepeatUntil'));
+		$form->addElement('html', '</div>');
+		$form->addElement('textarea', 'notes', get_lang('Notes'), array ('cols' => 40, 'rows' => 4));
+		$form->addElement('style_submit_button', 'submit', get_lang('AddNewBookingPeriod'),'class="add"');
+		$str='';
+
+		if(!$_POST['forever']) $str.="window_hide('forever_timewindow');";
+		if(!$_POST['recurrence_c']) $str.="window_hide('recurrence_timewindow');";
+		if(!$_POST['timepicker']) $str.="window_hide('timepicker_timewindow');";
+
+		$form->addElement('html', "<script type=\"text/javascript\">
+											/* <![CDATA[ */
+											".$str."
+											function window_show(item) {
+											el = document.getElementById(item);
+											el.style.display='';
+											}
+											function window_hide(item) {
+											el = document.getElementById(item);
+											el.style.display='none';
+											}
+											/* ]]> */
+											</script>\n");
+		if (count($itemlist) > 0) {
+			// here we set the default start and end time that we will see in the form 1h 30m after now()
+
+			// 1h after now
+			$date_defaults_start = array(
 		        'd' => date('d'),
-		        'F' => date('n'),
-		        'Y' => date('Y'),
-		        'H' => date('H',time()+60*60),
-		        'i' => '00'
-		    );
-
-		    //2h after now
-		    $date_defaults_end = array(
+		        'F' => date('n'),
+		        'Y' => date('Y'),
+		        'H' => date('H',time()+60*60),
+		        'i' => '00'
+		    );
+
+		    //2h after now
+		    $date_defaults_end = array(
 		        'd' => date('d'),
-		        'F' => date('n'),
-		        'Y' => date('Y'),
-		        'H' => date('H',time()+60*60*2),
-		        'i' => '00'
-		    );
+		        'F' => date('n'),
+		        'Y' => date('Y'),
+		        'H' => date('H',time()+60*60*2),
+		        'i' => '00'
+		    );
 
 
-		    	// 1h after now
-			$date_defaults_start_sub = array(
+		    	// 1h after now
+			$date_defaults_start_sub = array(
 		        'd' => date('d'),
-		        'F' => date('n'),
-		        'Y' => date('Y'),
-		        'H' => date('H',time()-60*60),
-		        'i' => '00'
-		    );
-
-		    //2h after now
-		    $date_defaults_end_sub = array(
+		        'F' => date('n'),
+		        'Y' => date('Y'),
+		        'H' => date('H',time()-60*60),
+		        'i' => '00'
+		    );
+
+		    //2h after now
+		    $date_defaults_end_sub = array(
 		        'd' => date('d'),
-		        'F' => date('n'),
-		        'Y' => date('Y'),
-		        'H' => date('H',time()),
-		        'i' => '00'
-		    );
+		        'F' => date('n'),
+		        'Y' => date('Y'),
+		        'H' => date('H',time()),
+		        'i' => '00'
+		    );
 
-			$defaultvalues['start'] = $date_defaults_start;
+			$defaultvalues['start'] = $date_defaults_start;
 			$defaultvalues['end'] = $date_defaults_end;
-			$defaultvalues['subscribe_from'] = $date_defaults_start_sub;
-			$defaultvalues['subscribe_until'] = $date_defaults_end_sub;
-			$defaultvalues['recurrence_until'] = $date_defaults_end;
-
-			$defaultvalues['recurrence_c'] = '0';
-			$defaultvalues['forever'] = '0';
-			$defaultvalues['timepicker'] = '0';
-
-			$defaultvalues['maxuser'] = '1';
-			$defaultvalues['repeater'] = '1';
-			$defaultvalues['auto_accept'] = '1';
-
-			$form->setDefaults($defaultvalues);
-			$form->Display();
-		} else {
-			if ($_GET['cat_id'] != 0)
-				Display :: display_normal_message(get_lang('NoItems'),false);
-		}
-
-		$buffer = ob_get_contents();
-		ob_end_clean();
-
-		if ($form->validate()) {
+			$defaultvalues['subscribe_from'] = $date_defaults_start_sub;
+			$defaultvalues['subscribe_until'] = $date_defaults_end_sub;
+			$defaultvalues['recurrence_until'] = $date_defaults_end;
+
+			$defaultvalues['recurrence_c'] = '0';
+			$defaultvalues['forever'] = '0';
+			$defaultvalues['timepicker'] = '0';
+
+			$defaultvalues['maxuser'] = '1';
+			$defaultvalues['repeater'] = '1';
+			$defaultvalues['auto_accept'] = '1';
+
+			$form->setDefaults($defaultvalues);
+			$form->Display();
+		} else {
+			if ($_GET['cat_id'] != 0)
+				Display :: display_normal_message(get_lang('NoItems'),false);
+		}
+
+		$buffer = ob_get_contents();
+		ob_end_clean();
+
+		if ($form->validate()) {
 			$values = $form->exportValues();
-			if ($values['forever'] == 0) {
-				$values['subscribe_from'] = 0;
-				$values['subscribe_until'] = 0;
-			}
-			$msg_number = Rsys :: add_reservation($values['itemid'], $values['auto_accept'], $values['maxuser'], $values['start'], $values['end'], $values['subscribe_from'], $values['subscribe_until'], $values['notes'], $values['timepicker'],$values['min'],$values['max'],0);
-			switch($msg_number) {
-				case 0 :
-					Display :: display_normal_message(Rsys :: get_return_msg(get_lang('BookingPeriodAdded'), "m_reservation.php", $tool_name),false);
-					break;
-				case 1 :
-					Display :: display_normal_message(str_replace('#END#', "<b>".$GLOBALS['end_date']."</b>",str_replace('#START#', "<b>".$GLOBALS['start_date']."</b>",get_lang('BookingPeriodDateOverlap'))),false);
-					break;
+			if ($values['forever'] == 0) {
+				$values['subscribe_from'] = 0;
+				$values['subscribe_until'] = 0;
+			}
+			$msg_number = Rsys :: add_reservation($values['itemid'], $values['auto_accept'], $values['maxuser'], $values['start'], $values['end'], $values['subscribe_from'], $values['subscribe_until'], $values['notes'], $values['timepicker'],$values['min'],$values['max'],0);
+			switch($msg_number) {
+				case 0 :
+					Display :: display_normal_message(Rsys :: get_return_msg(get_lang('BookingPeriodAdded'), "m_reservation.php", $tool_name),false);
+					break;
+				case 1 :
+					Display :: display_normal_message(str_replace('#END#', "<b>".$GLOBALS['end_date']."</b>",str_replace('#START#', "<b>".$GLOBALS['start_date']."</b>",get_lang('BookingPeriodDateOverlap'))),false);
+					break;
 				case 2 :
-					Display :: display_normal_message(get_lang('BookingPeriodSubscribeUntilAfterStart'),false);
-					break;
-				case 3:
-					Display :: display_normal_message(get_lang('BookingPeriodPast'),false);
-					break;
-				case 4:
-					Display :: display_normal_message(get_lang('BookingPeriodTimePickerLimitation'),false);
-					break;
-				case 5:
-					Display :: display_normal_message(get_lang('BookingPeriodTimePickerError1'),false);
-					break;
-				case 6:
-					Display :: display_normal_message(get_lang('BookingPeriodTimePickerError2'),false);
-					break;
-				case 7:
-					Display :: display_normal_message(get_lang('BookingPeriodTimePickerError3'),false);
-					break;
-				default :
-					break;
-			}
-		}
-
-		if($_POST['recurrence_c'] && $msg_number == 0){
-				$Inserted_id = mysql_insert_id();
-				$recurrence_date_start = Rsys :: mysql_datetime_to_timestamp($values['start']);
-				$recurrence_date_end = Rsys :: mysql_datetime_to_timestamp($values['end']);
-				$recurrence_period_end = Rsys :: mysql_datetime_to_timestamp($values['recurrence_until']);
-				$recurrence_subscribe_from = Rsys :: mysql_datetime_to_timestamp($values['subscribe_from']);
-				$count = 0;
-				$recurrence_date_start = $recurrence_date_start + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
-				$recurrence_date_end = $recurrence_date_end + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
-				while($recurrence_date_end < $recurrence_period_end){
-					if ($values['forever'] == 0) {
-						$recurrence_subscribe_from = 0;
-						$recurrence_subscribe_until = 0;
-					}else{
-						$recurrence_subscribe_from = $recurrence_subscribe_from + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
-						$recurrence_subscribe_until = $recurrence_subscribe_until + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
-					}
-					$errors[]=Rsys :: add_reservation($values['itemid'], $values['auto_accept'], $values['maxuser'], Rsys :: timestamp_to_datetime($recurrence_date_start), Rsys :: timestamp_to_datetime($recurrence_date_end), $values['forever'] == 0 ? 0 : Rsys :: timestamp_to_datetime($recurrence_subscribe_from), $values['forever'] == 0 ? 0 : Rsys :: timestamp_to_datetime($recurrence_subscribe_until), $values['notes'], $values['timepicker'],$values['min'],$values['max'],$Inserted_id);
-					if($errors[$count] <> 0){
-						$msg .= str_replace('#START#', "<b>".Rsys :: timestamp_to_datetime($recurrence_date_start)."</b>",str_replace('#END#', "<b>".Rsys :: timestamp_to_datetime($recurrence_date_end)."</b>",get_lang('ReservationFromUntilError')));
-					}
-					$count++;
-					$recurrence_date_start = $recurrence_date_start + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
-					$recurrence_date_end = $recurrence_date_end + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
-				}
-		}
-		if(!empty ($msg))
-		Display :: display_normal_message($msg);
-
-		echo $buffer;
-
-		break;
-	case 'edit' :
-		if (isset ($_GET["id"]))
-			$Reservation_id = $_GET["id"];
-		else
-			$Reservation_id = $_POST["id"];
-
-		$result = Rsys :: get_num_subscriptions_ReservationPeriods($Reservation_id);
-
-		if($result != '0')
-		{
+					Display :: display_normal_message(get_lang('BookingPeriodSubscribeUntilAfterStart'),false);
+					break;
+				case 3:
+					Display :: display_normal_message(get_lang('BookingPeriodPast'),false);
+					break;
+				case 4:
+					Display :: display_normal_message(get_lang('BookingPeriodTimePickerLimitation'),false);
+					break;
+				case 5:
+					Display :: display_normal_message(get_lang('BookingPeriodTimePickerError1'),false);
+					break;
+				case 6:
+					Display :: display_normal_message(get_lang('BookingPeriodTimePickerError2'),false);
+					break;
+				case 7:
+					Display :: display_normal_message(get_lang('BookingPeriodTimePickerError3'),false);
+					break;
+				default :
+					break;
+			}
+		}
+
+		if($_POST['recurrence_c'] && $msg_number == 0){
+				$Inserted_id = mysql_insert_id();
+				$recurrence_date_start = Rsys :: mysql_datetime_to_timestamp($values['start']);
+				$recurrence_date_end = Rsys :: mysql_datetime_to_timestamp($values['end']);
+				$recurrence_period_end = Rsys :: mysql_datetime_to_timestamp($values['recurrence_until']);
+				$recurrence_subscribe_from = Rsys :: mysql_datetime_to_timestamp($values['subscribe_from']);
+				$count = 0;
+				$recurrence_date_start = $recurrence_date_start + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
+				$recurrence_date_end = $recurrence_date_end + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
+				while($recurrence_date_end < $recurrence_period_end){
+					if ($values['forever'] == 0) {
+						$recurrence_subscribe_from = 0;
+						$recurrence_subscribe_until = 0;
+					}else{
+						$recurrence_subscribe_from = $recurrence_subscribe_from + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
+						$recurrence_subscribe_until = $recurrence_subscribe_until + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
+					}
+					$errors[]=Rsys :: add_reservation($values['itemid'], $values['auto_accept'], $values['maxuser'], Rsys :: timestamp_to_datetime($recurrence_date_start), Rsys :: timestamp_to_datetime($recurrence_date_end), $values['forever'] == 0 ? 0 : Rsys :: timestamp_to_datetime($recurrence_subscribe_from), $values['forever'] == 0 ? 0 : Rsys :: timestamp_to_datetime($recurrence_subscribe_until), $values['notes'], $values['timepicker'],$values['min'],$values['max'],$Inserted_id);
+					if($errors[$count] <> 0){
+						$msg .= str_replace('#START#', "<b>".Rsys :: timestamp_to_datetime($recurrence_date_start)."</b>",str_replace('#END#', "<b>".Rsys :: timestamp_to_datetime($recurrence_date_end)."</b>",get_lang('ReservationFromUntilError')));
+					}
+					$count++;
+					$recurrence_date_start = $recurrence_date_start + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
+					$recurrence_date_end = $recurrence_date_end + (60 * 60 * 24 * $values['repeater'] * $values['recurrence_selector']);
+				}
+		}
+		if(!empty ($msg))
+		Display :: display_normal_message($msg);
+
+		echo $buffer;
+
+		break;
+	case 'edit' :
+		if (isset ($_GET["id"]))
+			$Reservation_id = $_GET["id"];
+		else
+			$Reservation_id = $_POST["id"];
+
+		$result = Rsys :: get_num_subscriptions_ReservationPeriods($Reservation_id);
+
+		if($result != '0')
+		{
 			$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
 			$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
-			Display :: display_header('');
-			api_display_tool_title($tool_name);
-			Display :: display_normal_message(Rsys :: get_return_msg(str_replace('#NUM#', $result, get_lang('BookingPeriodHasSubscriptions')),"m_reservation.php",get_lang('BookingPeriodList')),false);
-		}
-		else
+			Display :: display_header('');
+			api_display_tool_title($tool_name);
+			Display :: display_normal_message(Rsys :: get_return_msg(str_replace('#NUM#', $result, get_lang('BookingPeriodHasSubscriptions')),"m_reservation.php",get_lang('BookingPeriodList')),false);
+		}
+		else
 		{
 			$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-			$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
+			$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
 
-			Display :: display_header(get_lang('EditBookingPeriod'));
-			api_display_tool_title(get_lang('EditNewBookingPeriod'));
+			Display :: display_header(get_lang('EditBookingPeriod'));
+			api_display_tool_title(get_lang('EditNewBookingPeriod'));
 
-			$reservation = Rsys :: get_reservation($Reservation_id);
-			$item_category = Rsys :: get_item($reservation[0][2]);
-			$categori = Rsys :: get_category($item_category[1]);
-			$cats = Rsys :: get_category_rights();
-			$tijdelijke_cat = $categori[0];
-			if (isset ($_GET['cat_id']))
-				$categori[0] = $_GET['cat_id'];
+			$reservation = Rsys :: get_reservation($Reservation_id);
+			$item_category = Rsys :: get_item($reservation[0][2]);
+			$categori = Rsys :: get_category($item_category[1]);
+			$cats = Rsys :: get_category_rights();
+			$tijdelijke_cat = $categori[0];
+			if (isset ($_GET['cat_id']))
+				$categori[0] = $_GET['cat_id'];
 
-			ob_start();
+			ob_start();
 
-			echo '<form id="cat_form" action="m_reservation.php" method="get">';
-			echo '<input type="hidden" name="id" value="'.$Reservation_id.'" />';
-			echo '<input type="hidden" name="action" value="edit"/>';
+			echo '<form id="cat_form" action="m_reservation.php" method="get">';
+			echo '<input type="hidden" name="id" value="'.$Reservation_id.'" />';
+			echo '<input type="hidden" name="action" value="edit"/>';
 
 			echo '<div class="row">';
-			echo '<div class="label">'.get_lang('ResourceType').': </div>';
-			echo '<div class="formw">';
+			echo '<div class="label">'.get_lang('ResourceType').': </div>';
+			echo '<div class="formw">';
 
-			echo '<select name="cat_id" onchange="this.form.submit();">';
-			echo '<option value="0">&nbsp;</option>';
-			foreach ($cats as $catid => $cat)
-				echo '<option value="'.$catid.'"'. ($catid == $categori[0] ? ' selected="selected"' : '').'>'.$cat.'</option>';
-			echo '</select></div>';
+			echo '<select name="cat_id" onchange="this.form.submit();">';
+			echo '<option value="0">&nbsp;</option>';
+			foreach ($cats as $catid => $cat)
+				echo '<option value="'.$catid.'"'. ($catid == $categori[0] ? ' selected="selected"' : '').'>'.$cat.'</option>';
+			echo '</select></div>';
 
 			echo '</div>';
 			echo '</form>';
 
-			$itemlist = Rsys :: get_cat_r_items($categori[0]);
-			$form = new FormValidator('reservation', 'post', 'm_reservation.php?action=edit&id='.$Reservation_id);
-			$choices[] = $form->createElement('radio', 'forever', '', get_lang('NoPeriod'), '0', array ('onclick' => 'javascript:timewindow_hide(\'forever_timewindow\')'));
-			$choices[] = $form->createElement('radio', 'forever', '', get_lang('FixedPeriod'), '1', array ('onclick' => 'javascript:timewindow_show(\'forever_timewindow\')'));
-			$form->addElement('select', 'item_id', get_lang('Resource'), $itemlist);
+			$itemlist = Rsys :: get_cat_r_items($categori[0]);
+			$form = new FormValidator('reservation', 'post', 'm_reservation.php?action=edit&id='.$Reservation_id);
+			$choices[] = $form->createElement('radio', 'forever', '', get_lang('NoPeriod'), '0', array ('onclick' => 'javascript:timewindow_hide(\'forever_timewindow\')'));
+			$choices[] = $form->createElement('radio', 'forever', '', get_lang('FixedPeriod'), '1', array ('onclick' => 'javascript:timewindow_show(\'forever_timewindow\')'));
+			$form->addElement('select', 'item_id', get_lang('Resource'), $itemlist);
 
 			$form->add_timewindow('start', 'end', get_lang('StartDate'), get_lang('EndDate'));
-			$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('TimePickerLimitation').'</div></div><br />');
-
-			$form->addElement('text', 'maxuser', get_lang('MaxUsers'));
-			$form->addGroup($choices, null, get_lang('SubscriptionPeriod'), '<br />', false);
-
-			$form->addElement('html', '<div style="margin-left:25px;display:block;" id="forever_timewindow">');
-			$form->add_timewindow('subscribe_from', 'subscribe_until', '', '');
-			$form->addElement('html', '</div>');
-			$form->addElement('html', "<script type=\"text/javascript\">
-												/* <![CDATA[ */
-												". ($reservation[0][7] == '0000-00-00 00:00:00' && $reservation[0][8] == '0000-00-00 00:00:00' ? "timewindow_hide('forever_timewindow');" : "")."
-												function timewindow_show(item) {
-												el = document.getElementById(item);
-												el.style.display='';
-												}
-												function timewindow_hide(item) {
-												el = document.getElementById(item);
-												el.style.display='none';
-												}
-												/* ]]> */
-												</script>\n");
-			$form->addElement('checkbox', 'auto_accept', get_lang('AutoAccept'));
-			$form->addElement('checkbox', 'timepicker', get_lang('TimePicker'),'',array('disabled'=>'disabled'));
-			$form->addElement('textarea', 'notes', get_lang('Notes'), array ('cols' => 40, 'rows' => 4));
-			$form->addElement('style_submit_button', 'submit', get_lang('EditNewBookingPeriod'),'class="save"');
-			$form->addElement('hidden', 'id', $Reservation_id);
-			$form->addElement('hidden', 'timepicker2');
-			$form->addElement('hidden', 'period', ($reservation[0][7] == '0000-00-00 00:00:00' && $reservation[0][8] == '0000-00-00 00:00:00' ? 0 : 1));
-
-			if ($categori[0] == $tijdelijke_cat)
-				$defaultvalues['item_id'] = $reservation[0][2];
-
-			$defaultvalues['auto_accept'] = $reservation[0][3];
-			$defaultvalues['maxuser'] = $reservation[0][4];
-			$defaultvalues['start'] = $reservation[0][5];
-			$defaultvalues['end'] = $reservation[0][6];
-
-			$defaultvalues['forever']=($reservation[0][7] == '0000-00-00 00:00:00' && $reservation[0][8] == '0000-00-00 00:00:00' ? 0 : 1);
-
-			$my_start_date = Rsys :: mysql_datetime_to_timestamp($reservation[0][5]);
-
-			if ($defaultvalues['forever']==0) {
+			$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('TimePickerLimitation').'</div></div><br />');
+
+			$form->addElement('text', 'maxuser', get_lang('MaxUsers'));
+			$form->addGroup($choices, null, get_lang('SubscriptionPeriod'), '<br />', false);
+
+			$form->addElement('html', '<div style="margin-left:25px;display:block;" id="forever_timewindow">');
+			$form->add_timewindow('subscribe_from', 'subscribe_until', '', '');
+			$form->addElement('html', '</div>');
+			$form->addElement('html', "<script type=\"text/javascript\">
+												/* <![CDATA[ */
+												". ($reservation[0][7] == '0000-00-00 00:00:00' && $reservation[0][8] == '0000-00-00 00:00:00' ? "timewindow_hide('forever_timewindow');" : "")."
+												function timewindow_show(item) {
+												el = document.getElementById(item);
+												el.style.display='';
+												}
+												function timewindow_hide(item) {
+												el = document.getElementById(item);
+												el.style.display='none';
+												}
+												/* ]]> */
+												</script>\n");
+			$form->addElement('checkbox', 'auto_accept', get_lang('AutoAccept'));
+			$form->addElement('checkbox', 'timepicker', get_lang('TimePicker'),'',array('disabled'=>'disabled'));
+			$form->addElement('textarea', 'notes', get_lang('Notes'), array ('cols' => 40, 'rows' => 4));
+			$form->addElement('style_submit_button', 'submit', get_lang('EditNewBookingPeriod'),'class="save"');
+			$form->addElement('hidden', 'id', $Reservation_id);
+			$form->addElement('hidden', 'timepicker2');
+			$form->addElement('hidden', 'period', ($reservation[0][7] == '0000-00-00 00:00:00' && $reservation[0][8] == '0000-00-00 00:00:00' ? 0 : 1));
+
+			if ($categori[0] == $tijdelijke_cat)
+				$defaultvalues['item_id'] = $reservation[0][2];
+
+			$defaultvalues['auto_accept'] = $reservation[0][3];
+			$defaultvalues['maxuser'] = $reservation[0][4];
+			$defaultvalues['start'] = $reservation[0][5];
+			$defaultvalues['end'] = $reservation[0][6];
+
+			$defaultvalues['forever']=($reservation[0][7] == '0000-00-00 00:00:00' && $reservation[0][8] == '0000-00-00 00:00:00' ? 0 : 1);
+
+			$my_start_date = Rsys :: mysql_datetime_to_timestamp($reservation[0][5]);
+
+			if ($defaultvalues['forever']==0) {
 				//here we set the default dates
-				$defaultvalues['subscribe_from'] = $my_start_date - 60*60 ;
-				$defaultvalues['subscribe_until'] = $my_start_date - 60 ;
-			}
-			else {
-				$defaultvalues['subscribe_from'] = $reservation[0][7];
+				$defaultvalues['subscribe_from'] = $my_start_date - 60*60 ;
+				$defaultvalues['subscribe_until'] = $my_start_date - 60 ;
+			}
+			else {
+				$defaultvalues['subscribe_from'] = $reservation[0][7];
 				$defaultvalues['subscribe_until'] = $reservation[0][8];
-			}
-
-
-			$defaultvalues['notes'] = $reservation[0][10];
-			$defaultvalues['timepicker'] = $reservation[0][11];
-			$defaultvalues['timepicker2'] = $reservation[0][11];
-			$form->setDefaults($defaultvalues);
-
-			if (count($reservation) > 0) {
-				$form->Display();
-			} else {
-				Display :: display_normal_message(get_lang('NoItems'),false);
-			}
-			$buffer = ob_get_contents();
-			ob_end_clean();
-			if ($form->validate()) {
-				$values = $form->exportValues();
-				//print_r($values);
-				$auto_accept = true;
-				if (($values['forever'] == $values['period']) || $values['forever']=='0') {
-					$values['subscribe_from'] = 0;
-					$values['subscribe_until'] = 0;
-				}
-				$msg_number = Rsys :: edit_reservation($values['id'], $_POST['item_id'], $values['auto_accept'], $values['maxuser'], $values['start'], $values['end'], $values['subscribe_from'], $values['subscribe_until'], $values['notes'], $values['timepicker2']);
-				switch ($msg_number) {
-					case 0 :
-						Display :: display_normal_message(Rsys :: get_return_msg(get_lang('BookingPeriodEdited'), "m_reservation.php", $tool_name),false);
-						break;
-					case 1 :
-						Display :: display_normal_message(str_replace('#END#', "<b>".$GLOBALS['end_date']."</b>",str_replace('#START#', "<b>".$GLOBALS['start_date']."</b>",get_lang('BookingPeriodDateOverlap'))),false);
-						break;
-					case 2 :
-						Display :: display_normal_message(get_lang('BookingPeriodSubscribeUntilAfterStart'),false);
-						break;
-					case 3:
-						Display :: display_normal_message(get_lang('ReservationMaxUsersOverrun'),false);
-						break;
-					case 4:
-						Display :: display_normal_message(get_lang('BookingPeriodTimepickerLimitation'),false);
-						break;
-					default :
-						break;
-				}
-			}
-
-			echo $buffer;
-		}
-		break;
-	case 'delete' :
-		Rsys :: delete_reservation($_GET["id"]);
-		ob_start();
-		Display :: display_normal_message(Rsys :: get_return_msg(get_lang('BookingPeriodDeleted'), "m_reservation.php", $tool_name),false);
-		$msg = ob_get_contents();
-		ob_end_clean();
-	default :
-		$NoSearchResults = get_lang('NoReservations');
-
-		if ($_GET['view']=='calendar') {
+			}
+
+
+			$defaultvalues['notes'] = $reservation[0][10];
+			$defaultvalues['timepicker'] = $reservation[0][11];
+			$defaultvalues['timepicker2'] = $reservation[0][11];
+			$form->setDefaults($defaultvalues);
+
+			if (count($reservation) > 0) {
+				$form->Display();
+			} else {
+				Display :: display_normal_message(get_lang('NoItems'),false);
+			}
+			$buffer = ob_get_contents();
+			ob_end_clean();
+			if ($form->validate()) {
+				$values = $form->exportValues();
+				//print_r($values);
+				$auto_accept = true;
+				if (($values['forever'] == $values['period']) || $values['forever']=='0') {
+					$values['subscribe_from'] = 0;
+					$values['subscribe_until'] = 0;
+				}
+				$msg_number = Rsys :: edit_reservation($values['id'], $_POST['item_id'], $values['auto_accept'], $values['maxuser'], $values['start'], $values['end'], $values['subscribe_from'], $values['subscribe_until'], $values['notes'], $values['timepicker2']);
+				switch ($msg_number) {
+					case 0 :
+						Display :: display_normal_message(Rsys :: get_return_msg(get_lang('BookingPeriodEdited'), "m_reservation.php", $tool_name),false);
+						break;
+					case 1 :
+						Display :: display_normal_message(str_replace('#END#', "<b>".$GLOBALS['end_date']."</b>",str_replace('#START#', "<b>".$GLOBALS['start_date']."</b>",get_lang('BookingPeriodDateOverlap'))),false);
+						break;
+					case 2 :
+						Display :: display_normal_message(get_lang('BookingPeriodSubscribeUntilAfterStart'),false);
+						break;
+					case 3:
+						Display :: display_normal_message(get_lang('ReservationMaxUsersOverrun'),false);
+						break;
+					case 4:
+						Display :: display_normal_message(get_lang('BookingPeriodTimepickerLimitation'),false);
+						break;
+					default :
+						break;
+				}
+			}
+
+			echo $buffer;
+		}
+		break;
+	case 'delete' :
+		Rsys :: delete_reservation($_GET["id"]);
+		ob_start();
+		Display :: display_normal_message(Rsys :: get_return_msg(get_lang('BookingPeriodDeleted'), "m_reservation.php", $tool_name),false);
+		$msg = ob_get_contents();
+		ob_end_clean();
+	default :
+		$NoSearchResults = get_lang('NoReservations');
+
+		if ($_GET['view']=='calendar') {
 			$interbreadcrumb[] = array ("url" => "reservation.php", "name" => get_lang('Booking'));
-		}
-		else {
+		}
+		else {
 			$interbreadcrumb[] = array ("url" => "mysubscriptions.php", "name" => get_lang('Booking'));
-		}
-		$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
-
-		Display :: display_header('');
-		api_display_tool_title($tool_name);
-
-		echo '<form id="cat_form" action="m_reservation.php" method="get">';
-
-		echo '<div class="actions">';
-		echo '<a href="m_reservation.php?action=add"><img src="../img/view_more_stats.gif" border="0" alt="" title="'.get_lang('AddNewBookingPeriod').'"/>'.get_lang('AddNewBookingPeriod').'</a>';
-		echo '&nbsp;&nbsp;&nbsp;<a href="m_reservation.php?action=overviewsubscriptions">'.get_lang('OverviewReservedPeriods').'</a>';
-		echo '</div>';
-		echo '<div style="text-align: right; "><input type="text" name="keyword" /><button type="submit" class="search" value="'.get_lang('Search').'" >'.get_lang('Search').'</button></div></form>';
-
-		echo '<br>';
-		if (isset ($_POST['action'])) {
-			switch ($_POST['action']) {
-				case 'delete_reservations' :
-					$ids = $_POST['reservations'];
-					if (count($ids) > 0) {
-						foreach ($ids as $index => $id)
-							Rsys :: delete_reservation($id);
-					}
-					break;
-			}
-		}
-		$table = new SortableTable('reservation', array ('Rsys', 'get_num_reservations'), array ('Rsys', 'get_table_reservations'), 1);
-		$table->set_additional_parameters(array ('keyword' => $_GET['keyword']));
-		$table->set_header(0, '', false, array ('style' => 'width:10px'));
-		$table->set_header(1, get_lang('ResourceName'), true);
-		$table->set_header(2, get_lang('StartDate'), true);
-		$table->set_header(3, get_lang('EndDate'), true);
-		$table->set_header(4, get_lang('SubscribeFrom'), true);
-		$table->set_header(5, get_lang('SubscribeUntil'), true);
-		$table->set_header(6, get_lang('Subscribers'), true);
-		$table->set_header(7, get_lang('Notes'), false);
-		$table->set_header(8, '', false, array ('style' => 'width:65px;'));
-		$table->set_column_filter(8, 'modify_filter');
-		$table->set_form_actions(array ('delete_reservations' => get_lang('DeleteSelectedBookingPeriod')), 'reservations');
-		$table->display();
-
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-Display :: display_footer();
-?>
+		}
+		$interbreadcrumb[] = array ("url" => "m_reservation.php", "name" => get_lang('ManageBookingPeriods'));
+
+		Display :: display_header('');
+		api_display_tool_title($tool_name);
+
+		echo '<form id="cat_form" action="m_reservation.php" method="get">';
+
+		echo '<div class="actions">';
+		echo '<a href="m_reservation.php?action=add"><img src="../img/view_more_stats.gif" border="0" alt="" title="'.get_lang('AddNewBookingPeriod').'"/>'.get_lang('AddNewBookingPeriod').'</a>';
+		echo '&nbsp;&nbsp;&nbsp;<a href="m_reservation.php?action=overviewsubscriptions">'.get_lang('OverviewReservedPeriods').'</a>';
+		echo '</div>';
+		echo '<div style="text-align: right; "><input type="text" name="keyword" /><button type="submit" class="search" value="'.get_lang('Search').'" >'.get_lang('Search').'</button></div></form>';
+
+		echo '<br>';
+		if (isset ($_POST['action'])) {
+			switch ($_POST['action']) {
+				case 'delete_reservations' :
+					$ids = $_POST['reservations'];
+					if (count($ids) > 0) {
+						foreach ($ids as $index => $id)
+							Rsys :: delete_reservation($id);
+					}
+					break;
+			}
+		}
+		$table = new SortableTable('reservation', array ('Rsys', 'get_num_reservations'), array ('Rsys', 'get_table_reservations'), 1);
+		$table->set_additional_parameters(array ('keyword' => $_GET['keyword']));
+		$table->set_header(0, '', false, array ('style' => 'width:10px'));
+		$table->set_header(1, get_lang('ResourceName'), true);
+		$table->set_header(2, get_lang('StartDate'), true);
+		$table->set_header(3, get_lang('EndDate'), true);
+		$table->set_header(4, get_lang('SubscribeFrom'), true);
+		$table->set_header(5, get_lang('SubscribeUntil'), true);
+		$table->set_header(6, get_lang('Subscribers'), true);
+		$table->set_header(7, get_lang('Notes'), false);
+		$table->set_header(8, '', false, array ('style' => 'width:65px;'));
+		$table->set_column_filter(8, 'modify_filter');
+		$table->set_form_actions(array ('delete_reservations' => get_lang('DeleteSelectedBookingPeriod')), 'reservations');
+		$table->display();
+
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+Display :: display_footer();
+?>

+ 103 - 103
main/reservation/mysubscriptions.php

@@ -1,108 +1,108 @@
-<?php // $Id: mysubscriptions.php,v 1.3 2006/04/27 14:14:03 kvansteenkiste Exp $
-/*
-==============================================================================
-    Dokeos - elearning and course management software
-
-    Copyright (c) 2004-2008 Dokeos S.
-    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
-    Copyright (c) Kristof Van Steenkiste
-    Copyright (c) Julio Montoya Armas
-
-    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
-==============================================================================
-*/
-/**
-    ---------------------------------------------------------------------
-        An overview with a list of upcoming reservations where
-        the user has subscribed to (may also be viewable in the agenda)
-
-        Later: links to m_item & m_reservation for every item your group (class) owns and
-        the possibility (links) for adding new items or reservations
-    ---------------------------------------------------------------------
- */
-require_once('rsys.php');
-
-Rsys::protect_script('mysubscriptions');
-$tool_name = get_lang('Booking');
-
-/**
-    ---------------------------------------------------------------------
- */
-
-/**
- *  Filter to display the modify-buttons
- */
-function modify_filter($id){
+<?php // $Id: mysubscriptions.php,v 1.3 2006/04/27 14:14:03 kvansteenkiste Exp $
+/*
+==============================================================================
+    Dokeos - elearning and course management software
+
+    Copyright (c) 2004-2008 Dokeos S.
+    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
+    Copyright (c) Kristof Van Steenkiste
+    Copyright (c) Julio Montoya Armas
+
+    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
+==============================================================================
+*/
+/**
+    ---------------------------------------------------------------------
+        An overview with a list of upcoming reservations where
+        the user has subscribed to (may also be viewable in the agenda)
+
+        Later: links to m_item & m_reservation for every item your group (class) owns and
+        the possibility (links) for adding new items or reservations
+    ---------------------------------------------------------------------
+ */
+require_once('rsys.php');
+
+Rsys::protect_script('mysubscriptions');
+$tool_name = get_lang('Booking');
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+/**
+ *  Filter to display the modify-buttons
+ */
+function modify_filter($id){
      return ' <a href="mysubscriptions.php?action=delete&amp;reservation_id='.substr($id,0,strpos($id,'-')).'&amp;dummy='.substr($id,strrpos($id,'-')+1).'" title="'.get_lang("DeleteSubscription").'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmDeleteSubscription")))."'".')) return false;"><img alt="" src="../img/delete.gif" /></a>';
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
-switch ($_GET['action']) {
-    case 'delete' :
-        Rsys :: delete_subscription($_GET['reservation_id'],$_GET['dummy']);
-        ob_start();
-        Display :: display_normal_message(Rsys::get_return_msg(get_lang('SubscriptionDeleted'),"mysubscriptions.php",$tool_name),false);
-        $msg=ob_get_contents();
-		ob_end_clean();
-    default :
-        $NoSearchResults=get_lang('NoReservations');
-        Display :: display_header($tool_name);
-        api_display_tool_title($tool_name);
-
-        if (api_is_allowed_to_create_course()) {
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
+switch ($_GET['action']) {
+    case 'delete' :
+        Rsys :: delete_subscription($_GET['reservation_id'],$_GET['dummy']);
+        ob_start();
+        Display :: display_normal_message(Rsys::get_return_msg(get_lang('SubscriptionDeleted'),"mysubscriptions.php",$tool_name),false);
+        $msg=ob_get_contents();
+		ob_end_clean();
+    default :
+        $NoSearchResults=get_lang('NoReservations');
+        Display :: display_header($tool_name);
+        api_display_tool_title($tool_name);
+
+        if (api_is_allowed_to_create_course()) {
 	        echo '<div class="actions">';
-			echo '<div style="float: right;"><a href="reservation.php">'.Display::return_icon('sessions.gif',get_lang('BookingCalendarView')).'&nbsp;'.get_lang('GoToCalendarView').'</a></div>';
+			echo '<div style="float: right;"><a href="reservation.php">'.Display::return_icon('sessions.gif',get_lang('BookingCalendarView')).'&nbsp;'.get_lang('GoToCalendarView').'</a></div>';
 			echo '<a href="m_item.php?view=list">'.Display::return_icon('cube.png',get_lang('Resources')).'&nbsp;'.get_lang('Resources').'</a>';
-			echo '&nbsp;&nbsp;<a href="m_reservation.php?view=list">'.Display::return_icon('calendar_day.gif',get_lang('BookingPeriods')).'&nbsp;'.get_lang('BookingPeriods').'</a>';
-			echo '&nbsp;&nbsp;<a href="m_reservation.php?action=add&view=list">'.Display::return_icon('calendar_add.gif',get_lang('BookIt')).'&nbsp;'.get_lang('BookIt').'</a>';
-
-			if (api_is_platform_admin()) {
-				//echo '&nbsp;&nbsp;<a href="m_category.php">'.Display::return_icon('settings.gif',get_lang('Configuration')).'&nbsp;'.get_lang('Configuration').'</a>';
-			}
-			echo '</div><br />';
-        }
-
-        if (isset ($_POST['action'])) {
-            switch ($_POST['action']) {
-                case 'delete_subscriptions' :
-                    $ids = $_POST['subscriptions'];
-                    if (count($ids) > 0) {
-                        foreach ($ids as $id)
-                            Rsys :: delete_subscription(substr($id,0,strpos($id,'-')),substr($id,strrpos($id,'-')+1));
-                    }
-                    break;
-            }
-        }
-
-        $table = new SortableTable('subscription', array('Rsys','get_num_subscriptions'),array('Rsys','get_table_subscriptions'),2);
-        $table->set_header(0, '', false,array('style'=>'width:10px'));
-        $table->set_header(1, get_lang('ResourceName'), true);
-        $table->set_header(2, get_lang('StartDate'), true);
-        $table->set_header(3, get_lang('EndDate'), true);
-		$table->set_header(4, get_lang('Accept'), true);
+			echo '&nbsp;&nbsp;<a href="m_reservation.php?view=list">'.Display::return_icon('calendar_day.gif',get_lang('BookingPeriods')).'&nbsp;'.get_lang('BookingPeriods').'</a>';
+			echo '&nbsp;&nbsp;<a href="m_reservation.php?action=add&view=list">'.Display::return_icon('calendar_add.gif',get_lang('BookIt')).'&nbsp;'.get_lang('BookIt').'</a>';
+
+			if (api_is_platform_admin()) {
+				//echo '&nbsp;&nbsp;<a href="m_category.php">'.Display::return_icon('settings.gif',get_lang('Configuration')).'&nbsp;'.get_lang('Configuration').'</a>';
+			}
+			echo '</div><br />';
+        }
+
+        if (isset ($_POST['action'])) {
+            switch ($_POST['action']) {
+                case 'delete_subscriptions' :
+                    $ids = $_POST['subscriptions'];
+                    if (count($ids) > 0) {
+                        foreach ($ids as $id)
+                            Rsys :: delete_subscription(substr($id,0,strpos($id,'-')),substr($id,strrpos($id,'-')+1));
+                    }
+                    break;
+            }
+        }
+
+        $table = new SortableTable('subscription', array('Rsys','get_num_subscriptions'),array('Rsys','get_table_subscriptions'),2);
+        $table->set_header(0, '', false,array('style'=>'width:10px'));
+        $table->set_header(1, get_lang('ResourceName'), true);
+        $table->set_header(2, get_lang('StartDate'), true);
+        $table->set_header(3, get_lang('EndDate'), true);
+		$table->set_header(4, get_lang('Accept'), true);
         $table->set_header(5, get_lang('Modify'), false,array('style'=>'width:50px;'));
-        $table->set_column_filter(5, 'modify_filter');
-        $table->set_form_actions(array ('delete_subscriptions' => get_lang('DeleteSelectedSubscriptions')),'subscriptions');
-        $table->display();
-}
-
-/**
-    ---------------------------------------------------------------------
- */
-
+        $table->set_column_filter(5, 'modify_filter');
+        $table->set_form_actions(array ('delete_subscriptions' => get_lang('DeleteSelectedSubscriptions')),'subscriptions');
+        $table->display();
+}
+
+/**
+    ---------------------------------------------------------------------
+ */
+
 Display :: display_footer();
-?>
+?>

+ 439 - 439
main/reservation/rcalendar.php

@@ -1,475 +1,475 @@
-<?php // $Id: rcalendar.php,v 1.50 2006/05/12 07:33:26 sjacobs Exp $
-/*
-==============================================================================
-    Dokeos - elearning and course management software
-
-    Copyright (c) 2004-2008 Dokeos SPRL
-    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
-    Copyright (c) Kristof Van Steenkiste
-
-    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
-==============================================================================
-*/
-/**
-    --------------
-    The rCalendar
-    --------------
- */
-$DaysShort = api_get_week_days_short();
-$DaysLong = api_get_week_days_long();
-$MonthsLong = api_get_months_long();
-
-class rCalendar {
-	function rCalendar() {
-	}
-	function get_short_day($day) {
-		global $DaysShort;
-		return $DaysShort[$day];
-	}
-	function get_long_day($day) {
-		global $DaysLong;
-		return $DaysLong[$day];
-	}
-	function get_long_month($month) {
-		global $MonthsLong;
-		return $MonthsLong[$month];
-	}
-
-    /*
-     * Deze methode retourneert de maandkalender waarbij dagen MET RESERVATIES groen worden en dagen zonder, grijs
+<?php // $Id: rcalendar.php,v 1.50 2006/05/12 07:33:26 sjacobs Exp $
+/*
+==============================================================================
+    Dokeos - elearning and course management software
+
+    Copyright (c) 2004-2008 Dokeos SPRL
+    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
+    Copyright (c) Kristof Van Steenkiste
+
+    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
+==============================================================================
+*/
+/**
+    --------------
+    The rCalendar
+    --------------
+ */
+$DaysShort = api_get_week_days_short();
+$DaysLong = api_get_week_days_long();
+$MonthsLong = api_get_months_long();
+
+class rCalendar {
+	function rCalendar() {
+	}
+	function get_short_day($day) {
+		global $DaysShort;
+		return $DaysShort[$day];
+	}
+	function get_long_day($day) {
+		global $DaysLong;
+		return $DaysLong[$day];
+	}
+	function get_long_month($month) {
+		global $MonthsLong;
+		return $MonthsLong[$month];
+	}
+
+    /*
+     * Deze methode retourneert de maandkalender waarbij dagen MET RESERVATIES groen worden en dagen zonder, grijs
      *
-     */
-	function get_mini_month($month, $year, $extra, $itemid) {
-		global $DaysShort;
-		$month = intval($month);
-		if ($month < 10)
-			$month = '0'.$month;
-		$stamp = Rsys :: mysql_datetime_to_timestamp($year.'-'.$month.'-01 00:00:00');
-		$daysinmonth = date('t', $stamp);
-		$dayofweek = date('w', $stamp); // 0-6
-		if ($dayofweek == 0)
-			$dayofweek = 7; // 1-7...
-		echo '<table style="padding:0.2em;border:1px solid #000" cellspacing="1"><tr><th><a style="font-size: 11px;font-family: Verdana,sans-serif;" href="reservation.php?item='.$itemid.'&amp;viewday&amp;changemonth=yes&amp;date='. ($month == 1 ? $year -1 : $year).'-'. ($month == 1 ? 12 : $month -1).'-1'.$extra.'">&laquo;</a></th><th colspan="5" style="font-family: Verdana,sans-serif;border:2px inset #000;background-color:#FF0;font-size:11px">'.$this->get_long_month($month -1).' '.$year.'</th><th><a href="reservation.php?item='.$itemid.'&amp;viewday&amp;changemonth=yes&amp;date='. ($month == 12 ? $year +1 : $year).'-'. ($month == 12 ? 1 : $month +1).'-1'.$extra.'" style="font-size: 11px;font-family: Verdana,sans-serif;">&raquo;</a></th></tr><tr>';
-		for ($i = 1; $i <= 7; $i ++) {
-			echo '<th style="color:#036;font-size: 10px;font-family: Verdana,sans-serif; padding: 3px 0.2em 3px 0.2em">'.$this->get_short_day($i == 7 ? 0 : $i).'</th>';
-		}
-		echo '</tr><tr>';
-		for ($i = 1; $i <= 42; $i ++) {
-			if ($i - $dayofweek < $daysinmonth && $i >= $dayofweek)
-				echo '<td style="border-bottom:1px solid #CCE;cursor: pointer;border-right:1px solid #CCE;text-align: center;font-size: 11px;font-family: Verdana,sans-serif;" onmouseout="this.style.background=\'#FFF\'" onmouseover="this.style.background=\'#FF0\'" onclick="document.location.href=\'?viewday&amp;date='.$year.'-'.$month.'-'. ($i - $dayofweek +1).$extra.'\'"><a href="?viewday&amp;date='.$year.'-'.$month.'-'. ($i - $dayofweek +1).$extra.'" style="color:'
+     */
+	function get_mini_month($month, $year, $extra, $itemid) {
+		global $DaysShort;
+		$month = intval($month);
+		if ($month < 10)
+			$month = '0'.$month;
+		$stamp = Rsys :: mysql_datetime_to_timestamp($year.'-'.$month.'-01 00:00:00');
+		$daysinmonth = date('t', $stamp);
+		$dayofweek = date('w', $stamp); // 0-6
+		if ($dayofweek == 0)
+			$dayofweek = 7; // 1-7...
+		echo '<table style="padding:0.2em;border:1px solid #000" cellspacing="1"><tr><th><a style="font-size: 11px;font-family: Verdana,sans-serif;" href="reservation.php?item='.$itemid.'&amp;viewday&amp;changemonth=yes&amp;date='. ($month == 1 ? $year -1 : $year).'-'. ($month == 1 ? 12 : $month -1).'-1'.$extra.'">&laquo;</a></th><th colspan="5" style="font-family: Verdana,sans-serif;border:2px inset #000;background-color:#FF0;font-size:11px">'.$this->get_long_month($month -1).' '.$year.'</th><th><a href="reservation.php?item='.$itemid.'&amp;viewday&amp;changemonth=yes&amp;date='. ($month == 12 ? $year +1 : $year).'-'. ($month == 12 ? 1 : $month +1).'-1'.$extra.'" style="font-size: 11px;font-family: Verdana,sans-serif;">&raquo;</a></th></tr><tr>';
+		for ($i = 1; $i <= 7; $i ++) {
+			echo '<th style="color:#036;font-size: 10px;font-family: Verdana,sans-serif; padding: 3px 0.2em 3px 0.2em">'.$this->get_short_day($i == 7 ? 0 : $i).'</th>';
+		}
+		echo '</tr><tr>';
+		for ($i = 1; $i <= 42; $i ++) {
+			if ($i - $dayofweek < $daysinmonth && $i >= $dayofweek)
+				echo '<td style="border-bottom:1px solid #CCE;cursor: pointer;border-right:1px solid #CCE;text-align: center;font-size: 11px;font-family: Verdana,sans-serif;" onmouseout="this.style.background=\'#FFF\'" onmouseover="this.style.background=\'#FF0\'" onclick="document.location.href=\'?viewday&amp;date='.$year.'-'.$month.'-'. ($i - $dayofweek +1).$extra.'\'"><a href="?viewday&amp;date='.$year.'-'.$month.'-'. ($i - $dayofweek +1).$extra.'" style="color:'
 
                  // Hier wordt een boolean bepaald voor elke dag, TRUE=reservaties op die dag>>Groen, FALSE=geen reservaties op die dag>>Grijs
-                 // (TODO: legende-kleuren retourneren ipv TRUE of FALSE)
-                 //.(Rsys :: check_date_month_calendar($year,$month,($i - $dayofweek +1),$itemid) ? "#0C0" : "#666").
-				//.Rsys :: check_date_month_calendar($year,$month,($i - $dayofweek +1),$itemid).
-                 .(Rsys :: check_date_month_calendar($year.'-'.$month.'-'. ($i - $dayofweek +1),$itemid) ? "#0C0" : "#666").
-
-                    '">'.($i - $dayofweek +1).'</a></td>';
-			elseif ($i < $dayofweek) echo '<td>&nbsp;</td>';
-			else
-				break;
-			if ($i +1 - $dayofweek < $daysinmonth && $i +1 > $dayofweek && $i % 7 == 0)
-				echo '</tr><tr>';
-		}
-		echo '</tr></table>';
-	}
-
-    /*
-     * Deze methode retourneert een balkje van een gegeven $width met een bepaalde kleur ($color) met evt. een titel
+                 // (TODO: legende-kleuren retourneren ipv TRUE of FALSE)
+                 //.(Rsys :: check_date_month_calendar($year,$month,($i - $dayofweek +1),$itemid) ? "#0C0" : "#666").
+				//.Rsys :: check_date_month_calendar($year,$month,($i - $dayofweek +1),$itemid).
+                 .(Rsys :: check_date_month_calendar($year.'-'.$month.'-'. ($i - $dayofweek +1),$itemid) ? "#0C0" : "#666").
+
+                    '">'.($i - $dayofweek +1).'</a></td>';
+			elseif ($i < $dayofweek) echo '<td>&nbsp;</td>';
+			else
+				break;
+			if ($i +1 - $dayofweek < $daysinmonth && $i +1 > $dayofweek && $i % 7 == 0)
+				echo '</tr><tr>';
+		}
+		echo '</tr></table>';
+	}
+
+    /*
+     * Deze methode retourneert een balkje van een gegeven $width met een bepaalde kleur ($color) met evt. een titel
      *
-     */
-	function get_bar($width, $color, $link = '', $title = '', $itemid=null, $cat=null) {
-		// 1) width herberekenen om afrondingsfouten te beperken
-		if($GLOBALS['weekday_pointer']!=$GLOBALS['last_weekday_pointer']) {
-			$GLOBALS['daytotal']=0;
-			$GLOBALS['lasttotal']=0;
-			$GLOBALS['last_weekday_pointer']=$GLOBALS['weekday_pointer'];
-		}
-
-		$GLOBALS['daytotal']+=$width;
-		$GLOBALS['rounded_total']=round($GLOBALS['daytotal']);
-		$width=$GLOBALS['rounded_total']-$GLOBALS['lasttotal'];
-		$GLOBALS['lasttotal']=$GLOBALS['rounded_total'];
-		// 2) kleur aanpassen indien item op blackout staat
-		if($GLOBALS['bblackout'] && $color!='red' && $color!='orange' && $color!='grey') {
-			$color='black';
-			$link='';
-		}
-		$img='';
+     */
+	function get_bar($width, $color, $link = '', $title = '', $itemid=null, $cat=null) {
+		// 1) width herberekenen om afrondingsfouten te beperken
+		if($GLOBALS['weekday_pointer']!=$GLOBALS['last_weekday_pointer']) {
+			$GLOBALS['daytotal']=0;
+			$GLOBALS['lasttotal']=0;
+			$GLOBALS['last_weekday_pointer']=$GLOBALS['weekday_pointer'];
+		}
+
+		$GLOBALS['daytotal']+=$width;
+		$GLOBALS['rounded_total']=round($GLOBALS['daytotal']);
+		$width=$GLOBALS['rounded_total']-$GLOBALS['lasttotal'];
+		$GLOBALS['lasttotal']=$GLOBALS['rounded_total'];
+		// 2) kleur aanpassen indien item op blackout staat
+		if($GLOBALS['bblackout'] && $color!='red' && $color!='orange' && $color!='grey') {
+			$color='black';
+			$link='';
+		}
+		$img='';
 		// 3) html code returnen voor gekleurde bar
-		if (!empty($itemid) && !empty($cat)&& !empty($link)) {
-			$link.='&cat='.$cat.'&item='.$itemid;
-			$img = '<img src="../img/px_'.$color.'.gif" alt="" style="height: 15px;width: '.$width.'px'. (!empty ($link) ? ';cursor: pointer;" onclick="window.location.href=\''.$link.'\'"' : (!empty ($title) ? ';cursor: help;"' : '"')). (!empty ($title) ? ' title="'.$title.'"' : '').' />';
-		}
+		if (!empty($itemid) && !empty($cat)&& !empty($link)) {
+			$link.='&cat='.$cat.'&item='.$itemid;
+			$img = '<img src="../img/px_'.$color.'.gif" alt="" style="height: 15px;width: '.$width.'px'. (!empty ($link) ? ';cursor: pointer;" onclick="window.location.href=\''.$link.'\'"' : (!empty ($title) ? ';cursor: help;"' : '"')). (!empty ($title) ? ' title="'.$title.'"' : '').' />';
+		}
 		else {
 			$img = '<img src="../img/px_'.$color.'.gif" alt="" style="height: 15px;width: '.$width.'px'. (!empty ($link) ? ';cursor: pointer;" onclick="window.location.href=\''.$link.'\'"' : (!empty ($title) ? ';cursor: help;"' : '"')). (!empty ($title) ? ' title="'.$title.'"' : '').' />';
 		}
-		return $img;
+		return $img;
 
-	}
+	}
 
-    /*
-     * Deze methode retourneert de weekkalender
+    /*
+     * Deze methode retourneert de weekkalender
      *
      *  - Deze methode ontvangt een item-id & 1 dag als parameter (dag+maand+jaar), de omliggende week (met reservaties etc.) wordt dan opgehaald
-     *  - hoe groter de $day_scale, hoe kleiner de tabel (86400/$day_scale=breedte van 1 dag)
-     */
-	function get_week_view($day, $month, $year, $itemid, $day_scale = 180,$cat) {
-        // 1) Item is blackout? >> True of False ... wordt gebruikt in get_bar methode om kleur indien nodig om te zetten
+     *  - hoe groter de $day_scale, hoe kleiner de tabel (86400/$day_scale=breedte van 1 dag)
+     */
+	function get_week_view($day, $month, $year, $itemid, $day_scale = 180,$cat) {
+        // 1) Item is blackout? >> True of False ... wordt gebruikt in get_bar methode om kleur indien nodig om te zetten
         $GLOBALS['bblackout']=Rsys::is_blackout($itemid);
 
-        // 2) $day_scale controleren en aanpassen indien nodig
-        // Day_scale mag niet groter zijn dan 3600 (anders wordt de tabel te klein)
-        	if ($day_scale > 3600)
-	     		$day_scale = 3600;
-        // Day_scale mag niet kleiner zijn dan  1 (anders wordt de tabel te groot)
+        // 2) $day_scale controleren en aanpassen indien nodig
+        // Day_scale mag niet groter zijn dan 3600 (anders wordt de tabel te klein)
+        	if ($day_scale > 3600)
+	     		$day_scale = 3600;
+        // Day_scale mag niet kleiner zijn dan  1 (anders wordt de tabel te groot)
 	 	elseif ($day_scale < 1)
-            		$day_scale = 1;
+            		$day_scale = 1;
 
         // 3) Een '0' voor de maand-integer zetten indien deze kleiner is dan 10, nodig voor datetime
-        // bv voor 1 december 1985: '01-12-1985' ipv '1-12-1985' (S�ba's geboortedatum ^^)
-        	if ($month < 10)
-	      		$month = '0'.$month;
-
-        // 4) Bepaal de juiste start datum (maandag) van de omliggende week
-        // (verander eventueel maand (en jaar) wanneer de maandag in de vorige maand/jaar ligt)
-		$fromdate = $year.'-'.$month.'-'. ($day < 10 ? '0'.$day : $day).' 00:00:00';
-		$stamp = Rsys :: mysql_datetime_to_timestamp($fromdate);
-		$dayofweek = date('w', $stamp);
-		if ($dayofweek == 0) {
-			$stamp = $stamp - (1);
-			$datum = Rsys :: mysql_datetime_to_array(Rsys :: timestamp_to_datetime($stamp));
-			$day = $datum['day'];
-			$month = $datum['month'];
-			$year = $datum['year'];
-		}
-		$fromdate = $year.'-'.$month.'-'.$day.' 00:00:00';
-		$stamp = Rsys :: mysql_datetime_to_timestamp($fromdate);
-		$dayofweek = date('w', $stamp);
-		if ($day - $dayofweek < 0) {
-			$stamp = $stamp - (60 * 60 * 24 * ($dayofweek -1));
-			$fromdate = Rsys :: timestamp_to_datetime($stamp);
-			$tilldate = $stamp;
-		} else {
-			$day = $day - $dayofweek +1; // M-FIX: sunday + 1 = monday
-			$fromdate = $year.'-'.$month.'-'. ($day < 10 ? '0'.$day : $day).' 00:00:00';
-			$tilldate = Rsys :: mysql_datetime_to_timestamp($fromdate);
-		}
-       //zeven Dagen opvullen en eind-datum bepalen (= startdatum + 7 dagen)
-		for ($i = 1; $i <= 7; $i ++) {
-			$day_start_dates[$i] = $tilldate;
-			$tilldate += 60 * 60 * 24;
-		}
-
-       // 5) Haal de reservaties periodes (+ reservaties) op tussen de start en einddatum
-		$arr = Rsys :: get_item_reservations($fromdate, Rsys :: timestamp_to_datetime($tilldate), $itemid);
-
-	// 6) Doorloop $arr met reservatie periodes en vul de $days array op met balkjes (bars) voor elke dag
-		$weekday_pointer = $GLOBALS['weekday_pointer'] = 1; // Stel de weekdag pointer in op 1 (=maandag)
-		$one_day = 60 * 60 * 24 - 1; // Het aantal seconden dat ��n dag in beslag neemt (23:59:59)
-		$last_end = $day_start_dates[1]; // Stel de $last_end pointer in op het begin van maandag (00:00:00)
-		if (count($arr['reservations'])>0) {
-			foreach ($arr['reservations'] as $res_id => $res) {
-				// 6.1) Stel basis variabelen in
-				$r = $res['info'];       // Reservatie periode informatie (start en eind tijd etc.)
-				$s = $res['subscriptions']; // Reservaties (inschrijvingen) op reservatie periode
-				$start = Rsys :: mysql_datetime_to_timestamp($r['start_at']); // Start tijd van reservatie periode blok
-				$end = Rsys :: mysql_datetime_to_timestamp($r['end_at']); // Eind tijd van reservatie periode blok
+        // bv voor 1 december 1985: '01-12-1985' ipv '1-12-1985' (S�ba's geboortedatum ^^)
+        	if ($month < 10)
+	      		$month = '0'.$month;
+
+        // 4) Bepaal de juiste start datum (maandag) van de omliggende week
+        // (verander eventueel maand (en jaar) wanneer de maandag in de vorige maand/jaar ligt)
+		$fromdate = $year.'-'.$month.'-'. ($day < 10 ? '0'.$day : $day).' 00:00:00';
+		$stamp = Rsys :: mysql_datetime_to_timestamp($fromdate);
+		$dayofweek = date('w', $stamp);
+		if ($dayofweek == 0) {
+			$stamp = $stamp - (1);
+			$datum = Rsys :: mysql_datetime_to_array(Rsys :: timestamp_to_datetime($stamp));
+			$day = $datum['day'];
+			$month = $datum['month'];
+			$year = $datum['year'];
+		}
+		$fromdate = $year.'-'.$month.'-'.$day.' 00:00:00';
+		$stamp = Rsys :: mysql_datetime_to_timestamp($fromdate);
+		$dayofweek = date('w', $stamp);
+		if ($day - $dayofweek < 0) {
+			$stamp = $stamp - (60 * 60 * 24 * ($dayofweek -1));
+			$fromdate = Rsys :: timestamp_to_datetime($stamp);
+			$tilldate = $stamp;
+		} else {
+			$day = $day - $dayofweek +1; // M-FIX: sunday + 1 = monday
+			$fromdate = $year.'-'.$month.'-'. ($day < 10 ? '0'.$day : $day).' 00:00:00';
+			$tilldate = Rsys :: mysql_datetime_to_timestamp($fromdate);
+		}
+       //zeven Dagen opvullen en eind-datum bepalen (= startdatum + 7 dagen)
+		for ($i = 1; $i <= 7; $i ++) {
+			$day_start_dates[$i] = $tilldate;
+			$tilldate += 60 * 60 * 24;
+		}
+
+       // 5) Haal de reservaties periodes (+ reservaties) op tussen de start en einddatum
+		$arr = Rsys :: get_item_reservations($fromdate, Rsys :: timestamp_to_datetime($tilldate), $itemid);
+
+	// 6) Doorloop $arr met reservatie periodes en vul de $days array op met balkjes (bars) voor elke dag
+		$weekday_pointer = $GLOBALS['weekday_pointer'] = 1; // Stel de weekdag pointer in op 1 (=maandag)
+		$one_day = 60 * 60 * 24 - 1; // Het aantal seconden dat ��n dag in beslag neemt (23:59:59)
+		$last_end = $day_start_dates[1]; // Stel de $last_end pointer in op het begin van maandag (00:00:00)
+		if (count($arr['reservations'])>0) {
+			foreach ($arr['reservations'] as $res_id => $res) {
+				// 6.1) Stel basis variabelen in
+				$r = $res['info'];       // Reservatie periode informatie (start en eind tijd etc.)
+				$s = $res['subscriptions']; // Reservaties (inschrijvingen) op reservatie periode
+				$start = Rsys :: mysql_datetime_to_timestamp($r['start_at']); // Start tijd van reservatie periode blok
+				$end = Rsys :: mysql_datetime_to_timestamp($r['end_at']); // Eind tijd van reservatie periode blok
 		            	$timepicker_min = $r['timepicker_min'];
-				$timepicker_max = $r['timepicker_max'];
-				$chunk_size = $end - $start; // Unscaled chunk_size (of "reservation-period-block") // een "chunk" is dus een balkje (bar)
-
-				// 6.2) Als de weekdag van de huidige start-tijd (van de reservatieperiode) niet overeenkomt met de huidige weekdag-pointer (=$weekday_pointer)
-				if (date('w', $start) != $weekday_pointer) {
-			              	// a) Wijzig de $weekday_pointer naar de weekdag waarin de start-tijd (van de reservatieperiode) zich bevindt
-					$weekday_pointer = $GLOBALS['weekday_pointer'] = date('w', $start);
-					if ($weekday_pointer == 0)
-						$weekday_pointer = 7;
-	                		// b) Stel de $last_end in op het begin van de nieuwe dag
-					$last_end = $day_start_dates[$weekday_pointer];
-				}
-
-				// 6.3) Vul de ruimte tussen $last_end en de huidige start-tijd met een grijze balk
-				if ($start - $last_end > 0)
-					$days[$weekday_pointer] .= $this->get_bar(($start - $last_end) / $day_scale, 'grey');
-
-				// 6.4.A) Indien het NIET om een timepicker gaat... (= 1 reservatie-blok)
-			       	if ($r['timepicker'] != 1) {
-					// ..a1) bepaal kleur en link (of geen link) op basis van de inschrijvingsperiode en het aantal en het maximaal aantal inschrijvingen
-			              	if ($r['subscribers'] < $r['max_users'] && Rsys :: mysql_datetime_to_timestamp($r['start_at']) > time() && ($r['subscribe_from']=='0000-00-00 00:00:00'||(Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) < time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()))) {
-						// Subscription is allowed
-						$color = "green";
-						$link = "subscribe.php?rid=".$r['id'];
-					}
-					elseif ($r['subscribers'] < $r['max_users'] && (Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) > time() || Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) < time() || Rsys :: mysql_datetime_to_timestamp($r['start_at']) < time())) {
-						// Subscribe_from is not yet reached
-						$color = "orange";
-						$link = null;
-					}
-					else {
-						// Subscription is not allowed
-						$color = "red";
-						$link = null;
-					}
-
-	                // ..a2) stel titel in (dat je ziet als je over het balkje zweeft met je muis)
-	                $title = date('H:i (d/m/Y)', $start).' &raquo; '.date('H:i (d/m/Y)', $end);
-
-			        // ..a3) controleer of het reservatie-periode-blok de huidige dag overschrijdt
-					if ($end > $day_start_dates[$weekday_pointer] + $one_day) {
-						// indien ja, cree�r dan balkjes voor elke volgende dag
-						$trimmed_chunk_size = $chunk_size - ($end - ($day_start_dates[$weekday_pointer] + $one_day));
-						$days[$weekday_pointer] .= $this->get_bar($trimmed_chunk_size / $day_scale, $color, $link, $title, $itemid, $cat);
-						$new_day = true;
-						while ($new_day && $weekday_pointer < 7) {
-							$weekday_pointer ++;
-		                    $GLOBALS['weekday_pointer']++;
-							$start = $days[$weekday_pointer];
-							$chunk_size = $end - $start;
-							if ($end > $day_start_dates[$weekday_pointer] + $one_day) { // If still larger than one day, trim chunk and continue
-								$days[$weekday_pointer] .= $this->get_bar($one_day / $day_scale, $color, $link, $title, $itemid, $cat);
-							} else {
-								$trimmed_chunk_size = $end - $day_start_dates[$weekday_pointer];
-								$days[$weekday_pointer] .= $this->get_bar($trimmed_chunk_size / $day_scale, $color, $link, $title, $itemid, $cat);
-								$new_day = false;
-							}
-						}
+				$timepicker_max = $r['timepicker_max'];
+				$chunk_size = $end - $start; // Unscaled chunk_size (of "reservation-period-block") // een "chunk" is dus een balkje (bar)
+
+				// 6.2) Als de weekdag van de huidige start-tijd (van de reservatieperiode) niet overeenkomt met de huidige weekdag-pointer (=$weekday_pointer)
+				if (date('w', $start) != $weekday_pointer) {
+			              	// a) Wijzig de $weekday_pointer naar de weekdag waarin de start-tijd (van de reservatieperiode) zich bevindt
+					$weekday_pointer = $GLOBALS['weekday_pointer'] = date('w', $start);
+					if ($weekday_pointer == 0)
+						$weekday_pointer = 7;
+	                		// b) Stel de $last_end in op het begin van de nieuwe dag
+					$last_end = $day_start_dates[$weekday_pointer];
+				}
+
+				// 6.3) Vul de ruimte tussen $last_end en de huidige start-tijd met een grijze balk
+				if ($start - $last_end > 0)
+					$days[$weekday_pointer] .= $this->get_bar(($start - $last_end) / $day_scale, 'grey');
+
+				// 6.4.A) Indien het NIET om een timepicker gaat... (= 1 reservatie-blok)
+			       	if ($r['timepicker'] != 1) {
+					// ..a1) bepaal kleur en link (of geen link) op basis van de inschrijvingsperiode en het aantal en het maximaal aantal inschrijvingen
+			              	if ($r['subscribers'] < $r['max_users'] && Rsys :: mysql_datetime_to_timestamp($r['start_at']) > time() && ($r['subscribe_from']=='0000-00-00 00:00:00'||(Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) < time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()))) {
+						// Subscription is allowed
+						$color = "green";
+						$link = "subscribe.php?rid=".$r['id'];
 					}
-					else // indien niet, voeg dan gewoon het balkje toe aan de huidige dag
-						$days[$weekday_pointer] .= $this->get_bar($chunk_size / $day_scale, $color, $link, $title, $itemid, $cat);
-
-					// 6.4.B) Indien het WEL om een timepicker gaat... (max_users telt hier niet)
+					elseif ($r['subscribers'] < $r['max_users'] && (Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) > time() || Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) < time() || Rsys :: mysql_datetime_to_timestamp($r['start_at']) < time())) {
+						// Subscribe_from is not yet reached
+						$color = "orange";
+						$link = null;
+					}
+					else {
+						// Subscription is not allowed
+						$color = "red";
+						$link = null;
+					}
+
+	                // ..a2) stel titel in (dat je ziet als je over het balkje zweeft met je muis)
+	                $title = date('H:i (d/m/Y)', $start).' &raquo; '.date('H:i (d/m/Y)', $end);
+
+			        // ..a3) controleer of het reservatie-periode-blok de huidige dag overschrijdt
+					if ($end > $day_start_dates[$weekday_pointer] + $one_day) {
+						// indien ja, cree�r dan balkjes voor elke volgende dag
+						$trimmed_chunk_size = $chunk_size - ($end - ($day_start_dates[$weekday_pointer] + $one_day));
+						$days[$weekday_pointer] .= $this->get_bar($trimmed_chunk_size / $day_scale, $color, $link, $title, $itemid, $cat);
+						$new_day = true;
+						while ($new_day && $weekday_pointer < 7) {
+							$weekday_pointer ++;
+		                    $GLOBALS['weekday_pointer']++;
+							$start = $days[$weekday_pointer];
+							$chunk_size = $end - $start;
+							if ($end > $day_start_dates[$weekday_pointer] + $one_day) { // If still larger than one day, trim chunk and continue
+								$days[$weekday_pointer] .= $this->get_bar($one_day / $day_scale, $color, $link, $title, $itemid, $cat);
+							} else {
+								$trimmed_chunk_size = $end - $day_start_dates[$weekday_pointer];
+								$days[$weekday_pointer] .= $this->get_bar($trimmed_chunk_size / $day_scale, $color, $link, $title, $itemid, $cat);
+								$new_day = false;
+							}
+						}
+					}
+					else // indien niet, voeg dan gewoon het balkje toe aan de huidige dag
+						$days[$weekday_pointer] .= $this->get_bar($chunk_size / $day_scale, $color, $link, $title, $itemid, $cat);
+
+					// 6.4.B) Indien het WEL om een timepicker gaat... (max_users telt hier niet)
 				    }
 					else
-					{
-						$timepicker_min *= 60;
+					{
+						$timepicker_min *= 60;
 						$timepicker_max *= 60;
-						$minute_interval = 30;
-						$minute_interval *= 60;
-						$color = "blue";
-						$pickedcolor = "red";
-						$tosmallchunkcolor = "yellow";
-						$start_pointer = $start;
-
-						$link = "subscribe.php?rid=".$r['id'].'&amp;timestart='; // + (start)tijd waarop geklikt werd = volwaardige link
-
-		if(count($s)==0) {
-			if ($start > time())
-			{
-				//controle of dat de time tussen $r['subscribe_from'] en $r['subscribe_until'] ligt
-				if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00'))				{
-					$days[$weekday_pointer] .= $this->get_bar(($end - $start) / $day_scale, $color, $link.$start_pointer, date('H:i', $start).' &raquo; '.date('H:i', $end), $itemid, $cat);
-				}
-				else
-				{
+						$minute_interval = 30;
+						$minute_interval *= 60;
+						$color = "blue";
+						$pickedcolor = "red";
+						$tosmallchunkcolor = "yellow";
+						$start_pointer = $start;
+
+						$link = "subscribe.php?rid=".$r['id'].'&amp;timestart='; // + (start)tijd waarop geklikt werd = volwaardige link
+
+		if(count($s)==0) {
+			if ($start > time())
+			{
+				//controle of dat de time tussen $r['subscribe_from'] en $r['subscribe_until'] ligt
+				if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00'))				{
+					$days[$weekday_pointer] .= $this->get_bar(($end - $start) / $day_scale, $color, $link.$start_pointer, date('H:i', $start).' &raquo; '.date('H:i', $end), $itemid, $cat);
+				}
+				else
+				{
 					$days[$weekday_pointer] .= $this->get_bar(($end - $start) / $day_scale, 'orange', null, date('H:i', $start).' &raquo; '.date('H:i', $end));
-				}
-			}
-			else
-			{
-				if (time() < $end)
-				{
-					//eerst oranje daarna blauw of geel
-					$days[$weekday_pointer] .= $this->get_bar((time() - $start) / $day_scale, 'orange', null, date('H:i', $start).' &raquo; '.date('H:i', time()));
-					//controle of het stuk nog kan gereserveerd worden -> stuk > timepicker_min
-					if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00'))					{
-						if (($end - time()) >= $timepicker_min)
-						{
-							$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, $color, $link.$start_pointer, date('H:i', time()).' &raquo; '.date('H:i', $end), $itemid, $cat);
-						}
-						else
-						{
-							$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, $tosmallchunkcolor, null, date('H:i', time()).' &raquo; '.date('H:i', $end));
-						}
-					}
-					else
-					{
-						$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, 'orange', null, date('H:i', time()).' &raquo; '.date('H:i', $end));
-					}
-				}
-				else
-				{
-					//volledig oranje blok
-					$days[$weekday_pointer] .= $this->get_bar(($end - $start) / $day_scale, 'orange', null, date('H:i', $start).' &raquo; '.date('H:i', $end));
-				}
-			}
-		}
-		else
-		{
+				}
+			}
+			else
+			{
+				if (time() < $end)
+				{
+					//eerst oranje daarna blauw of geel
+					$days[$weekday_pointer] .= $this->get_bar((time() - $start) / $day_scale, 'orange', null, date('H:i', $start).' &raquo; '.date('H:i', time()));
+					//controle of het stuk nog kan gereserveerd worden -> stuk > timepicker_min
+					if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00'))					{
+						if (($end - time()) >= $timepicker_min)
+						{
+							$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, $color, $link.$start_pointer, date('H:i', time()).' &raquo; '.date('H:i', $end), $itemid, $cat);
+						}
+						else
+						{
+							$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, $tosmallchunkcolor, null, date('H:i', time()).' &raquo; '.date('H:i', $end));
+						}
+					}
+					else
+					{
+						$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, 'orange', null, date('H:i', time()).' &raquo; '.date('H:i', $end));
+					}
+				}
+				else
+				{
+					//volledig oranje blok
+					$days[$weekday_pointer] .= $this->get_bar(($end - $start) / $day_scale, 'orange', null, date('H:i', $start).' &raquo; '.date('H:i', $end));
+				}
+			}
+		}
+		else
+		{
 			$i = 0;
 			foreach ($s as $key => $sub) {
-				$start = Rsys :: mysql_datetime_to_timestamp($sub['start_at']);
-				$einde = Rsys :: mysql_datetime_to_timestamp($sub['end_at']);
+				$start = Rsys :: mysql_datetime_to_timestamp($sub['start_at']);
+				$einde = Rsys :: mysql_datetime_to_timestamp($sub['end_at']);
 
 				if (Rsys :: mysql_datetime_to_timestamp($sub['start_at']) - $start_pointer <= 0) {
-					//start onmiddelijk met een rood stuk
-					$start_tijd = date('H:i',$start_pointer);
-					$eind_tijd = date('H:i',$einde);
-					$days[$weekday_pointer] .= $this->get_bar(($einde - $start_pointer) / $day_scale, $pickedcolor, null, $start_tijd.' &raquo; '.$eind_tijd);
-				}
+					//start onmiddelijk met een rood stuk
+					$start_tijd = date('H:i',$start_pointer);
+					$eind_tijd = date('H:i',$einde);
+					$days[$weekday_pointer] .= $this->get_bar(($einde - $start_pointer) / $day_scale, $pickedcolor, null, $start_tijd.' &raquo; '.$eind_tijd);
+				}
 				else {
 					//start met een blauw of oranje stuk
 					//kijken of dat de start_tijd al buiten de huidige tijd ligt ->
 					if ($start_pointer > time()) {
-						$start_tijd = date('H:i',$start_pointer);
-						$eind_tijd = date('H:i',$start);
-						if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00')) {
-							//niet buiten tijd!
-							//blauw stuk maken indien groter dan timepicker_min anders geel
-							if (($start - $start_pointer) >= $timepicker_min) {
-								$days[$weekday_pointer] .= $this->get_bar(($start - $start_pointer) / $day_scale, $color, $link.$start_pointer, $start_tijd.' &raquo; '.$eind_tijd, $itemid, $cat);
-							}
-							else {
-								$days[$weekday_pointer] .= $this->get_bar(($start - $start_pointer) / $day_scale, $tosmallchunkcolor, null, $start_tijd.' &raquo; '.$eind_tijd);
-							}
-						}
-						else
-						{
-							$days[$weekday_pointer] .= $this->get_bar(($start - $start_pointer) / $day_scale, 'orange', null, $start_tijd.' &raquo; '.$eind_tijd);
+						$start_tijd = date('H:i',$start_pointer);
+						$eind_tijd = date('H:i',$start);
+						if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00')) {
+							//niet buiten tijd!
+							//blauw stuk maken indien groter dan timepicker_min anders geel
+							if (($start - $start_pointer) >= $timepicker_min) {
+								$days[$weekday_pointer] .= $this->get_bar(($start - $start_pointer) / $day_scale, $color, $link.$start_pointer, $start_tijd.' &raquo; '.$eind_tijd, $itemid, $cat);
+							}
+							else {
+								$days[$weekday_pointer] .= $this->get_bar(($start - $start_pointer) / $day_scale, $tosmallchunkcolor, null, $start_tijd.' &raquo; '.$eind_tijd);
+							}
+						}
+						else
+						{
+							$days[$weekday_pointer] .= $this->get_bar(($start - $start_pointer) / $day_scale, 'orange', null, $start_tijd.' &raquo; '.$eind_tijd);
+						}
+					}
+					else
+					{
+						//controleren of dat tijd nu groter is dan de start van het gereserveerde stuk
+						//Ja -> stuk voor de start oranje maken
+						//Neen -> stuk voor de start oranje maken en wat er nog overblijft vr de $start blauw maken
+						if (time() >= $start)
+						{
+							$days[$weekday_pointer] .= $this->get_bar(($start - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', $start));
+						}
+						else
+						{
+							//buiten tijd! -> stuk opdelen in een gedeelte buiten tijd en een gedeelte timepicker
+							//oranje stuk
+							$days[$weekday_pointer] .= $this->get_bar((time() - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', time()));
+							if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00'))							{
+								//blauw stuk maken indien groter dan timepicker_min anders geel
+								if (($start - time()) >= $timepicker_min)
+								{
+									$days[$weekday_pointer] .= $this->get_bar(($start - time()) / $day_scale, $color, $link.time(), date('H:i', time()).' &raquo; '.date('H:i', $start), $itemid, $cat);
+								}
+								else
+								{
+									$days[$weekday_pointer] .= $this->get_bar(($start - time()) / $day_scale, $tosmallchunkcolor, null, date('H:i', time()).' &raquo; '.date('H:i', $start), $itemid, $cat);
+								}
+							}
+							else
+							{
+								$days[$weekday_pointer] .= $this->get_bar(($start - time()) / $day_scale, 'orange', null, date('H:i', time()).' &raquo; '.date('H:i', $start));
+							}
 						}
-					}
-					else
-					{
-						//controleren of dat tijd nu groter is dan de start van het gereserveerde stuk
-						//Ja -> stuk voor de start oranje maken
-						//Neen -> stuk voor de start oranje maken en wat er nog overblijft vr de $start blauw maken
-						if (time() >= $start)
-						{
-							$days[$weekday_pointer] .= $this->get_bar(($start - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', $start));
-						}
-						else
-						{
-							//buiten tijd! -> stuk opdelen in een gedeelte buiten tijd en een gedeelte timepicker
-							//oranje stuk
-							$days[$weekday_pointer] .= $this->get_bar((time() - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', time()));
-							if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00'))							{
-								//blauw stuk maken indien groter dan timepicker_min anders geel
-								if (($start - time()) >= $timepicker_min)
-								{
-									$days[$weekday_pointer] .= $this->get_bar(($start - time()) / $day_scale, $color, $link.time(), date('H:i', time()).' &raquo; '.date('H:i', $start), $itemid, $cat);
-								}
-								else
-								{
-									$days[$weekday_pointer] .= $this->get_bar(($start - time()) / $day_scale, $tosmallchunkcolor, null, date('H:i', time()).' &raquo; '.date('H:i', $start), $itemid, $cat);
-								}
-							}
-							else
-							{
-								$days[$weekday_pointer] .= $this->get_bar(($start - time()) / $day_scale, 'orange', null, date('H:i', time()).' &raquo; '.date('H:i', $start));
-							}
-						}
-
-					}
-					$start_tijd = date('H:i',$start);
-					$eind_tijd = date('H:i',$einde);
-					$days[$weekday_pointer] .= $this->get_bar(($einde - $start) / $day_scale, $pickedcolor, null, $start_tijd.' &raquo; '.$eind_tijd);
-				}
-
-				//print_r($days);
-				$start_pointer = $einde;// + 1;
-			}
-			//indien er nog een stuk blauw moet gemaakt worden op het einde vd reservering
-			if ($start_pointer < $end)
-			{
-				//controleren of dat tijd nu groter is dan de start van het gereserveerde stuk
-				//Ja -> stuk voor de start oranje maken
-				//Neen -> stuk voor de start oranje maken en wat er nog overblijft vr de $start blauw maken
-				if (time() >= $end)
-				{
-					$days[$weekday_pointer] .= $this->get_bar(($end - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', $end));
-				}
-				else
-				{
-					if (time() >= $start_pointer)
-					{
-						//buiten tijd! -> stuk opdelen in een gedeelte buiten tijd en een gedeelte timepicker
-						//oranje stuk
-						$days[$weekday_pointer] .= $this->get_bar((time() - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', time()));
-						if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00'))						{
-							//blauw stuk maken indien groter dan timepicker_min anders geel
-							if (($end - time()) >= $timepicker_min)
-							{
-								//blauwe stuk
-								$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, $color, $link.time(), date('H:i', time()).' &raquo; '.date('H:i', $end), $itemid, $cat);
-							}
-							else
-							{
-								//geel stuk
-								$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, $tosmallchunkcolor, null, date('H:i', time()).' &raquo; '.date('H:i', $end));
-							}
-						}
-						else
-						{
-							$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, 'orange', null, date('H:i', time()).' &raquo; '.date('H:i', $end));
-						}
-					}
-					else
-					{
-						if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00')) {
-							//blauw stuk maken indien groter dan timepicker_min anders geel
-							if (($end - $start_pointer) >= $timepicker_min) {
-								//blauwe stuk
-								$days[$weekday_pointer] .= $this->get_bar(($end - $start_pointer) / $day_scale, $color, $link.$start_pointer, date('H:i', $start_pointer).' &raquo; '.date('H:i', $end), $itemid, $cat);
-							}
-							else {
-								//gele stuk
+
+					}
+					$start_tijd = date('H:i',$start);
+					$eind_tijd = date('H:i',$einde);
+					$days[$weekday_pointer] .= $this->get_bar(($einde - $start) / $day_scale, $pickedcolor, null, $start_tijd.' &raquo; '.$eind_tijd);
+				}
+
+				//print_r($days);
+				$start_pointer = $einde;// + 1;
+			}
+			//indien er nog een stuk blauw moet gemaakt worden op het einde vd reservering
+			if ($start_pointer < $end)
+			{
+				//controleren of dat tijd nu groter is dan de start van het gereserveerde stuk
+				//Ja -> stuk voor de start oranje maken
+				//Neen -> stuk voor de start oranje maken en wat er nog overblijft vr de $start blauw maken
+				if (time() >= $end)
+				{
+					$days[$weekday_pointer] .= $this->get_bar(($end - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', $end));
+				}
+				else
+				{
+					if (time() >= $start_pointer)
+					{
+						//buiten tijd! -> stuk opdelen in een gedeelte buiten tijd en een gedeelte timepicker
+						//oranje stuk
+						$days[$weekday_pointer] .= $this->get_bar((time() - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', time()));
+						if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00'))						{
+							//blauw stuk maken indien groter dan timepicker_min anders geel
+							if (($end - time()) >= $timepicker_min)
+							{
+								//blauwe stuk
+								$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, $color, $link.time(), date('H:i', time()).' &raquo; '.date('H:i', $end), $itemid, $cat);
+							}
+							else
+							{
+								//geel stuk
+								$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, $tosmallchunkcolor, null, date('H:i', time()).' &raquo; '.date('H:i', $end));
+							}
+						}
+						else
+						{
+							$days[$weekday_pointer] .= $this->get_bar(($end - time()) / $day_scale, 'orange', null, date('H:i', time()).' &raquo; '.date('H:i', $end));
+						}
+					}
+					else
+					{
+						if((Rsys :: mysql_datetime_to_timestamp($r['subscribe_from']) <= time() && Rsys :: mysql_datetime_to_timestamp($r['subscribe_until']) > time()) || ($r['subscribe_from'] == '0000-00-00 00:00:00' && $r['subscribe_until'] == '0000-00-00 00:00:00')) {
+							//blauw stuk maken indien groter dan timepicker_min anders geel
+							if (($end - $start_pointer) >= $timepicker_min) {
+								//blauwe stuk
+								$days[$weekday_pointer] .= $this->get_bar(($end - $start_pointer) / $day_scale, $color, $link.$start_pointer, date('H:i', $start_pointer).' &raquo; '.date('H:i', $end), $itemid, $cat);
+							}
+							else {
+								//gele stuk
 								$days[$weekday_pointer] .= $this->get_bar(($end - $start_pointer) / $day_scale, $tosmallchunkcolor, null, date('H:i', $start_pointer).' &raquo; '.date('H:i', $end));
-							}
-						}
-						else {
+							}
+						}
+						else {
 							$days[$weekday_pointer] .= $this->get_bar(($end - $start_pointer) / $day_scale, 'orange', null, date('H:i', $start_pointer).' &raquo; '.date('H:i', $end));
-						}
-					}
-				}
-			}
+						}
+					}
+				}
+			}
+		}
+	}
+
+
+			// 6.5) Zet de $last_end pointer op de eindtijd van de huidige reservatie periode
+			$last_end = $end;
+			}// end if
+		}
+
+		// 7) loop through all days of the week and fill them with the contents of $days
+		$firstcol = 120; // Width of first col (in pixels)
+		$x=0;
+        	$borderstyle = "border-bottom: 1px solid #003;";
+        	echo '<table cellspacing="0" style="padding: 1px;width: '. (round($one_day / $day_scale) + $firstcol + $x).'px;border: 1px solid #003;border-bottom: 0"><tr><td style="'.$borderstyle.'width: '.$firstcol.'px;background-color: #069; ">&nbsp;</td><td style="'.$borderstyle.'background-color: #069; color: #FFF; white-space: nowrap; font-family: Arial, sans-serif; font-size:10px;width: '. (round($one_day / $day_scale) + $x).'px">';
+		$vast = (3600 * 2) / $day_scale;
+	       $lasttotal=0;
+		for ($i = 0; $i < 22; $i = $i +2) {
+            		$w=$vast;
+            		$total+=$w;
+            		$rounded_total=round($total);
+            		$w=$rounded_total-$lasttotal;
+			echo '<div style="float:left; width: '. $w .'px">'.$i.'</div>';
+            		$lasttotal=$rounded_total;
+		}
+		echo '<div style="float:left;">22</div><div style="float: right">0</float>';
+		echo '</td></tr>';
+		for ($i = 1; $i <= 7; $i ++) {
+			echo '<tr><td style="background-color: #069; color: #FFF; width:'.$firstcol.'px; font-family: Verdana, Arial, sans-serif; font-weight: bold;font-size:10px;'.$borderstyle.';cursor: help" title="'.date('d/m/Y',$day_start_dates[$i]).'">'.$this->get_long_day($i == 7 ? 0 : $i).'</td><td style="'.$borderstyle.' background-color: #CCC; width:'. (round($one_day / $day_scale) + $x).'px; white-space: nowrap;">';
+			if (is_array($days) && array_key_exists($i, $days))
+				echo $days[$i];
+			else
+				echo '&nbsp;';
+			echo '</td></tr>'."\n";
 		}
+		echo '</table>';
+        	$GLOBALS['weekstart']=date('d/m/Y',$day_start_dates[1]);
+        	$GLOBALS['weekend']=date('d/m/Y',$day_start_dates[7]);
 	}
-
-
-			// 6.5) Zet de $last_end pointer op de eindtijd van de huidige reservatie periode
-			$last_end = $end;
-			}// end if
-		}
-
-		// 7) loop through all days of the week and fill them with the contents of $days
-		$firstcol = 120; // Width of first col (in pixels)
-		$x=0;
-        	$borderstyle = "border-bottom: 1px solid #003;";
-        	echo '<table cellspacing="0" style="padding: 1px;width: '. (round($one_day / $day_scale) + $firstcol + $x).'px;border: 1px solid #003;border-bottom: 0"><tr><td style="'.$borderstyle.'width: '.$firstcol.'px;background-color: #069; ">&nbsp;</td><td style="'.$borderstyle.'background-color: #069; color: #FFF; white-space: nowrap; font-family: Arial, sans-serif; font-size:10px;width: '. (round($one_day / $day_scale) + $x).'px">';
-		$vast = (3600 * 2) / $day_scale;
-	       $lasttotal=0;
-		for ($i = 0; $i < 22; $i = $i +2) {
-            		$w=$vast;
-            		$total+=$w;
-            		$rounded_total=round($total);
-            		$w=$rounded_total-$lasttotal;
-			echo '<div style="float:left; width: '. $w .'px">'.$i.'</div>';
-            		$lasttotal=$rounded_total;
-		}
-		echo '<div style="float:left;">22</div><div style="float: right">0</float>';
-		echo '</td></tr>';
-		for ($i = 1; $i <= 7; $i ++) {
-			echo '<tr><td style="background-color: #069; color: #FFF; width:'.$firstcol.'px; font-family: Verdana, Arial, sans-serif; font-weight: bold;font-size:10px;'.$borderstyle.';cursor: help" title="'.date('d/m/Y',$day_start_dates[$i]).'">'.$this->get_long_day($i == 7 ? 0 : $i).'</td><td style="'.$borderstyle.' background-color: #CCC; width:'. (round($one_day / $day_scale) + $x).'px; white-space: nowrap;">';
-			if (is_array($days) && array_key_exists($i, $days))
-				echo $days[$i];
-			else
-				echo '&nbsp;';
-			echo '</td></tr>'."\n";
-		}
-		echo '</table>';
-        	$GLOBALS['weekstart']=date('d/m/Y',$day_start_dates[1]);
-        	$GLOBALS['weekend']=date('d/m/Y',$day_start_dates[7]);
-	}
-}
-?>
+}
+?>

+ 134 - 134
main/reservation/reservation.php

@@ -1,144 +1,144 @@
-<?php // $Id: reservation.php,v 1.34 2006/05/10 12:30:38 sjacobs Exp $
-/*
-==============================================================================
-    Dokeos - elearning and course management software
-
-    Copyright (c) 2004-2008 Dokeos SPRL
-    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
-    Copyright (c) Kristof Van Steenkiste
-    Copyright (c) Julio Montoya Armas
-
-    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
-==============================================================================
-*/
-/**
-    ---------------------------------------------------------------------
-                Reservation-manager (add, edit & delete)
-    ---------------------------------------------------------------------
- */
-require_once('rsys.php');
-
-Rsys :: protect_script('reservation');
-$tool_name = get_lang('Booking');
-
-///$interbreadcrumb[] = array ("url" => 'reservation.php', "name" => get_lang('Booking'));
-
-
-Display :: display_header($tool_name);
-api_display_tool_title($tool_name);
-
-
-if (isset($_GET['cat'])) {
-	$category_id = Security::remove_XSS($_GET['cat']);
-}
-
-
-
-echo '<div class="actions">';
-///		echo '<a href="m_reservation.php?action=add"><img src="../img/view_more_stats.gif" border="0" alt="" title="'.get_lang('AddNewBookingPeriod').'"/>'.get_lang('AddNewBookingPeriod').'</a>';
-//echo '&nbsp;&nbsp;&nbsp;<a href="m_reservation.php?action=overviewsubscriptions">'.get_lang('OverviewReservedPeriods').'</a>';
-echo '<div style="float: right;"><a href="mysubscriptions.php">'.Display::return_icon('file_txt.gif',get_lang('BookingListView'),array('width'=>'22')).'&nbsp;'.get_lang('GoToListView').'</a></div>';
+<?php // $Id: reservation.php,v 1.34 2006/05/10 12:30:38 sjacobs Exp $
+/*
+==============================================================================
+    Dokeos - elearning and course management software
+
+    Copyright (c) 2004-2008 Dokeos SPRL
+    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
+    Copyright (c) Kristof Van Steenkiste
+    Copyright (c) Julio Montoya Armas
+
+    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
+==============================================================================
+*/
+/**
+    ---------------------------------------------------------------------
+                Reservation-manager (add, edit & delete)
+    ---------------------------------------------------------------------
+ */
+require_once('rsys.php');
+
+Rsys :: protect_script('reservation');
+$tool_name = get_lang('Booking');
+
+///$interbreadcrumb[] = array ("url" => 'reservation.php', "name" => get_lang('Booking'));
+
+
+Display :: display_header($tool_name);
+api_display_tool_title($tool_name);
+
+
+if (isset($_GET['cat'])) {
+	$category_id = Security::remove_XSS($_GET['cat']);
+}
+
+
+
+echo '<div class="actions">';
+///		echo '<a href="m_reservation.php?action=add"><img src="../img/view_more_stats.gif" border="0" alt="" title="'.get_lang('AddNewBookingPeriod').'"/>'.get_lang('AddNewBookingPeriod').'</a>';
+//echo '&nbsp;&nbsp;&nbsp;<a href="m_reservation.php?action=overviewsubscriptions">'.get_lang('OverviewReservedPeriods').'</a>';
+echo '<div style="float: right;"><a href="mysubscriptions.php">'.Display::return_icon('file_txt.gif',get_lang('BookingListView'),array('width'=>'22')).'&nbsp;'.get_lang('GoToListView').'</a></div>';
 echo '<a href="m_item.php?view=calendar">'.Display::return_icon('cube.png',get_lang('Resources')).'&nbsp;'.get_lang('Resources').'</a>';
-echo '&nbsp;&nbsp;<a href="m_reservation.php?view=calendar">'.Display::return_icon('calendar_day.gif',get_lang('BookingPeriods')).'&nbsp;'.get_lang('BookingPeriods').'</a>';
-echo '&nbsp;&nbsp;<a href="m_reservation.php?action=add&view=calendar">'.Display::return_icon('calendar_add.gif',get_lang('BookIt')).'&nbsp;'.get_lang('BookIt').'</a>';
+echo '&nbsp;&nbsp;<a href="m_reservation.php?view=calendar">'.Display::return_icon('calendar_day.gif',get_lang('BookingPeriods')).'&nbsp;'.get_lang('BookingPeriods').'</a>';
+echo '&nbsp;&nbsp;<a href="m_reservation.php?action=add&view=calendar">'.Display::return_icon('calendar_add.gif',get_lang('BookIt')).'&nbsp;'.get_lang('BookIt').'</a>';
 
 if (api_is_platform_admin())
-{
-	//echo '&nbsp;&nbsp;<a href="m_category.php">'.Display::return_icon('settings.gif',get_lang('Configuration')).'&nbsp;'.get_lang('Configuration').'</a>';
-}
-
-echo '</div><br />';
-
-function getBlock($color) {
-	return '<img src="../img/px_'.$color.'.gif" alt="" style="border:1px solid #000;height: 10px;width: 10px;vertical-align:top;margin-left:10px" />';
+{
+	//echo '&nbsp;&nbsp;<a href="m_category.php">'.Display::return_icon('settings.gif',get_lang('Configuration')).'&nbsp;'.get_lang('Configuration').'</a>';
 }
 
-$gogogo=false;
-// Get resolution of user
-if((empty($_SESSION['swidth'])||empty($_SESSION['sheight']))&&(empty($_GET['swidth'])||empty($_GET['sheight']))) {
-?>
-<script type="text/javascript">
-window.location.href='reservation.php?sheight='+screen. height+'&swidth='+screen.width;
-</script>
+echo '</div><br />';
+
+function getBlock($color) {
+	return '<img src="../img/px_'.$color.'.gif" alt="" style="border:1px solid #000;height: 10px;width: 10px;vertical-align:top;margin-left:10px" />';
+}
+
+$gogogo=false;
+// Get resolution of user
+if((empty($_SESSION['swidth'])||empty($_SESSION['sheight']))&&(empty($_GET['swidth'])||empty($_GET['sheight']))) {
+?>
+<script type="text/javascript">
+window.location.href='reservation.php?sheight='+screen. height+'&swidth='+screen.width;
+</script>
 <?php
-}
-elseif((empty($_SESSION['swidth']))) {
-    $_SESSION['swidth']=$_GET['swidth'];
-    $_SESSION['sheight']=$_GET['sheight'];
+}
+elseif((empty($_SESSION['swidth']))) {
+    $_SESSION['swidth']=$_GET['swidth'];
+    $_SESSION['sheight']=$_GET['sheight'];
     $gogogo=true;
-}
+}
 else
-	$gogogo=true;
-
-echo '<div style="float: left;"><form id="cat_form" action="reservation.php" method="get"><input type="hidden" name="cat" value="'.$category_id.'" /><div style="float: left;">'.get_lang('ResourceType').': <select name="cat" onchange="this.form.submit();"><option value="0">'.get_lang('Select').'</option>';
-$cats = Rsys :: get_category_with_items();
-
-if(count($cats)>0){
-    foreach ($cats as $cat)
-	   echo '<option value="'.$cat['id'].'"'. ($cat['id'] == $category_id ? ' selected="selected"' : '').'>'.$cat['name'].'</option>';
-}
-
-echo '</select></div></form></div>';
-
-if ($gogogo&&!empty($category_id)) {
-	$itemlist = Rsys :: get_cat_items($category_id);
-    echo '<div style="float: left;">';
-	if (count($itemlist) != 0) {
-	echo '<form id="item_form" action="reservation.php?cat='.$category_id.'&amp;item=" method="get">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="hidden" name="cat" value="'.$category_id.'" />'.get_lang('Resource').': <select name="item" onchange="this.form.submit();"><option value="0">'.get_lang('Select').'</option>';
-		foreach ($itemlist as $id => $item)
-			echo '<option value="'.$id.'"'. ($id == $_GET['item'] ? ' selected="selected"' : '').'>'.$item.'</option>';
-		echo '</select></form>';
-	}else{
+	$gogogo=true;
+
+echo '<div style="float: left;"><form id="cat_form" action="reservation.php" method="get"><input type="hidden" name="cat" value="'.$category_id.'" /><div style="float: left;">'.get_lang('ResourceType').': <select name="cat" onchange="this.form.submit();"><option value="0">'.get_lang('Select').'</option>';
+$cats = Rsys :: get_category_with_items();
+
+if(count($cats)>0){
+    foreach ($cats as $cat)
+	   echo '<option value="'.$cat['id'].'"'. ($cat['id'] == $category_id ? ' selected="selected"' : '').'>'.$cat['name'].'</option>';
+}
+
+echo '</select></div></form></div>';
+
+if ($gogogo&&!empty($category_id)) {
+	$itemlist = Rsys :: get_cat_items($category_id);
+    echo '<div style="float: left;">';
+	if (count($itemlist) != 0) {
+	echo '<form id="item_form" action="reservation.php?cat='.$category_id.'&amp;item=" method="get">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="hidden" name="cat" value="'.$category_id.'" />'.get_lang('Resource').': <select name="item" onchange="this.form.submit();"><option value="0">'.get_lang('Select').'</option>';
+		foreach ($itemlist as $id => $item)
+			echo '<option value="'.$id.'"'. ($id == $_GET['item'] ? ' selected="selected"' : '').'>'.$item.'</option>';
+		echo '</select></form>';
+	}else{
 		echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.get_lang('NoItemsReservation');
-	}
-    echo '</div>';
-	if(!empty($_GET['item'])) {
-		$calendar = new rCalendar();
-		$time=Rsys::mysql_datetime_to_array($_GET['date'].' 00:00:00');
-		ob_start();
-        echo '<div style="float: left; margin-right: 10px">';
-		if(isset($_GET['changemonth'])) {
-			echo $calendar->get_mini_month(intval($time['month']),intval($time['year']),"&amp;cat=".$category_id."&amp;item=".$_GET['item']."&amp;changemonth=yes",$_GET['item']);
-		}
-		else
-			echo $calendar->get_mini_month(date('m'),date('Y'),"&amp;cat=".$category_id."&amp;item=".$_GET['item'],$_GET['item']);
-        echo '</div><div style="float: left" >';
-
-        switch($_SESSION['swidth']) {
-            case '640': $week_scale= 170;break;
-            case '1024': $week_scale=130;break;
-            case '1152': $week_scale=110;break;
-            case '1280': $week_scale=94;break;
-            case '1600': $week_scale=70;break;
-            case '1792': $week_scale=60;break;
-            case '1800': $week_scale=50;break;
-            case '1920': $week_scale=40;break;
-            case '2048': $week_scale=30;break;
+	}
+    echo '</div>';
+	if(!empty($_GET['item'])) {
+		$calendar = new rCalendar();
+		$time=Rsys::mysql_datetime_to_array($_GET['date'].' 00:00:00');
+		ob_start();
+        echo '<div style="float: left; margin-right: 10px">';
+		if(isset($_GET['changemonth'])) {
+			echo $calendar->get_mini_month(intval($time['month']),intval($time['year']),"&amp;cat=".$category_id."&amp;item=".$_GET['item']."&amp;changemonth=yes",$_GET['item']);
+		}
+		else
+			echo $calendar->get_mini_month(date('m'),date('Y'),"&amp;cat=".$category_id."&amp;item=".$_GET['item'],$_GET['item']);
+        echo '</div><div style="float: left" >';
+
+        switch($_SESSION['swidth']) {
+            case '640': $week_scale= 170;break;
+            case '1024': $week_scale=130;break;
+            case '1152': $week_scale=110;break;
+            case '1280': $week_scale=94;break;
+            case '1600': $week_scale=70;break;
+            case '1792': $week_scale=60;break;
+            case '1800': $week_scale=50;break;
+            case '1920': $week_scale=40;break;
+            case '2048': $week_scale=30;break;
             default: $week_scale= 150; // 800x600
-        }
-		if(isset($_GET['date'])){
-			echo $calendar->get_week_view(intval($time['day']),intval($time['month']), $time['year'],$_GET['item'], $week_scale,$category_id);
-		}else
-			echo $calendar->get_week_view(intval(date('d')), intval(date('m')), intval(date('Y')), $_GET['item'], $week_scale,$category_id);
-		echo '</div>';
-       $buffer=ob_get_contents();
-       ob_end_clean();
-
-
-       $legend=getBlock('green').' '.api_ucfirst(get_lang('OpenBooking')).' '.getBlock('blue').' '.get_lang('TimePicker').' '.getBlock('orange').' '.get_lang('OutPeriod').' '.getBlock('red').' '.get_lang('Reserved').' '.getBlock('grey').' '.get_lang('NoReservations').' '.getBlock('black').' '.get_lang('Blackout');
-       echo '<br /><br /><div style="text-align:right; border-bottom: 2px dotted #666; margin: 0 0 0.2em 0; padding: 0.2em;clear:both;font-family: Verdana,sans-serif;font-size: 1.2em;color:#666;font-weight:bold">'.$GLOBALS['weekstart'].' - '.$GLOBALS['weekend'].'</div>'.$buffer.'<div style="clear:both;">&nbsp;</div><div style="background-color:#EEE;padding: 0.5em;font-family:Verdana;sans-serif;font-size:10px;text-align:center">'.$legend.'</div>';
-	}
-}
-Display :: display_footer();
-?>
+        }
+		if(isset($_GET['date'])){
+			echo $calendar->get_week_view(intval($time['day']),intval($time['month']), $time['year'],$_GET['item'], $week_scale,$category_id);
+		}else
+			echo $calendar->get_week_view(intval(date('d')), intval(date('m')), intval(date('Y')), $_GET['item'], $week_scale,$category_id);
+		echo '</div>';
+       $buffer=ob_get_contents();
+       ob_end_clean();
+
+
+       $legend=getBlock('green').' '.api_ucfirst(get_lang('OpenBooking')).' '.getBlock('blue').' '.get_lang('TimePicker').' '.getBlock('orange').' '.get_lang('OutPeriod').' '.getBlock('red').' '.get_lang('Reserved').' '.getBlock('grey').' '.get_lang('NoReservations').' '.getBlock('black').' '.get_lang('Blackout');
+       echo '<br /><br /><div style="text-align:right; border-bottom: 2px dotted #666; margin: 0 0 0.2em 0; padding: 0.2em;clear:both;font-family: Verdana,sans-serif;font-size: 1.2em;color:#666;font-weight:bold">'.$GLOBALS['weekstart'].' - '.$GLOBALS['weekend'].'</div>'.$buffer.'<div style="clear:both;">&nbsp;</div><div style="background-color:#EEE;padding: 0.5em;font-family:Verdana;sans-serif;font-size:10px;text-align:center">'.$legend.'</div>';
+	}
+}
+Display :: display_footer();
+?>

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 1081 - 1081
main/reservation/rsys.php


+ 173 - 173
main/reservation/subscribe.php

@@ -1,179 +1,179 @@
-<?php
-// $Id: subscribe.php,v 1.9 2006/05/11 14:36:10 kvansteenkiste Exp $
-/*
-==============================================================================
-    Dokeos - elearning and course management software
-
-    Copyright (c) 2004-2008 Dokeos SPRL
-    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
+<?php
+// $Id: subscribe.php,v 1.9 2006/05/11 14:36:10 kvansteenkiste Exp $
+/*
+==============================================================================
+    Dokeos - elearning and course management software
+
+    Copyright (c) 2004-2008 Dokeos SPRL
+    Copyright (c) Sebastien Jacobs (www.spiritual-coder.com)
     Copyright (c) Kristof Van Steenkiste
     Copyright (c) Julio Montoya Armas
-
-    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
-==============================================================================
-*/
-/**
-    ---------------------------------------------------------------------
-                Reservation-manager (add, edit & delete)
-    ---------------------------------------------------------------------
- */
-
-require_once('rsys.php');
-Rsys :: protect_script('reservation');
-
-
-if (!empty($_GET['cat']) && !empty($_GET['item'] )) {
-	$cat = (int)$_GET['cat'];
-	$item = (int)$_GET['item'];
-	$interbreadcrumb[] = array ('url' => "reservation.php?cat=$cat&item=$item", 'name' => get_lang('Booking'));
-} else {
+
+    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
+==============================================================================
+*/
+/**
+    ---------------------------------------------------------------------
+                Reservation-manager (add, edit & delete)
+    ---------------------------------------------------------------------
+ */
+
+require_once('rsys.php');
+Rsys :: protect_script('reservation');
+
+
+if (!empty($_GET['cat']) && !empty($_GET['item'] )) {
+	$cat = (int)$_GET['cat'];
+	$item = (int)$_GET['item'];
+	$interbreadcrumb[] = array ('url' => "reservation.php?cat=$cat&item=$item", 'name' => get_lang('Booking'));
+} else {
 	$interbreadcrumb[] = array ('url' => 'reservation.php', 'name' => get_lang('Booking'));
-}
-
-
-$tool_name = get_lang('BookIt');
-Display :: display_header($tool_name);
-api_display_tool_title($tool_name);
-
-$reservationid = Database::escape_string($_GET['rid']);
-$reservation = Rsys :: get_reservation($reservationid);
-$item = Rsys :: get_item($reservation[0][2]);
-if ($reservation[0][9] < $reservation[0][4]) {
+}
+
+
+$tool_name = get_lang('BookIt');
+Display :: display_header($tool_name);
+api_display_tool_title($tool_name);
+
+$reservationid = Database::escape_string($_GET['rid']);
+$reservation = Rsys :: get_reservation($reservationid);
+$item = Rsys :: get_item($reservation[0][2]);
+if ($reservation[0][9] < $reservation[0][4]) {
 	ob_start();
-	$form = new FormValidator('reservation', 'post', 'subscribe.php?rid='.Security::remove_XSS($_GET['rid']));
-	$form->addElement('hidden', 'timepicker', $reservation[0][11]);
-	$form->addElement('hidden', 'accepted', $reservation[0][3]);
-	if ($reservation[0][11] == 1) {
-		//$subscribe_timepicker_information="Gelieve voor #name# een peroide te kiezen #from_till tussen :#start_end";
-		$min_timepicker = $reservation[0][12];
-		$max_timepicker = $reservation[0][13];
-		$min_timepicker_min = fmod($min_timepicker,60);
-		$min_timepicker_hour = floor($min_timepicker/60);
-		$max_timepicker_min = fmod($max_timepicker,60);
-		$max_timepicker_hour = floor($max_timepicker/60);
-		$min_timepicker_show = $min_timepicker_hour."h".$min_timepicker_min."m";
-		$max_timepicker_show = $max_timepicker_hour."h".$max_timepicker_min."m";
-
-		if (!($min_timepicker == 0 && $max_timepicker == 0)) {
-			if($min_timepicker_show == $max_timepicker_show) {
-				$from_till = "van ".$min_timepicker_show;
-			} else {
-				$from_till = "van ".$min_timepicker_show." tot ".$max_timepicker_show;
-			}
-		} else {
-			$from_till = "";
-			$min_timepicker = 1;
-			//een reservatieperiode moet toch wel minimum 1 minuut zijn
-		}
-
-		$res_start_at = $reservation[0][5];
-		$res_end_at = $reservation[0][6];
-		//echo time()."-".$res_start_at;
-		if (time() > Rsys :: mysql_datetime_to_timestamp($res_start_at)) {
-			$time_start = time();
-		} else {
-			$time_start = Rsys :: mysql_datetime_to_timestamp($res_start_at);
-		}
-
-		$sql = "SELECT start_at, end_at FROM ".Rsys :: getTable('subscription')."
-				WHERE reservation_id='".$reservationid."' and end_at > NOW() ORDER BY start_at";
-		$result = Database::query($sql, __FILE__, __LINE__);
-		if (Database::num_rows($result) != 0){
-			$start_end = "<ul>";
-			while ($array = Database::fetch_array($result)) {
-				//print_r($array);
-				if (time() < Rsys :: mysql_datetime_to_timestamp($array["start_at"]))
+	$form = new FormValidator('reservation', 'post', 'subscribe.php?rid='.Security::remove_XSS($_GET['rid']));
+	$form->addElement('hidden', 'timepicker', $reservation[0][11]);
+	$form->addElement('hidden', 'accepted', $reservation[0][3]);
+	if ($reservation[0][11] == 1) {
+		//$subscribe_timepicker_information="Gelieve voor #name# een peroide te kiezen #from_till tussen :#start_end";
+		$min_timepicker = $reservation[0][12];
+		$max_timepicker = $reservation[0][13];
+		$min_timepicker_min = fmod($min_timepicker,60);
+		$min_timepicker_hour = floor($min_timepicker/60);
+		$max_timepicker_min = fmod($max_timepicker,60);
+		$max_timepicker_hour = floor($max_timepicker/60);
+		$min_timepicker_show = $min_timepicker_hour."h".$min_timepicker_min."m";
+		$max_timepicker_show = $max_timepicker_hour."h".$max_timepicker_min."m";
+
+		if (!($min_timepicker == 0 && $max_timepicker == 0)) {
+			if($min_timepicker_show == $max_timepicker_show) {
+				$from_till = "van ".$min_timepicker_show;
+			} else {
+				$from_till = "van ".$min_timepicker_show." tot ".$max_timepicker_show;
+			}
+		} else {
+			$from_till = "";
+			$min_timepicker = 1;
+			//een reservatieperiode moet toch wel minimum 1 minuut zijn
+		}
+
+		$res_start_at = $reservation[0][5];
+		$res_end_at = $reservation[0][6];
+		//echo time()."-".$res_start_at;
+		if (time() > Rsys :: mysql_datetime_to_timestamp($res_start_at)) {
+			$time_start = time();
+		} else {
+			$time_start = Rsys :: mysql_datetime_to_timestamp($res_start_at);
+		}
+
+		$sql = "SELECT start_at, end_at FROM ".Rsys :: getTable('subscription')."
+				WHERE reservation_id='".$reservationid."' and end_at > NOW() ORDER BY start_at";
+		$result = Database::query($sql, __FILE__, __LINE__);
+		if (Database::num_rows($result) != 0){
+			$start_end = "<ul>";
+			while ($array = Database::fetch_array($result)) {
+				//print_r($array);
+				if (time() < Rsys :: mysql_datetime_to_timestamp($array["start_at"]))
 				{
-					if (((Rsys :: mysql_datetime_to_timestamp($array["start_at"]) - $time_start) >= ($min_timepicker*60)) && ($time_start < Rsys :: mysql_datetime_to_timestamp($array["start_at"])))
-					{
-						$start_end .= "<li>".Rsys :: timestamp_to_datetime($time_start)." en ".$array["start_at"]."</li>";
-					}
-				}
-				$time_start = Rsys :: mysql_datetime_to_timestamp($array["end_at"]);
-				$end_time_last_block = $array["end_at"];
-			}
-			if ((Rsys :: mysql_datetime_to_timestamp($res_end_at) - Rsys :: mysql_datetime_to_timestamp($end_time_last_block)) >= ($min_timepicker*60))
-			{
-				$start_end .= "<li>".$end_time_last_block." en ".$res_end_at."</li>";
-			}
-			$start_end .= "</ul>";
-		} else {
-			$start_end = " ".Rsys :: timestamp_to_datetime($time_start)." en ".$res_end_at;
-		}
-
-		//$form->addElement('html', "timestart:".$time_start."-".Rsys :: mysql_datetime_to_timestamp($res_start_at));
-		$form->addElement('html', "<p>".str_replace('#start_end',$start_end,str_replace('#from_till', $from_till,str_replace('#name#', "<b>".$item[3]."</b>",str_replace('#start#', "<b>".$reservation[0][5]."</b>", str_replace('#end#', "<b>".$reservation[0][6]."</b>", get_lang("SubscribeTimePickerInformation"))))))." </p>");
-		$form->add_timewindow('startpicker', 'endpicker', get_lang('StartDate'), get_lang('EndDate'));
-		$form->addElement('hidden', 'min', $reservation[0][12]);
-		$form->addElement('hidden', 'max', $reservation[0][13]);
-		$datum = $_GET['timestart'];
-		$defaultvalues['startpicker'] = Rsys :: timestamp_to_datetime($datum);
-		//$defaultvalues['endpicker'] = Rsys :: timestamp_to_datetime($datum +900);
-		$defaultvalues['endpicker'] = Rsys :: timestamp_to_datetime($datum +($min_timepicker*60));
-		$form->setDefaults($defaultvalues);
-	} else {
-		$form->addElement('html', "<p> * ".str_replace('#name#', "<b>".$item[3]."</b>",str_replace('#start#', "<b>".$reservation[0][5]."</b>", str_replace('#end#', "<b>".$reservation[0][6]."</b>", get_lang('SubscribeInformation'))))." *</p>");
-	}
-	$buttons[] = $form->createElement('submit', 'submit', get_lang('Ok'));
-	$buttons[] = $form->createElement('button', 'cancel', get_lang('Cancel'), array ('onclick' => 'location.href="reservation.php?cat='.$item[1].'&item='.$item[0].'"'));
-	$form->addGroup($buttons, null, '', '', false);
-
-	$buffer = ob_get_contents();
-	ob_end_clean();
-
-	if ($form->validate()) {
-		$values = $form->exportValues();
-		if ($values['timepicker'] == 0) {
-			$result = Rsys :: add_subscription($_GET['rid'], api_get_user_id(),$values['accepted']);
-			switch ($result) {
-				case 0 :
-					Display :: display_normal_message(Rsys :: get_return_msg2(get_lang('ReservationAdded'), "javascript:history.go(-2)", get_lang('BookingView')),false);
-					break;
-				case 1 :
-					Display :: display_normal_message(Rsys :: get_return_msg2(str_replace('#END#', "<b>".$GLOBALS['end_date']."</b>",str_replace('#START#', "<b>".$GLOBALS['start_date']."</b>",get_lang('ReservationAlready'))),"reservation.php?cat=".$item[1]."&item=".$item[0]."", get_lang('BookingView')),false);
-					break;
-			}
-
-		} else {
-			$result = Rsys :: add_subscription_timepicker($_GET['rid'], api_get_user_id(), $values['startpicker'], $values['endpicker'],$values['accepted'],$values['min'],$values['max']);
-			switch ($result) {
-				case 0 :
-					Display :: display_normal_message(Rsys :: get_return_msg2(get_lang('ReservationAdded'), "reservation.php?cat=".$item[1]."&item=".$item[0]."&date=".date( 'Y-m-d',Rsys :: mysql_datetime_to_timestamp($values['startpicker']))."&changemonth=yes", get_lang('BookingView')),false);
-					break;
-				case 1 :
-					Display :: display_normal_message(str_replace('#END#', "<b>".$GLOBALS['end_date']."</b>",str_replace('#START#', "<b>".$GLOBALS['start_date']."</b>",get_lang('ReservationOutOfDate'))),false);
-					$form->display();
-					echo $buffer;
-					break;
-				case 2 :
-					Display :: display_normal_message(get_lang('BookingPeriodTooSmall'),false);
-					$form->display();
-					//echo $buffer;
-					break;
-				case 3 :
-					Display :: display_normal_message(get_lang('BookingPeriodTooBig'),false);
-					$form->display();
-					//echo $buffer;
-					break;
-			}
-		}
-	} else
-		$form->display();
-} else {
-	Display :: display_normal_message(Rsys :: get_return_msg2(get_lang('ReservationTresspassing'), "javascript:history.go(-2)", get_lang('BookingView')),false);
-}
-
-
-Display :: display_footer();
+					if (((Rsys :: mysql_datetime_to_timestamp($array["start_at"]) - $time_start) >= ($min_timepicker*60)) && ($time_start < Rsys :: mysql_datetime_to_timestamp($array["start_at"])))
+					{
+						$start_end .= "<li>".Rsys :: timestamp_to_datetime($time_start)." en ".$array["start_at"]."</li>";
+					}
+				}
+				$time_start = Rsys :: mysql_datetime_to_timestamp($array["end_at"]);
+				$end_time_last_block = $array["end_at"];
+			}
+			if ((Rsys :: mysql_datetime_to_timestamp($res_end_at) - Rsys :: mysql_datetime_to_timestamp($end_time_last_block)) >= ($min_timepicker*60))
+			{
+				$start_end .= "<li>".$end_time_last_block." en ".$res_end_at."</li>";
+			}
+			$start_end .= "</ul>";
+		} else {
+			$start_end = " ".Rsys :: timestamp_to_datetime($time_start)." en ".$res_end_at;
+		}
+
+		//$form->addElement('html', "timestart:".$time_start."-".Rsys :: mysql_datetime_to_timestamp($res_start_at));
+		$form->addElement('html', "<p>".str_replace('#start_end',$start_end,str_replace('#from_till', $from_till,str_replace('#name#', "<b>".$item[3]."</b>",str_replace('#start#', "<b>".$reservation[0][5]."</b>", str_replace('#end#', "<b>".$reservation[0][6]."</b>", get_lang("SubscribeTimePickerInformation"))))))." </p>");
+		$form->add_timewindow('startpicker', 'endpicker', get_lang('StartDate'), get_lang('EndDate'));
+		$form->addElement('hidden', 'min', $reservation[0][12]);
+		$form->addElement('hidden', 'max', $reservation[0][13]);
+		$datum = $_GET['timestart'];
+		$defaultvalues['startpicker'] = Rsys :: timestamp_to_datetime($datum);
+		//$defaultvalues['endpicker'] = Rsys :: timestamp_to_datetime($datum +900);
+		$defaultvalues['endpicker'] = Rsys :: timestamp_to_datetime($datum +($min_timepicker*60));
+		$form->setDefaults($defaultvalues);
+	} else {
+		$form->addElement('html', "<p> * ".str_replace('#name#', "<b>".$item[3]."</b>",str_replace('#start#', "<b>".$reservation[0][5]."</b>", str_replace('#end#', "<b>".$reservation[0][6]."</b>", get_lang('SubscribeInformation'))))." *</p>");
+	}
+	$buttons[] = $form->createElement('submit', 'submit', get_lang('Ok'));
+	$buttons[] = $form->createElement('button', 'cancel', get_lang('Cancel'), array ('onclick' => 'location.href="reservation.php?cat='.$item[1].'&item='.$item[0].'"'));
+	$form->addGroup($buttons, null, '', '', false);
+
+	$buffer = ob_get_contents();
+	ob_end_clean();
+
+	if ($form->validate()) {
+		$values = $form->exportValues();
+		if ($values['timepicker'] == 0) {
+			$result = Rsys :: add_subscription($_GET['rid'], api_get_user_id(),$values['accepted']);
+			switch ($result) {
+				case 0 :
+					Display :: display_normal_message(Rsys :: get_return_msg2(get_lang('ReservationAdded'), "javascript:history.go(-2)", get_lang('BookingView')),false);
+					break;
+				case 1 :
+					Display :: display_normal_message(Rsys :: get_return_msg2(str_replace('#END#', "<b>".$GLOBALS['end_date']."</b>",str_replace('#START#', "<b>".$GLOBALS['start_date']."</b>",get_lang('ReservationAlready'))),"reservation.php?cat=".$item[1]."&item=".$item[0]."", get_lang('BookingView')),false);
+					break;
+			}
+
+		} else {
+			$result = Rsys :: add_subscription_timepicker($_GET['rid'], api_get_user_id(), $values['startpicker'], $values['endpicker'],$values['accepted'],$values['min'],$values['max']);
+			switch ($result) {
+				case 0 :
+					Display :: display_normal_message(Rsys :: get_return_msg2(get_lang('ReservationAdded'), "reservation.php?cat=".$item[1]."&item=".$item[0]."&date=".date( 'Y-m-d',Rsys :: mysql_datetime_to_timestamp($values['startpicker']))."&changemonth=yes", get_lang('BookingView')),false);
+					break;
+				case 1 :
+					Display :: display_normal_message(str_replace('#END#', "<b>".$GLOBALS['end_date']."</b>",str_replace('#START#', "<b>".$GLOBALS['start_date']."</b>",get_lang('ReservationOutOfDate'))),false);
+					$form->display();
+					echo $buffer;
+					break;
+				case 2 :
+					Display :: display_normal_message(get_lang('BookingPeriodTooSmall'),false);
+					$form->display();
+					//echo $buffer;
+					break;
+				case 3 :
+					Display :: display_normal_message(get_lang('BookingPeriodTooBig'),false);
+					$form->display();
+					//echo $buffer;
+					break;
+			}
+		}
+	} else
+		$form->display();
+} else {
+	Display :: display_normal_message(Rsys :: get_return_msg2(get_lang('ReservationTresspassing'), "javascript:history.go(-2)", get_lang('BookingView')),false);
+}
+
+
+Display :: display_footer();
 ?>

+ 67 - 67
main/social/contacts.inc.php

@@ -1,69 +1,69 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-
-$language_file = array('registration','messages','userInfo','admin');
-require '../inc/global.inc.php';
-require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-require_once api_get_path(LIBRARY_PATH).'image.lib.php';
-require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-require_once '../inc/lib/social.lib.php';
-$this_section = SECTION_MYPROFILE;
-$_SESSION['this_section']=$this_section;
-//$list_path_friends=array();
-$request=api_is_xml_http_request();
-$language_variable=api_xml_http_response_encode(get_lang('Contacts'));
-//api_display_tool_title($language_variable);
-
-$user_id=api_get_user_id();
-$image_path = UserManager::get_user_picture_path_by_id ($user_id,'web',false,true);
-?>
-<div align="center" >
-<table width="100%" border="0" cellpadding="0" cellspacing="0" class="social-content-table">
-  <tr>
-    <td width="100%" height="20" valign="top">
-    <table width="100%" border="0" cellpadding="0" cellspacing="0">
-      <tr>
-        <td width="100%" height="20" valign="top"><?php
-        echo '&nbsp;&nbsp;Dokeos&nbsp;&nbsp;-&nbsp;&nbsp;';
-        $user_id=api_get_user_id();
-        $user_info=api_get_user_info($user_id);
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+
+$language_file = array('registration','messages','userInfo','admin');
+require '../inc/global.inc.php';
+require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+require_once api_get_path(LIBRARY_PATH).'image.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once '../inc/lib/social.lib.php';
+$this_section = SECTION_MYPROFILE;
+$_SESSION['this_section']=$this_section;
+//$list_path_friends=array();
+$request=api_is_xml_http_request();
+$language_variable=api_xml_http_response_encode(get_lang('Contacts'));
+//api_display_tool_title($language_variable);
+
+$user_id=api_get_user_id();
+$image_path = UserManager::get_user_picture_path_by_id ($user_id,'web',false,true);
+?>
+<div align="center" >
+<table width="100%" border="0" cellpadding="0" cellspacing="0" class="social-content-table">
+  <tr>
+    <td width="100%" height="20" valign="top">
+    <table width="100%" border="0" cellpadding="0" cellspacing="0">
+      <tr>
+        <td width="100%" height="20" valign="top"><?php
+        echo '&nbsp;&nbsp;Dokeos&nbsp;&nbsp;-&nbsp;&nbsp;';
+        $user_id=api_get_user_id();
+        $user_info=api_get_user_info($user_id);
         echo $name_user=api_xml_http_response_encode(api_get_person_name($user_info['firstName'], $user_info['lastName']));
-         ?></td>
-        </tr>
-    </table>
-    </td>
-  </tr>
-  <tr>
-    <td height="25" valign="top">
-    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="social-subtitle-search">
-      <tr>
-        <td width="100%" height="25" valign="top" class="social-align-box">&nbsp;&nbsp;<?php echo api_xml_http_response_encode(get_lang('Search')) .'&nbsp;&nbsp; : &nbsp;&nbsp;'; ?><input class="social-search-image" type="text" class="search-image" id="id_search_image" name="id_search_image" value="" onkeyup="search_image_social(this)" /></td>
-      </tr>
-    </table></td>
-  </tr>
-  <tr>
-    <td height="175" valign="top">
-    <table width="100%" border="0" cellpadding="0" cellspacing="0" >
-      <tr>
-        <td width="100%" height="22" valign="top">
-        <table width="100%" border="0" cellpadding="0" cellspacing="0" class="social-align-box">
-          <tr>
-            <td width="100%" height="22" valign="top">&nbsp;&nbsp;<?php echo api_xml_http_response_encode(get_lang('ContactsList')); ?></td>
-              </tr>
-        </table></td>
-        </tr>
-      <tr>
-	<td height="153" valign="top">
-<?php
-echo '<div id="div_content_table">';
-require_once 'show_search_image.inc.php';
-echo '</div>';
-?>
-        </td>
-        </tr>
-    </table></td>
-  </tr>
-</table>
+         ?></td>
+        </tr>
+    </table>
+    </td>
+  </tr>
+  <tr>
+    <td height="25" valign="top">
+    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="social-subtitle-search">
+      <tr>
+        <td width="100%" height="25" valign="top" class="social-align-box">&nbsp;&nbsp;<?php echo api_xml_http_response_encode(get_lang('Search')) .'&nbsp;&nbsp; : &nbsp;&nbsp;'; ?><input class="social-search-image" type="text" class="search-image" id="id_search_image" name="id_search_image" value="" onkeyup="search_image_social(this)" /></td>
+      </tr>
+    </table></td>
+  </tr>
+  <tr>
+    <td height="175" valign="top">
+    <table width="100%" border="0" cellpadding="0" cellspacing="0" >
+      <tr>
+        <td width="100%" height="22" valign="top">
+        <table width="100%" border="0" cellpadding="0" cellspacing="0" class="social-align-box">
+          <tr>
+            <td width="100%" height="22" valign="top">&nbsp;&nbsp;<?php echo api_xml_http_response_encode(get_lang('ContactsList')); ?></td>
+              </tr>
+        </table></td>
+        </tr>
+      <tr>
+	<td height="153" valign="top">
+<?php
+echo '<div id="div_content_table">';
+require_once 'show_search_image.inc.php';
+echo '</div>';
+?>
+        </td>
+        </tr>
+    </table></td>
+  </tr>
+</table>
 </div>

+ 85 - 85
main/social/group_contact.inc.php

@@ -1,90 +1,90 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-
-$language_file = array('registration','messages','userInfo','admin');
-require '../inc/global.inc.php';
-require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-require_once api_get_path(LIBRARY_PATH).'image.lib.php';
-require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-require_once '../inc/lib/social.lib.php';
-$this_section = SECTION_MYPROFILE;
-$_SESSION['this_section']=$this_section;
-$list_path_friends=array();
-$list_groups=array();
-$request=api_is_xml_http_request();
-$language_variable=api_xml_http_response_encode(get_lang('ContactsGroups'));
-//api_display_tool_title($language_variable);
-$user_id=api_get_user_id();
-$list_groups=UserFriend::show_list_type_friends();
-
-for ($p=0;$p<count($list_groups);$p++) {
-	$list_path_friends=UserFriend::get_list_path_web_by_user_id ($user_id,$list_groups[$p]['id']);
-?>
-<table width="100%" border="0" cellpadding="0" cellspacing="0" class="data_table">
-          <tr>
-		<th align="left" id="<?php echo 'td_'.$list_groups[$p]['id']; ?>" style="cursor:pointer" valign="top" onclick="toogle_function(this)">
-			<?php echo api_xml_http_response_encode(get_lang($list_groups[$p]['title'])); ?>
-		</th>
-	    <th width="30" align="center">
-    		<?php Display::display_icon('visible.gif',api_xml_http_response_encode(get_lang('ChangeVisibility')), array('id'=>'btn_'.$list_groups[$p]['id'])); ?>
-    		<input type="hidden" class="hidden" id="id_hd_dame" name="hd_dame" value="0" />
-	    </th>
-        </tr>
-      <tr>
-	<td colspan="2">
-		<div align="center" id="<?php echo 'div_group_'.$list_groups[$p]['id']; ?>" >
-		<?php
-		$friend_html='';
-		$number_of_images=10;
-		$number_friends=0;
-		$list_friends_id=array();
-		$list_friends_dir=array();
-		$list_friends_file=array();
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+
+$language_file = array('registration','messages','userInfo','admin');
+require '../inc/global.inc.php';
+require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+require_once api_get_path(LIBRARY_PATH).'image.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once '../inc/lib/social.lib.php';
+$this_section = SECTION_MYPROFILE;
+$_SESSION['this_section']=$this_section;
+$list_path_friends=array();
+$list_groups=array();
+$request=api_is_xml_http_request();
+$language_variable=api_xml_http_response_encode(get_lang('ContactsGroups'));
+//api_display_tool_title($language_variable);
+$user_id=api_get_user_id();
+$list_groups=UserFriend::show_list_type_friends();
+
+for ($p=0;$p<count($list_groups);$p++) {
+	$list_path_friends=UserFriend::get_list_path_web_by_user_id ($user_id,$list_groups[$p]['id']);
+?>
+<table width="100%" border="0" cellpadding="0" cellspacing="0" class="data_table">
+          <tr>
+		<th align="left" id="<?php echo 'td_'.$list_groups[$p]['id']; ?>" style="cursor:pointer" valign="top" onclick="toogle_function(this)">
+			<?php echo api_xml_http_response_encode(get_lang($list_groups[$p]['title'])); ?>
+		</th>
+	    <th width="30" align="center">
+    		<?php Display::display_icon('visible.gif',api_xml_http_response_encode(get_lang('ChangeVisibility')), array('id'=>'btn_'.$list_groups[$p]['id'])); ?>
+    		<input type="hidden" class="hidden" id="id_hd_dame" name="hd_dame" value="0" />
+	    </th>
+        </tr>
+      <tr>
+	<td colspan="2">
+		<div align="center" id="<?php echo 'div_group_'.$list_groups[$p]['id']; ?>" >
+		<?php
+		$friend_html='';
+		$number_of_images=10;
+		$number_friends=0;
+		$list_friends_id=array();
+		$list_friends_dir=array();
+		$list_friends_file=array();
 		if (count($list_path_friends)!=0) {
-	for ($z=0;$z<count($list_path_friends['id_friend']);$z++) {
-		$list_friends_id[]  = $list_path_friends['id_friend'][$z]['friend_user_id'];
-		$list_friends_dir[] = $list_path_friends['path_friend'][$z]['dir'];
-		$list_friends_file[]= $list_path_friends['path_friend'][$z]['file'];
-	}
-	$number_friends= count($list_friends_dir);
-	$number_loop   = ($number_friends/$number_of_images);
-	$loop_friends  = ceil($number_loop);
-	$j=0;//<div id="div_groupid_"'.$list_groups[$p]['id'].'">
-	for ($k=0;$k<$loop_friends;$k++) {
-		if ($j==$number_of_images) {
-			$number_of_images=$number_of_images*2;
-		}
-		while ($j<$number_of_images) {
-			if ($list_friends_file[$j]<>"") {
+	for ($z=0;$z<count($list_path_friends['id_friend']);$z++) {
+		$list_friends_id[]  = $list_path_friends['id_friend'][$z]['friend_user_id'];
+		$list_friends_dir[] = $list_path_friends['path_friend'][$z]['dir'];
+		$list_friends_file[]= $list_path_friends['path_friend'][$z]['file'];
+	}
+	$number_friends= count($list_friends_dir);
+	$number_loop   = ($number_friends/$number_of_images);
+	$loop_friends  = ceil($number_loop);
+	$j=0;//<div id="div_groupid_"'.$list_groups[$p]['id'].'">
+	for ($k=0;$k<$loop_friends;$k++) {
+		if ($j==$number_of_images) {
+			$number_of_images=$number_of_images*2;
+		}
+		while ($j<$number_of_images) {
+			if ($list_friends_file[$j]<>"") {
 				$user_info=api_get_user_info($list_friends_id[$j]);
-				$user_name=api_xml_http_response_encode(api_get_person_name($user_info['firstName'], $user_info['lastName']));
-				if($list_friends_file[$j]==='unknown.jpg') {
-					$big='';
-				} else {
-					$big='big_';
-				}
-				$friends_profile = UserFriend::get_picture_user($list_friends_id[$j], $list_friends_file[$j], 92);
-				$friend_html.='<div id="div_'.$list_friends_id[$j].'" class="image_friend_network">' .
-							  '<a href="javascript:void(0)" onclick=load_thick("'.$list_friends_dir[$j].$big.$list_friends_file[$j].'","") title="" class="thickbox">' .
-							  '<span><center><img src="'.$friends_profile['file'].'" '.$friends_profile['style'].' id="imgfriend_'.$list_friends_id[$j].'" title="'.api_xml_http_response_encode($user_name).'" /></center></span>'.
-							  '<center class="friend">'.api_xml_http_response_encode($user_name).'</center>'.
-							  '</a></div>';
-			}
-			$j++;
-		}
-	}
+				$user_name=api_xml_http_response_encode(api_get_person_name($user_info['firstName'], $user_info['lastName']));
+				if($list_friends_file[$j]==='unknown.jpg') {
+					$big='';
+				} else {
+					$big='big_';
+				}
+				$friends_profile = UserFriend::get_picture_user($list_friends_id[$j], $list_friends_file[$j], 92);
+				$friend_html.='<div id="div_'.$list_friends_id[$j].'" class="image_friend_network">' .
+							  '<a href="javascript:void(0)" onclick=load_thick("'.$list_friends_dir[$j].$big.$list_friends_file[$j].'","") title="" class="thickbox">' .
+							  '<span><center><img src="'.$friends_profile['file'].'" '.$friends_profile['style'].' id="imgfriend_'.$list_friends_id[$j].'" title="'.api_xml_http_response_encode($user_name).'" /></center></span>'.
+							  '<center class="friend">'.api_xml_http_response_encode($user_name).'</center>'.
+							  '</a></div>';
+			}
+			$j++;
+		}
+	}
 	echo $friend_html;
 		}
-		else {
-			echo api_xml_http_response_encode(get_lang('YouDontHaveContactsInThisGroup'));
-		}
-		?>
-		</div>
-	</td>
-  </tr>
-</table>
-<?php
-}
+		else {
+			echo api_xml_http_response_encode(get_lang('YouDontHaveContactsInThisGroup'));
+		}
+		?>
+		</div>
+	</td>
+  </tr>
+</table>
+<?php
+}
 ?>

+ 451 - 451
main/social/index.php

@@ -1,489 +1,489 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-
-$cidReset = true;
-$language_file = array('registration','messages','userInfo','admin');
-require '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-$this_section = SECTION_MYPROFILE;
-$_SESSION['this_section']=$this_section;
-api_block_anonymous_users();
-$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
-$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery-1.1.3.1.pack.js" type="text/javascript"></script>';
-$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.history_remote.pack.js" type="text/javascript"></script>';
-$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.tabs.pack.js" type="text/javascript"></script>';
-$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/thickbox.js" type="text/javascript" language="javascript"></script>';
-//$htmlHeadXtra[] = '<style rel="stylesheet" href="../inc/lib/javascript/thickbox.css" type="text/css" media="projection, screen">';
-$htmlHeadXtra[]='<style type="text/css" media="all">@import "'.api_get_path(WEB_LIBRARY_PATH).'javascript/thickbox.css";</style>';
-$htmlHeadXtra[] = '<script type="text/javascript">
-$(function() {
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+
+$cidReset = true;
+$language_file = array('registration','messages','userInfo','admin');
+require '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+$this_section = SECTION_MYPROFILE;
+$_SESSION['this_section']=$this_section;
+api_block_anonymous_users();
+$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
+$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery-1.1.3.1.pack.js" type="text/javascript"></script>';
+$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.history_remote.pack.js" type="text/javascript"></script>';
+$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.tabs.pack.js" type="text/javascript"></script>';
+$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/thickbox.js" type="text/javascript" language="javascript"></script>';
+//$htmlHeadXtra[] = '<style rel="stylesheet" href="../inc/lib/javascript/thickbox.css" type="text/css" media="projection, screen">';
+$htmlHeadXtra[]='<style type="text/css" media="all">@import "'.api_get_path(WEB_LIBRARY_PATH).'javascript/thickbox.css";</style>';
+$htmlHeadXtra[] = '<script type="text/javascript">
+$(function() {
 	$("#container-9").tabs({ remote: true});
-});
-function register_friend(element_input) {
-	name_button=$(element_input).attr("id");
-	name_div_id="id_"+name_button.substring(13);
-	user_id=name_div_id.split("_");
-	user_friend_id=user_id[1];
-	 $.ajax({
-		contentType: "application/x-www-form-urlencoded",
-		beforeSend: function(objeto) {
-		$("#id_response").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-		type: "POST",
-		url: "../social/register_friend.php",
-		data: "friend_id="+user_friend_id,
-		success: function(datos) {
-		 $("div#"+name_div_id).hide("slow");
-		 $("#id_response").html(datos);
-		}
+});
+function register_friend(element_input) {
+	name_button=$(element_input).attr("id");
+	name_div_id="id_"+name_button.substring(13);
+	user_id=name_div_id.split("_");
+	user_friend_id=user_id[1];
+	 $.ajax({
+		contentType: "application/x-www-form-urlencoded",
+		beforeSend: function(objeto) {
+		$("#id_response").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+		type: "POST",
+		url: "../social/register_friend.php",
+		data: "friend_id="+user_friend_id,
+		success: function(datos) {
+		 $("div#"+name_div_id).hide("slow");
+		 $("#id_response").html(datos);
+		}
 	});
-}
-function denied_friend (element_input) {
-	name_button=$(element_input).attr("id");
-	name_div_id="id_"+name_button.substring(13);
-	user_id=name_div_id.split("_");
+}
+function denied_friend (element_input) {
+	name_button=$(element_input).attr("id");
+	name_div_id="id_"+name_button.substring(13);
+	user_id=name_div_id.split("_");
 	friend_user_id=user_id[1];
-	 $.ajax({
-		contentType: "application/x-www-form-urlencoded",
-		beforeSend: function(objeto) {
-		$("#id_response").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-		type: "POST",
-		url: "../social/register_friend.php",
-		data: "denied_friend_id="+friend_user_id,
-		success: function(datos) {
-		 $("div#"+name_div_id).hide("slow");
-		 $("#id_response").html(datos);
-		}
-	});
-}
-function delete_friend (element_div) {
-	id_image=$(element_div).attr("id");
-	user_id=id_image.split("_");
-	if (confirm("'.get_lang('Delete', '').'")) {
-		 $.ajax({
-			contentType: "application/x-www-form-urlencoded",
-			beforeSend: function(objeto) {
-			/*$("#id_response").html("Cargando...");*/ },
-			type: "POST",
-			url: "../social/register_friend.php",
-			data: "delete_friend_id="+user_id[1],
-			success: function(datos) {
-			//alert(datos);
-			 $("div#"+"div_"+user_id[1]).hide("slow");
-			 $("div#"+"div_"+user_id[1]).html("");
-			 clear_form ();
-			}
-		});
-	}
-}
-function qualify_friend(element_div) {
-	name_user=$(element_div).attr("title");
-	id_full=$(element_div).attr("id");
-	$("div#div_info_user").html(name_user);
-	user_qualify=id_full.split("_");
-	user_qualify_id=user_qualify[1];
-	$("#user_cod_qualify").attr("value",user_qualify_id);
-	get_image_url=$(element_div).attr("src");
-	img_html="<img width=100 height=120 src="+get_image_url+" />";
-	$("div#div_qualify_image").html(img_html);
-}
-function set_qualify_friend() {
-	user_id_friend = $("#user_cod_qualify").attr("value");
-	type_friend    = $("input[@name=list_type_friend]:checked").val();
-	if (user_id_friend==0) {
-		alert("'.get_lang('SelectOneContact', '').'");
-		return false;
-	}
-	if (type_friend==null) {
-		alert("'.get_lang('SelectOneGroup', '').'");
+	 $.ajax({
+		contentType: "application/x-www-form-urlencoded",
+		beforeSend: function(objeto) {
+		$("#id_response").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+		type: "POST",
+		url: "../social/register_friend.php",
+		data: "denied_friend_id="+friend_user_id,
+		success: function(datos) {
+		 $("div#"+name_div_id).hide("slow");
+		 $("#id_response").html(datos);
+		}
+	});
+}
+function delete_friend (element_div) {
+	id_image=$(element_div).attr("id");
+	user_id=id_image.split("_");
+	if (confirm("'.get_lang('Delete', '').'")) {
+		 $.ajax({
+			contentType: "application/x-www-form-urlencoded",
+			beforeSend: function(objeto) {
+			/*$("#id_response").html("Cargando...");*/ },
+			type: "POST",
+			url: "../social/register_friend.php",
+			data: "delete_friend_id="+user_id[1],
+			success: function(datos) {
+			//alert(datos);
+			 $("div#"+"div_"+user_id[1]).hide("slow");
+			 $("div#"+"div_"+user_id[1]).html("");
+			 clear_form ();
+			}
+		});
+	}
+}
+function qualify_friend(element_div) {
+	name_user=$(element_div).attr("title");
+	id_full=$(element_div).attr("id");
+	$("div#div_info_user").html(name_user);
+	user_qualify=id_full.split("_");
+	user_qualify_id=user_qualify[1];
+	$("#user_cod_qualify").attr("value",user_qualify_id);
+	get_image_url=$(element_div).attr("src");
+	img_html="<img width=100 height=120 src="+get_image_url+" />";
+	$("div#div_qualify_image").html(img_html);
+}
+function set_qualify_friend() {
+	user_id_friend = $("#user_cod_qualify").attr("value");
+	type_friend    = $("input[@name=list_type_friend]:checked").val();
+	if (user_id_friend==0) {
+		alert("'.get_lang('SelectOneContact', '').'");
 		return false;
 	}
-	if (confirm("'.get_lang('AttachContactsPersonal', '').' ?")) {
-		 $.ajax({
-			contentType: "application/x-www-form-urlencoded",
-			beforeSend: function(objeto) {
-			/*$("#id_response").html("Cargando...");*/ },
-			type: "POST",
-			url: "../social/register_friend.php",
-			data: "user_id_friend_q="+user_id_friend+"&type_friend_q="+type_friend,
-			success: function(datos) {
-			//alert(datos);
-			tb_remove();
-			//clear_form();
-			}
-		});
-	}
-}
-function show_icon_delete(element_html) {
-	elem_id=$(element_html).attr("id");
-	id_elem=elem_id.split("_");
-	ident="#img_"+id_elem[1];
-	$(ident).attr("src","../img/delete.gif");
-	$(ident).attr("alt","'.get_lang('Delete', '').'");
-	$(ident).attr("title","'.get_lang('Delete', '').'");
-}
-function hide_icon_delete(element_html)  {
-	elem_id=$(element_html).attr("id");
-	id_elem=elem_id.split("_");
-	ident="#img_"+id_elem[1];
-	$(ident).attr("src","../img/blank.gif");
-	$(ident).attr("alt","");
-	$(ident).attr("title","");
-}
-function search_image_social(element_html)  {
-	name_search=$(element_html).attr("value");
-	 $.ajax({
-		contentType: "application/x-www-form-urlencoded",
-		beforeSend: function(objeto) {
-		$("#div_content_table").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-		type: "POST",
-		url: "../social/show_search_image.inc.php",
-		data: "search_name_q="+name_search,
-		success: function(datos) {
-			$("div#div_content_table").html(datos);
-		}
-	});
-}
-function clear_form () {
-	$("input[@type=radio]").attr("checked", false);
-	$("div#div_qualify_image").html("");
-	$("div#div_info_user").html("");
-}
-function toogle_function (element_html){
-	elem_id=$(element_html).attr("id");
-	id_elem=elem_id.split("_");
-	ident="div#div_group_"+id_elem[1];
-	id_button="#btn_"+id_elem[1];
-	elem_src=$(id_button).attr("src");
-	image_show=elem_src.split("/");
-	for (i=0;i<image_show.length;i++) {
-		if (image_show[i]=="visible.gif" || image_show[i]=="invisible_na.gif") {
-			my_image=image_show[i];
-		}
-	}
-	if (my_image=="visible.gif") {
+	if (type_friend==null) {
+		alert("'.get_lang('SelectOneGroup', '').'");
+		return false;
+	}
+	if (confirm("'.get_lang('AttachContactsPersonal', '').' ?")) {
+		 $.ajax({
+			contentType: "application/x-www-form-urlencoded",
+			beforeSend: function(objeto) {
+			/*$("#id_response").html("Cargando...");*/ },
+			type: "POST",
+			url: "../social/register_friend.php",
+			data: "user_id_friend_q="+user_id_friend+"&type_friend_q="+type_friend,
+			success: function(datos) {
+			//alert(datos);
+			tb_remove();
+			//clear_form();
+			}
+		});
+	}
+}
+function show_icon_delete(element_html) {
+	elem_id=$(element_html).attr("id");
+	id_elem=elem_id.split("_");
+	ident="#img_"+id_elem[1];
+	$(ident).attr("src","../img/delete.gif");
+	$(ident).attr("alt","'.get_lang('Delete', '').'");
+	$(ident).attr("title","'.get_lang('Delete', '').'");
+}
+function hide_icon_delete(element_html)  {
+	elem_id=$(element_html).attr("id");
+	id_elem=elem_id.split("_");
+	ident="#img_"+id_elem[1];
+	$(ident).attr("src","../img/blank.gif");
+	$(ident).attr("alt","");
+	$(ident).attr("title","");
+}
+function search_image_social(element_html)  {
+	name_search=$(element_html).attr("value");
+	 $.ajax({
+		contentType: "application/x-www-form-urlencoded",
+		beforeSend: function(objeto) {
+		$("#div_content_table").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+		type: "POST",
+		url: "../social/show_search_image.inc.php",
+		data: "search_name_q="+name_search,
+		success: function(datos) {
+			$("div#div_content_table").html(datos);
+		}
+	});
+}
+function clear_form () {
+	$("input[@type=radio]").attr("checked", false);
+	$("div#div_qualify_image").html("");
+	$("div#div_info_user").html("");
+}
+function toogle_function (element_html){
+	elem_id=$(element_html).attr("id");
+	id_elem=elem_id.split("_");
+	ident="div#div_group_"+id_elem[1];
+	id_button="#btn_"+id_elem[1];
+	elem_src=$(id_button).attr("src");
+	image_show=elem_src.split("/");
+	for (i=0;i<image_show.length;i++) {
+		if (image_show[i]=="visible.gif" || image_show[i]=="invisible_na.gif") {
+			my_image=image_show[i];
+		}
+	}
+	if (my_image=="visible.gif") {
 		$(ident).hide("slow");
-		$(id_button).attr("src","../img/invisible_na.gif");
-	} else {
+		$(id_button).attr("src","../img/invisible_na.gif");
+	} else {
 		$(ident).show("slow");
-		$(id_button).attr("src","../img/visible.gif");
-	}
-}
-function selectall_cheks() {
-	$("input[@type=checkbox]").attr("checked", true);
-}
-function unselectall_cheks() {
-	$("input[@type=checkbox]").attr("checked", false);
-}
-function submit_form (path_submit) {
-	if (path_submit=="inbox") {
-		if (count_checkbox("inbox") > 0) {
+		$(id_button).attr("src","../img/visible.gif");
+	}
+}
+function selectall_cheks() {
+	$("input[@type=checkbox]").attr("checked", true);
+}
+function unselectall_cheks() {
+	$("input[@type=checkbox]").attr("checked", false);
+}
+function submit_form (path_submit) {
+	if (path_submit=="inbox") {
+		if (count_checkbox("inbox") > 0) {
 		   document.getElementById(\'form_send\').action="../social/index.php?inbox=true#remote-tab-2";
-		   if (confirm("'.get_lang('ConfirmYourChoice', '').'")) {
-		   		$("#form_send").submit();
+		   if (confirm("'.get_lang('ConfirmYourChoice', '').'")) {
+		   		$("#form_send").submit();
 		   }
-		} else {
-			alert("'.get_lang('SelectTheCheckbox', '').'");
-		}
-
-	} else {
-		if (count_checkbox("outbox") > 0) {
+		} else {
+			alert("'.get_lang('SelectTheCheckbox', '').'");
+		}
+
+	} else {
+		if (count_checkbox("outbox") > 0) {
 			document.getElementById(\'form_send_out\').action="../social/index.php?outbox=true#remote-tab-3";
 		   if (confirm("'.get_lang('ConfirmYourChoice', '').'")) {
-				$("#form_send_out").submit();
-		   }
-		} else {
-			alert("'.get_lang('SelectedMoreOptions', '').'");
+				$("#form_send_out").submit();
+		   }
+		} else {
+			alert("'.get_lang('SelectedMoreOptions', '').'");
+		}
+	}
+}
+function count_checkbox(status_type) {
+	if (status_type=="inbox") {
+		var checkboxes = document.getElementsByName("id[]");
+		var cont = 0;
+		for (var x=0; x < checkboxes.length; x++) {
+		   if (checkboxes[x].checked) {
+		       cont = cont + 1;
+		    }
 		}
-	}
-}
-function count_checkbox(status_type) {
-	if (status_type=="inbox") {
-		var checkboxes = document.getElementsByName("id[]");
-		var cont = 0;
-		for (var x=0; x < checkboxes.length; x++) {
-		   if (checkboxes[x].checked) {
-		       cont = cont + 1;
-		    }
-		}
 		return cont;
-	} else {
-		var checkboxes = document.getElementsByName("out[]");
-		var cont = 0;
-		for (var x=0; x < checkboxes.length; x++) {
-		   if (checkboxes[x].checked) {
-		       cont = cont + 1;
-		    }
-		}
+	} else {
+		var checkboxes = document.getElementsByName("out[]");
+		var cont = 0;
+		for (var x=0; x < checkboxes.length; x++) {
+		   if (checkboxes[x].checked) {
+		       cont = cont + 1;
+		    }
+		}
 		return cont;
-	}
-}
-function get_action_url_and_show_messages (name_rs,name_id) {
-	$(".confirmation-message").remove();
-	$(".normal-message").remove();
+	}
+}
+function get_action_url_and_show_messages (name_rs,name_id) {
+	$(".confirmation-message").remove();
+	$(".normal-message").remove();
 	$(".error-message").remove();
-		 $.ajax({
-			contentType: "application/x-www-form-urlencoded",
-			beforeSend: function(objeto) {
-			$("div#div_content_messages").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-			type: "GET",
-			url: "../messages/view_message.php",
-			data: "rs="+name_rs+"&id="+name_id,
-			success: function(datos) {
-			 $("div#div_content_messages").html(datos);
+		 $.ajax({
+			contentType: "application/x-www-form-urlencoded",
+			beforeSend: function(objeto) {
+			$("div#div_content_messages").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+			type: "GET",
+			url: "../messages/view_message.php",
+			data: "rs="+name_rs+"&id="+name_id,
+			success: function(datos) {
+			 $("div#div_content_messages").html(datos);
 			 $("div#div_content_table_data").html(" ");
-			}
-		});
-}
-function close_div_show (my_div) {
-	$(".confirmation-message").remove();
-	$(".normal-message").remove();
-	$(".error-message").remove();
-	$("div#"+my_div).html("");
-		 $.ajax({
-			contentType: "application/x-www-form-urlencoded",
-			beforeSend: function(objeto) {
-			$("div#div_content_table_data").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-			type: "POST",
-			url: "../messages/inbox.php",
-			data:"",
-			success: function(datos) {
+			}
+		});
+}
+function close_div_show (my_div) {
+	$(".confirmation-message").remove();
+	$(".normal-message").remove();
+	$(".error-message").remove();
+	$("div#"+my_div).html("");
+		 $.ajax({
+			contentType: "application/x-www-form-urlencoded",
+			beforeSend: function(objeto) {
+			$("div#div_content_table_data").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+			type: "POST",
+			url: "../messages/inbox.php",
+			data:"",
+			success: function(datos) {
 			 $("div#div_content_table_data").html(datos);
-			}
-		});
-}
-function reply_to_messages (my_action,name_rs,name_id) {
-	$(".confirmation-message").remove();
-	$(".normal-message").remove();
-	$(".error-message").remove();
-	if(my_action=="show") {
-		$("div#div_content_messages").html("");
-		$("div#div_content_table_data").html("");
-		 $.ajax({
-			contentType: "application/x-www-form-urlencoded",
-			beforeSend: function(objeto) {
-			$("div#div_content_messages").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-			type: "GET",
-			url: "../messages/new_message.php",
-			data:"re_id="+name_rs+"&id="+name_id,
-			success: function(datos) {
+			}
+		});
+}
+function reply_to_messages (my_action,name_rs,name_id) {
+	$(".confirmation-message").remove();
+	$(".normal-message").remove();
+	$(".error-message").remove();
+	if(my_action=="show") {
+		$("div#div_content_messages").html("");
+		$("div#div_content_table_data").html("");
+		 $.ajax({
+			contentType: "application/x-www-form-urlencoded",
+			beforeSend: function(objeto) {
+			$("div#div_content_messages").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+			type: "GET",
+			url: "../messages/new_message.php",
+			data:"re_id="+name_rs+"&id="+name_id,
+			success: function(datos) {
 			 $("div#div_content_messages").html(datos);
-			}
-		});
-	}
-}
-function compose_and_show_message (my_action,name_rs) {
-	if(my_action=="show") {
-		$("div#div_content_messages").html("");
-		$("div#div_content_table_data").html("");
-		$(".confirmation-message").remove();
-		$(".normal-message").remove();
-		$(".error-message").remove();
-			$.ajax({
-			contentType: "application/x-www-form-urlencoded",
-			beforeSend: function(objeto) {
-			$("div#div_content_messages").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-			type: "GET",
-			url: "../messages/new_message.php",
-			data:"rs="+name_rs,
-			success: function(datos) {
+			}
+		});
+	}
+}
+function compose_and_show_message (my_action,name_rs) {
+	if(my_action=="show") {
+		$("div#div_content_messages").html("");
+		$("div#div_content_table_data").html("");
+		$(".confirmation-message").remove();
+		$(".normal-message").remove();
+		$(".error-message").remove();
+			$.ajax({
+			contentType: "application/x-www-form-urlencoded",
+			beforeSend: function(objeto) {
+			$("div#div_content_messages").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+			type: "GET",
+			url: "../messages/new_message.php",
+			data:"rs="+name_rs,
+			success: function(datos) {
 			 $("div#div_content_messages").html(datos);
-			}
+			}
 		});
 	}
-}
-function send_request_and_search() {
-	cont=0;
-      //$("#id_text_name").bind("keyup", function(){
-      	name=$("#id_text_name").get(0).value;
-      	if (name.length==0) {
-      		return false;
+}
+function send_request_and_search() {
+	cont=0;
+      //$("#id_text_name").bind("keyup", function(){
+      	name=$("#id_text_name").get(0).value;
+      	if (name.length==0) {
+      		return false;
       	}
-		$.ajax({
-				contentType: "application/x-www-form-urlencoded",
-				beforeSend: function(objeto) {
-				//$("#id_div_search").html("Searching...");
-					},
-				type: "POST",
-				url: "../social/select_options.php",
-				data: "search="+name,
-				success: function(datos){
+		$.ajax({
+				contentType: "application/x-www-form-urlencoded",
+				beforeSend: function(objeto) {
+				//$("#id_div_search").html("Searching...");
+					},
+				type: "POST",
+				url: "../social/select_options.php",
+				data: "search="+name,
+				success: function(datos){
 
-					num_records=datos.split(\'</option>\');
-					if (num_records.length==1) {
+					num_records=datos.split(\'</option>\');
+					if (num_records.length==1) {
 						$("#id_div_search").html("");
-						return false;
-					} else {
-						 $("#id_div_search").html(datos)
-						  list_search_hide();
-					}
+						return false;
+					} else {
+						 $("#id_div_search").html(datos)
+						  list_search_hide();
+					}
 
-						$("#id_search_name").bind("click", function() {
-							name_option=$("select#id_search_name option:selected").text();
-							code_option=$("select#id_search_name option:selected").val();
-							 $("#user_list").attr("value", code_option);
-							 $("#id_text_name").attr("value", name_option);
+						$("#id_search_name").bind("click", function() {
+							name_option=$("select#id_search_name option:selected").text();
+							code_option=$("select#id_search_name option:selected").val();
+							 $("#user_list").attr("value", code_option);
+							 $("#id_text_name").attr("value", name_option);
 
-							 $("#id_div_search").html("");
-							 cont++;
-						 });
-				}
-		});
-      //});
-}
-function delete_one_message (num_id) {
-		$("div#div_content_messages").html("");
-		$("div#div_content_table_data").html("");
-		$(".confirmation-message").remove();
-		$(".normal-message").remove();
+							 $("#id_div_search").html("");
+							 cont++;
+						 });
+				}
+		});
+      //});
+}
+function delete_one_message (num_id) {
+		$("div#div_content_messages").html("");
+		$("div#div_content_table_data").html("");
+		$(".confirmation-message").remove();
+		$(".normal-message").remove();
 		$(".error-message").remove();
-			$.ajax({
-				contentType: "application/x-www-form-urlencoded",
-				beforeSend: function(objeto) {
-				$("#div_content_table_data").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-				type: "GET",
-				url: "../messages/inbox.php",
-				data: "action="+"deleteone"+"&id="+num_id,
-				success: function(datos){
-				$("#div_content_table_data").html(datos)
-				}
-		});
-}
-function show_sent_message (id_sent) {
-		$("div#div_content_messages_sent").html("");
-		$("div#div_content_table_data_sent").html("");
-			$.ajax({
-				contentType: "application/x-www-form-urlencoded",
-				beforeSend: function(objeto) {
-				$("#div_content_table_data_sent").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-				type: "GET",
-				url: "../messages/view_message.php",
-				data: "rs="+"1"+"&id_send="+id_sent,
-				success: function(datos){
-				$("#div_content_table_data_sent").html(datos)
-				}
-		});
-}
-function close_and_open_outbox() {
-		$("div#div_content_messages_sent").html("");
-		$("div#div_content_table_data_sent").html("");
-		 $.ajax({
-			contentType: "application/x-www-form-urlencoded",
-			beforeSend: function(objeto) {
-			$("div#div_content_table_data_sent").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-			type: "POST",
-			url: "../messages/outbox.php",
-			data:"",
-			success: function(datos) {
+			$.ajax({
+				contentType: "application/x-www-form-urlencoded",
+				beforeSend: function(objeto) {
+				$("#div_content_table_data").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+				type: "GET",
+				url: "../messages/inbox.php",
+				data: "action="+"deleteone"+"&id="+num_id,
+				success: function(datos){
+				$("#div_content_table_data").html(datos)
+				}
+		});
+}
+function show_sent_message (id_sent) {
+		$("div#div_content_messages_sent").html("");
+		$("div#div_content_table_data_sent").html("");
+			$.ajax({
+				contentType: "application/x-www-form-urlencoded",
+				beforeSend: function(objeto) {
+				$("#div_content_table_data_sent").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+				type: "GET",
+				url: "../messages/view_message.php",
+				data: "rs="+"1"+"&id_send="+id_sent,
+				success: function(datos){
+				$("#div_content_table_data_sent").html(datos)
+				}
+		});
+}
+function close_and_open_outbox() {
+		$("div#div_content_messages_sent").html("");
+		$("div#div_content_table_data_sent").html("");
+		 $.ajax({
+			contentType: "application/x-www-form-urlencoded",
+			beforeSend: function(objeto) {
+			$("div#div_content_table_data_sent").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+			type: "POST",
+			url: "../messages/outbox.php",
+			data:"",
+			success: function(datos) {
 			 $("div#div_content_table_data_sent").html(datos);
-			}
-		});
-}
-function delete_one_message_outbox (num_id) {
-		$("div#div_content_messages_sent").html("");
+			}
+		});
+}
+function delete_one_message_outbox (num_id) {
+		$("div#div_content_messages_sent").html("");
 		$("div#div_content_table_data_sent").html("");
-			$.ajax({
-				contentType: "application/x-www-form-urlencoded",
-				beforeSend: function(objeto) {
-				$("#div_content_table_data_sent").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
-				type: "GET",
-				url: "../messages/outbox.php",
-				data: "action="+"deleteone"+"&id="+num_id,
-				success: function(datos){
-				$("#div_content_table_data_sent").html(datos)
-				}
-		});
-}
-function list_search_hide () {
-		setTimeout("hide_search_list()",2000);
-}
-function hide_search_list () {
-	$("div#id_div_search").html("");
-}
-</script>';
-if (api_get_setting('allow_message_tool')=='true') {
-	$htmlHeadXtra[] ='<script type="text/javascript">
-		function delete_message_js() {
-			$(".message-content").animate({ opacity: "hide" }, "slow");
+			$.ajax({
+				contentType: "application/x-www-form-urlencoded",
+				beforeSend: function(objeto) {
+				$("#div_content_table_data_sent").html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
+				type: "GET",
+				url: "../messages/outbox.php",
+				data: "action="+"deleteone"+"&id="+num_id,
+				success: function(datos){
+				$("#div_content_table_data_sent").html(datos)
+				}
+		});
+}
+function list_search_hide () {
+		setTimeout("hide_search_list()",2000);
+}
+function hide_search_list () {
+	$("div#id_div_search").html("");
+}
+</script>';
+if (api_get_setting('allow_message_tool')=='true') {
+	$htmlHeadXtra[] ='<script type="text/javascript">
+		function delete_message_js() {
+			$(".message-content").animate({ opacity: "hide" }, "slow");
 			$(".message-view").animate({ opacity: "show" }, "slow");
-		}
+		}
 	</script>';
-}
-$htmlHeadXtra[] = '<link rel="stylesheet" href="../inc/lib/javascript/jquery.tabs.css" type="text/css" media="print, projection, screen">';
-$htmlHeadXtra[] = '<link rel="stylesheet" href="'.api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/jquery.tabs.css" type="text/css" media="print, projection, screen">';
-$htmlHeadXtra[] = '
-        <!-- Additional IE/Win specific style sheet (Conditional Comments) -->
-        <!--[if lte IE 7]>
-        <link rel="stylesheet" href="../inc/lib/javascript/jquery.tabs-ie.css" type="text/css" media="projection, screen">
-        <![endif]-->';
-$_SESSION['social_exist']=true;
-$_SESSION['social_dest'] = 'index.php';
-$interbreadcrumb[]= array (
-	'url' => '#',
-	'name' => get_lang('ModifyProfile')
-);
-if ((api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') ||(api_get_setting('allow_social_tool')=='true') && api_get_user_id()<>2 && api_get_user_id()<>0) {
-	$interbreadcrumb[]= array (
-	'url' => 'index.php?#remote-tab-1',
-	'name' => get_lang('SocialNetwork')
-	);
-} elseif ((api_get_setting('allow_social_tool')=='false' && api_get_setting('allow_message_tool')=='true')) {
-	$interbreadcrumb[]= array (
-	'url' => 'index.php?#remote-tab-1',
-	'name' => get_lang('MessageTool')
+}
+$htmlHeadXtra[] = '<link rel="stylesheet" href="../inc/lib/javascript/jquery.tabs.css" type="text/css" media="print, projection, screen">';
+$htmlHeadXtra[] = '<link rel="stylesheet" href="'.api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/jquery.tabs.css" type="text/css" media="print, projection, screen">';
+$htmlHeadXtra[] = '
+        <!-- Additional IE/Win specific style sheet (Conditional Comments) -->
+        <!--[if lte IE 7]>
+        <link rel="stylesheet" href="../inc/lib/javascript/jquery.tabs-ie.css" type="text/css" media="projection, screen">
+        <![endif]-->';
+$_SESSION['social_exist']=true;
+$_SESSION['social_dest'] = 'index.php';
+$interbreadcrumb[]= array (
+	'url' => '#',
+	'name' => get_lang('ModifyProfile')
+);
+if ((api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') ||(api_get_setting('allow_social_tool')=='true') && api_get_user_id()<>2 && api_get_user_id()<>0) {
+	$interbreadcrumb[]= array (
+	'url' => 'index.php?#remote-tab-1',
+	'name' => get_lang('SocialNetwork')
+	);
+} elseif ((api_get_setting('allow_social_tool')=='false' && api_get_setting('allow_message_tool')=='true')) {
+	$interbreadcrumb[]= array (
+	'url' => 'index.php?#remote-tab-1',
+	'name' => get_lang('MessageTool')
 	);
-}
-
-Display :: display_header('');
-if (isset($_GET['sendform'])) {
-	$form_reply=array();
-	$form_reply[]=urlencode($_POST['title']);
-	$form_reply[]=urlencode(api_html_entity_decode($_POST['content']));
-	$form_reply[]=$_POST['user_list'];
-	$form_reply[]=$_POST['re_id'];
-	$form_reply[]=urlencode($_POST['compose']);
-	$form_reply[]=urlencode($_POST['id_text_name']);
-	$form_reply[]=urlencode($_POST['save_form']);
-	$form_info=implode(base64_encode('&%ff..x'),$form_reply);
-	$form_send_data_message='?form_reply='.$form_info;
-} elseif (isset($_GET['inbox'])) {
-	$form_delete=array();
-	$form_delete[]=$_POST['action'];
-	for ($i=0;$i<count($_POST['id']);$i++) {
-		$form_delete[]=$_POST['id'][$i];
-	}
-	$form_info=implode(',',$form_delete);
-	$form_send_data_message='?form_delete='.($form_info);
-} elseif (isset($_GET['outbox'])) {
-	$form_delete_outbox=array();
-	$form_delete_outbox[]=$_POST['action'];
-	for ($i=0;$i<count($_POST['out']);$i++) {
-		$form_delete_outbox[]=$_POST['out'][$i];
-	}
-	$form_info_outbox=implode(',',$form_delete_outbox);
+}
+
+Display :: display_header('');
+if (isset($_GET['sendform'])) {
+	$form_reply=array();
+	$form_reply[]=urlencode($_POST['title']);
+	$form_reply[]=urlencode(api_html_entity_decode($_POST['content']));
+	$form_reply[]=$_POST['user_list'];
+	$form_reply[]=$_POST['re_id'];
+	$form_reply[]=urlencode($_POST['compose']);
+	$form_reply[]=urlencode($_POST['id_text_name']);
+	$form_reply[]=urlencode($_POST['save_form']);
+	$form_info=implode(base64_encode('&%ff..x'),$form_reply);
+	$form_send_data_message='?form_reply='.$form_info;
+} elseif (isset($_GET['inbox'])) {
+	$form_delete=array();
+	$form_delete[]=$_POST['action'];
+	for ($i=0;$i<count($_POST['id']);$i++) {
+		$form_delete[]=$_POST['id'][$i];
+	}
+	$form_info=implode(',',$form_delete);
+	$form_send_data_message='?form_delete='.($form_info);
+} elseif (isset($_GET['outbox'])) {
+	$form_delete_outbox=array();
+	$form_delete_outbox[]=$_POST['action'];
+	for ($i=0;$i<count($_POST['out']);$i++) {
+		$form_delete_outbox[]=$_POST['out'][$i];
+	}
+	$form_info_outbox=implode(',',$form_delete_outbox);
 	$form_send_data_message='?form_delete_outbox='.($form_info_outbox);
-}
-$form_url_send=isset($form_send_data_message) ? $form_send_data_message :'';
-?>
-<div id="container-9">
-    <ul>
-        <li><a href="data_personal.inc.php"><span><?php Display :: display_icon('profile.png',get_lang('PersonalData')); echo '&nbsp;&nbsp;'.get_lang('PersonalData'); ?></span></a></li>
+}
+$form_url_send=isset($form_send_data_message) ? $form_send_data_message :'';
+?>
+<div id="container-9">
+    <ul>
+        <li><a href="data_personal.inc.php"><span><?php Display :: display_icon('profile.png',get_lang('PersonalData')); echo '&nbsp;&nbsp;'.get_lang('PersonalData'); ?></span></a></li>
         <?php
        	if (api_get_setting('allow_message_tool')=='true') {
        	?>
-        <li><a href="../messages/inbox.php<?php echo $form_url_send; ?>"><span><?php Display :: display_icon('inbox.png',get_lang('Inbox')); echo '&nbsp;&nbsp;'.get_lang('Inbox');?></span></a></li>
-        <li><a href="../messages/outbox.php<?php echo $form_url_send; ?>"><span><?php Display :: display_icon('outbox.png',get_lang('Outbox') ); echo '&nbsp;&nbsp;'.get_lang('Outbox');?></span></a></li>
-        <?php }
+        <li><a href="../messages/inbox.php<?php echo $form_url_send; ?>"><span><?php Display :: display_icon('inbox.png',get_lang('Inbox')); echo '&nbsp;&nbsp;'.get_lang('Inbox');?></span></a></li>
+        <li><a href="../messages/outbox.php<?php echo $form_url_send; ?>"><span><?php Display :: display_icon('outbox.png',get_lang('Outbox') ); echo '&nbsp;&nbsp;'.get_lang('Outbox');?></span></a></li>
+        <?php }
   	 	if (api_get_setting('allow_social_tool')=='true') {
-        ?>
-        <li><a href="select_friend_response.php"><span><?php Display :: display_icon('pending_invitation.png',get_lang('PendingInvitations'), array('height'=>'22px')); echo '&nbsp;&nbsp;'.get_lang('PendingInvitations'); ?></span></a></li>
-        <li><a href="contacts.inc.php"><span><?php Display :: display_icon('contacts.png',get_lang('Contacts')); echo '&nbsp;&nbsp;'.get_lang('Contacts'); ?></span></a></li>
-        <li><a href="group_contact.inc.php"><span><?php Display :: display_icon('group_contact.png',get_lang('ContactsGroups')); echo '&nbsp;&nbsp;'.get_lang('ContactsGroups'); ?></span></a></li>
-        <?php
-  	 	}
         ?>
-    </ul>
-    <?php //echo '<div id="show">&nbsp;</div>';?>
-</div>
-<?php
-Display :: display_footer();
-?>
+        <li><a href="select_friend_response.php"><span><?php Display :: display_icon('pending_invitation.png',get_lang('PendingInvitations'), array('height'=>'22px')); echo '&nbsp;&nbsp;'.get_lang('PendingInvitations'); ?></span></a></li>
+        <li><a href="contacts.inc.php"><span><?php Display :: display_icon('contacts.png',get_lang('Contacts')); echo '&nbsp;&nbsp;'.get_lang('Contacts'); ?></span></a></li>
+        <li><a href="group_contact.inc.php"><span><?php Display :: display_icon('group_contact.png',get_lang('ContactsGroups')); echo '&nbsp;&nbsp;'.get_lang('ContactsGroups'); ?></span></a></li>
+        <?php
+  	 	}
+        ?>
+    </ul>
+    <?php //echo '<div id="show">&nbsp;</div>';?>
+</div>
+<?php
+Display :: display_footer();
+?>

+ 25 - 25
main/social/select_options.php

@@ -1,32 +1,32 @@
-<?php
-/* For licensing terms, see /dokeos_license.txt */
-$language_file = array('registration','messages','userInfo','admin');
-$cidReset = true;
-require '../inc/global.inc.php';
-$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-$tbl_my_user = Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_my_user_friend = Database :: get_main_table(TABLE_MAIN_USER_FRIEND);
+<?php
+/* For licensing terms, see /dokeos_license.txt */
+$language_file = array('registration','messages','userInfo','admin');
+$cidReset = true;
+require '../inc/global.inc.php';
+$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+$tbl_my_user = Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_my_user_friend = Database :: get_main_table(TABLE_MAIN_USER_FRIEND);
 $search=Database::escape_string(Security::remove_XSS($_POST['search']));
 $current_date=date('Y-m-d H:i:s',time());
-$html_form='<select id="id_search_name" name="id_search_name" size="8"" style="width:350px;">';
-$user_id = api_get_user_id();
-$is_western_name_order = api_is_western_name_order();
-if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
+$html_form='<select id="id_search_name" name="id_search_name" size="8"" style="width:350px;">';
+$user_id = api_get_user_id();
+$is_western_name_order = api_is_western_name_order();
+if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
 	$sql = 'SELECT DISTINCT u.user_id as id, '.($is_western_name_order ? 'concat(u.firstname," ",u.lastname," ","( ",u.email," )")' : 'concat(u.lastname," ",u.firstname," ","( ",u.email," )")').' as name
-	FROM '.$tbl_my_user_friend.' uf ' .
- 	'INNER JOIN '.$tbl_my_user.' AS u  ON uf.friend_user_id = u.user_id ' .
- 	'WHERE relation_type<>6 AND friend_user_id<>'.(int)$user_id.' AND '.($is_western_name_order ? 'concat(u.firstname, " ", u.lastname)' : 'concat(u.lastname, " ", u.firstname)').' like CONCAT("%","'.$search.'","%") ';
-} elseif (api_get_setting('allow_social_tool')=='false' && api_get_setting('allow_message_tool')=='true') {
-	$valid=api_get_setting('time_limit_whosonline');
-	$sql='SELECT DISTINCT u.user_id as id, '.($is_western_name_order ? 'concat(u.firstname," ",u.lastname," ","( ",u.email," )")' : 'concat(u.lastname," ",u.firstname," ","( ",u.email," )")').' as name
+	FROM '.$tbl_my_user_friend.' uf ' .
+ 	'INNER JOIN '.$tbl_my_user.' AS u  ON uf.friend_user_id = u.user_id ' .
+ 	'WHERE relation_type<>6 AND friend_user_id<>'.(int)$user_id.' AND '.($is_western_name_order ? 'concat(u.firstname, " ", u.lastname)' : 'concat(u.lastname, " ", u.firstname)').' like CONCAT("%","'.$search.'","%") ';
+} elseif (api_get_setting('allow_social_tool')=='false' && api_get_setting('allow_message_tool')=='true') {
+	$valid=api_get_setting('time_limit_whosonline');
+	$sql='SELECT DISTINCT u.user_id as id, '.($is_western_name_order ? 'concat(u.firstname," ",u.lastname," ","( ",u.email," )")' : 'concat(u.lastname," ",u.firstname," ","( ",u.email," )")').' as name
 	 FROM '.$tbl_my_user.' u INNER JOIN '.$track_online_table.' t ON u.user_id=t.login_user_id
 	 WHERE DATE_ADD(login_date,INTERVAL "'.$valid.'" MINUTE) >= "'.$current_date.'" AND '.($is_western_name_order ? 'concat(u.firstname, " ", u.lastname)' : 'concat(u.lastname, " ", u.firstname)').' like CONCAT("%","'.$search.'","%") ';
-}
-
-$res=Database::query($sql,__FILE__,__LINE__);
-while ($row=Database::fetch_array($res,'ASSOC')) {
+}
+
+$res=Database::query($sql,__FILE__,__LINE__);
+while ($row=Database::fetch_array($res,'ASSOC')) {
 	$html_form.='<option value="'.$row['id'].'">'.api_xml_http_response_encode($row['name']).'</option>';
-}
-$html_form.='</select>';
-echo $html_form;
+}
+$html_form.='</select>';
+echo $html_form;
 ?>

+ 77 - 77
main/social/show_search_image.inc.php

@@ -1,84 +1,84 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2009 Dokeos SPRL
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2009 Dokeos SPRL
 	Copyright (c) Julio Montoya Armas
-
-	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
-==============================================================================
-*/
-
-$cidReset = true;
-require '../inc/global.inc.php';
-$language_file = array('registration','messages','userInfo','admin');
-require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-require_once api_get_path(LIBRARY_PATH).'image.lib.php';
-require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
-require_once '../inc/lib/social.lib.php';
-$list_path_friends=array();
-$user_id=api_get_user_id();
-$name_search=Security::remove_XSS($_POST['search_name_q']);
-if (isset($name_search) && $name_search!='undefined') {
+
+	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
+==============================================================================
+*/
+
+$cidReset = true;
+require '../inc/global.inc.php';
+$language_file = array('registration','messages','userInfo','admin');
+require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+require_once api_get_path(LIBRARY_PATH).'image.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once '../inc/lib/social.lib.php';
+$list_path_friends=array();
+$user_id=api_get_user_id();
+$name_search=Security::remove_XSS($_POST['search_name_q']);
+if (isset($name_search) && $name_search!='undefined') {
 	$list_path_friends=UserFriend::get_list_path_web_by_user_id($user_id,null,$name_search);
-} else {
+} else {
 	$list_path_friends=UserFriend::get_list_path_web_by_user_id($user_id);
-}
-$friend_html='';
-$number_of_images=8;
-$number_friends=0;
-$list_friends_id=array();
-$list_friends_dir=array();
-$list_friends_file=array();
+}
+$friend_html='';
+$number_of_images=8;
+$number_friends=0;
+$list_friends_id=array();
+$list_friends_dir=array();
+$list_friends_file=array();
 if (count($list_path_friends)!=0) {
-	for ($z=0;$z<count($list_path_friends['id_friend']);$z++) {
-		$list_friends_id[]  = $list_path_friends['id_friend'][$z]['friend_user_id'];
-		$list_friends_dir[] = $list_path_friends['path_friend'][$z]['dir'];
-		$list_friends_file[]= $list_path_friends['path_friend'][$z]['file'];
-	}
-	$number_friends= count($list_friends_dir);
-	$number_loop   = ($number_friends/$number_of_images);
-	$loop_friends  = ceil($number_loop);
-	$j=0;
+	for ($z=0;$z<count($list_path_friends['id_friend']);$z++) {
+		$list_friends_id[]  = $list_path_friends['id_friend'][$z]['friend_user_id'];
+		$list_friends_dir[] = $list_path_friends['path_friend'][$z]['dir'];
+		$list_friends_file[]= $list_path_friends['path_friend'][$z]['file'];
+	}
+	$number_friends= count($list_friends_dir);
+	$number_loop   = ($number_friends/$number_of_images);
+	$loop_friends  = ceil($number_loop);
+	$j=0;
 	$friend_html.= '<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFC" >';
-	for ($k=0;$k<$loop_friends;$k++) {
-		$friend_html.='<tr><td valign="top">';
-		if ($j==$number_of_images) {
-			$number_of_images=$number_of_images*2;
-		}
-		while ($j<$number_of_images) {
-			if ($list_friends_file[$j]<>"") {
-				$user_info=api_get_user_info($list_friends_id[$j]);
-				$user_name=api_xml_http_response_encode(api_get_person_name($user_info['firstName'], $user_info['lastName']));
-				$friends_profile = UserFriend::get_picture_user($list_friends_id[$j], $list_friends_file[$j], 92);
-				$friend_html.='<div onMouseover="show_icon_delete(this)" onMouseout="hide_icon_delete(this)" class="image-social-content" id=div_'.$list_friends_id[$j].'  >
-				<span><center><img src="'.$friends_profile['file'].'" '.$friends_profile['style'].' id="imgfriend_'.$list_friends_id[$j].'" title="'.$user_name.'" onclick=load_thick(\'qualify_contact.inc.php?path_user="'.urlencode($list_friends_dir[$j].$list_friends_file[$j]).'&amp;id_user="'.$list_friends_id[$j].'"\',"") /></center></span>
-				<img onclick="delete_friend (this)" id=img_'.$list_friends_id[$j].' src="../img/blank.gif" alt="" title=""  class="image-delete" /> <center class="friend">'.$user_name.'</center></div>';
-				/*
-				 * $friend_html.='&nbsp;<div onMouseover="show_icon_delete(this)" onMouseout="hide_icon_delete(this)" class="image-social-content" id=div_'.$list_friends_id[$j].' style="float:left" >
-				 * <img src="'.$list_friends_dir[$j]."/".$list_friends_file[$j].'" width="90" height="110" style="margin-left:3px ;margin-rigth:3px;margin-top:10px;margin-bottom:3px;" id="imgfriend_'.$list_friends_id[$j].'" title="'.$user_name.'" onclick="qualify_friend(this)"/>
-				 * <img onclick="delete_friend (this)" id=img_'.$list_friends_id[$j].' src="../img/blank.gif" alt="" title=""  class="image-delete" /></div>&nbsp;';
-				 */
-			}
-			$j++;
-		}
-		$friend_html.='</td></tr>';
-	}
-	$friend_html.='<br/></table>';
-}
+	for ($k=0;$k<$loop_friends;$k++) {
+		$friend_html.='<tr><td valign="top">';
+		if ($j==$number_of_images) {
+			$number_of_images=$number_of_images*2;
+		}
+		while ($j<$number_of_images) {
+			if ($list_friends_file[$j]<>"") {
+				$user_info=api_get_user_info($list_friends_id[$j]);
+				$user_name=api_xml_http_response_encode(api_get_person_name($user_info['firstName'], $user_info['lastName']));
+				$friends_profile = UserFriend::get_picture_user($list_friends_id[$j], $list_friends_file[$j], 92);
+				$friend_html.='<div onMouseover="show_icon_delete(this)" onMouseout="hide_icon_delete(this)" class="image-social-content" id=div_'.$list_friends_id[$j].'  >
+				<span><center><img src="'.$friends_profile['file'].'" '.$friends_profile['style'].' id="imgfriend_'.$list_friends_id[$j].'" title="'.$user_name.'" onclick=load_thick(\'qualify_contact.inc.php?path_user="'.urlencode($list_friends_dir[$j].$list_friends_file[$j]).'&amp;id_user="'.$list_friends_id[$j].'"\',"") /></center></span>
+				<img onclick="delete_friend (this)" id=img_'.$list_friends_id[$j].' src="../img/blank.gif" alt="" title=""  class="image-delete" /> <center class="friend">'.$user_name.'</center></div>';
+				/*
+				 * $friend_html.='&nbsp;<div onMouseover="show_icon_delete(this)" onMouseout="hide_icon_delete(this)" class="image-social-content" id=div_'.$list_friends_id[$j].' style="float:left" >
+				 * <img src="'.$list_friends_dir[$j]."/".$list_friends_file[$j].'" width="90" height="110" style="margin-left:3px ;margin-rigth:3px;margin-top:10px;margin-bottom:3px;" id="imgfriend_'.$list_friends_id[$j].'" title="'.$user_name.'" onclick="qualify_friend(this)"/>
+				 * <img onclick="delete_friend (this)" id=img_'.$list_friends_id[$j].' src="../img/blank.gif" alt="" title=""  class="image-delete" /></div>&nbsp;';
+				 */
+			}
+			$j++;
+		}
+		$friend_html.='</td></tr>';
+	}
+	$friend_html.='<br/></table>';
+}
 echo $friend_html;
 ?>

+ 318 - 318
main/survey/create_new_survey.php

@@ -1,338 +1,338 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2009 Dokeos SPRL
-
-	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
-==============================================================================
-*/
-
-/**
-*	@package dokeos.survey
-* 	@author unknown, the initial survey that did not make it in 1.8 because of bad code
-* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts (if not all) of the code
-*	@author Julio Montoya Armas <gugli100@gmail.com>, Dokeos: Personality Test modification and rewriting large parts of the code
-* 	@version $Id: create_new_survey.php 22297 2009-07-22 22:08:30Z cfasanando $
-*
-* 	@todo only the available platform languages should be used => need an api get_languages and and api_get_available_languages (or a parameter)
-*/
-
-// name of the language file that needs to be included
-$language_file = 'survey';
-
-// including the global dokeos file
-require_once ('../inc/global.inc.php');
-
-$htmlHeadXtra[] = '<script type="text/javascript" language="javascript">
-
-		function advanced_parameters() {
-			if(document.getElementById(\'options\').style.display == \'none\') {
-					document.getElementById(\'options\').style.display = \'block\';
-					document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
-			} else {
-					document.getElementById(\'options\').style.display = \'none\';
-					document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2004-2009 Dokeos SPRL
+
+	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
+==============================================================================
+*/
+
+/**
+*	@package dokeos.survey
+* 	@author unknown, the initial survey that did not make it in 1.8 because of bad code
+* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts (if not all) of the code
+*	@author Julio Montoya Armas <gugli100@gmail.com>, Dokeos: Personality Test modification and rewriting large parts of the code
+* 	@version $Id: create_new_survey.php 22297 2009-07-22 22:08:30Z cfasanando $
+*
+* 	@todo only the available platform languages should be used => need an api get_languages and and api_get_available_languages (or a parameter)
+*/
+
+// name of the language file that needs to be included
+$language_file = 'survey';
+
+// including the global dokeos file
+require_once ('../inc/global.inc.php');
+
+$htmlHeadXtra[] = '<script type="text/javascript" language="javascript">
+
+		function advanced_parameters() {
+			if(document.getElementById(\'options\').style.display == \'none\') {
+					document.getElementById(\'options\').style.display = \'block\';
+					document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+			} else {
+					document.getElementById(\'options\').style.display = \'none\';
+					document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
 			}
-		}
+		}
 	</script>';
-
-// including additional libraries
-/** @todo check if these are all needed */
-/** @todo check if the starting / is needed. api_get_path probably ends with an / */
-//require_once (api_get_path(LIBRARY_PATH)."/survey.lib.php");
-require_once('survey.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'/fileManage.lib.php');
-require_once (api_get_path(CONFIGURATION_PATH) ."/add_course.conf.php");
-require_once (api_get_path(LIBRARY_PATH)."/add_course.lib.inc.php");
-require_once (api_get_path(LIBRARY_PATH)."/course.lib.php");
-require_once (api_get_path(LIBRARY_PATH)."/groupmanager.lib.php");
-require_once (api_get_path(LIBRARY_PATH)."/usermanager.lib.php");
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-
-// Database table definitions
-$table_survey 				= Database :: get_course_table(TABLE_SURVEY);
-$table_user 				= Database :: get_main_table(TABLE_MAIN_USER);
-$table_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
-$table_course_survey_rel 	= Database :: get_main_table(TABLE_MAIN_COURSE_SURVEY);
-
-/** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
-// if user is not teacher or if he's a coach trying to access an element out of his session
-if (!api_is_allowed_to_edit())
-{
-	if(!api_is_course_coach() || (!empty($_GET['survey_id']) && !api_is_element_in_the_session(TOOL_SURVEY,intval($_GET['survey_id']))))
-	{
-		Display :: display_header();
-		Display :: display_error_message(get_lang('NotAllowed'), false);
-		Display :: display_footer();
-		exit;
-	}
-}
-
-// getting the survey information
-$survey_id  = Security::remove_XSS($_GET['survey_id']);
-$survey_data = survey_manager::get_survey($survey_id);
-
-$urlname = strip_tags(api_substr(api_html_entity_decode($survey_data['title'],ENT_QUOTES,$charset), 0, 40));
-if (api_strlen(strip_tags($survey_data['title'])) > 40) {
-	$urlname .= '...';
-}
-
-// breadcrumbs
-if ($_GET['action'] == 'add')
-{
-	$interbreadcrumb[] = array ("url" => "survey_list.php", "name" => get_lang('SurveyList'));
-	$tool_name = get_lang('CreateNewSurvey');
-}
-if ($_GET['action'] == 'edit' && is_numeric($survey_id))
-{
-	$interbreadcrumb[] = array ("url" => "survey_list.php", "name" => get_lang('SurveyList'));
-	$interbreadcrumb[] = array ("url" => "survey.php?survey_id=".$survey_id, "name" => strip_tags($urlname));
-	$tool_name = get_lang('EditSurvey');
-}
-
-// getting the default values
-if ($_GET['action'] == 'edit' AND isset($survey_id) AND is_numeric($survey_id))
-{
-	$defaults = $survey_data;
-	$defaults['survey_id'] = $survey_id;
-	/*
-	$defaults['survey_share'] = array();
-	$defaults['survey_share']['survey_share'] = $survey_data['survey_share'];
-
-	if (!is_numeric($survey_data['survey_share']) OR $survey_data['survey_share'] == 0)
-	{
-		$form_share_value = 'true';
-	}
-	else
-	{
-		$form_share_value = $defaults['survey_share']['survey_share'];
-	}
-	*/
-
-	$defaults['anonymous'] = $survey_data['anonymous'];
-}
-else
-{
-	$defaults['survey_language'] = $_course['language'];
-	$defaults['start_date'] = date('d-F-Y H:i');
-	$startdateandxdays = time() + 864000; // today + 10 days
-	$defaults['end_date'] = date('d-F-Y H:i', $startdateandxdays);
-	//$defaults['survey_share']['survey_share'] = 0;
-	//$form_share_value = 1;
-	$defaults['anonymous'] = 0;
-}
-
-// initiate the object
-$form = new FormValidator('survey', 'post', api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$survey_id);
-
-$form->addElement('header', '', $tool_name);
-
-// settting the form elements
-if ($_GET['action'] == 'edit' AND isset($survey_id) AND is_numeric($survey_id))
-{
-	$form->addElement('hidden', 'survey_id');
-}
-
-$survey_code = $form->addElement('text', 'survey_code', get_lang('SurveyCode'), array('size' => '20','maxlength'=>'20'));
-//$form->applyFilter('survey_code', 'html_filter');
-
-if ($_GET['action'] == 'edit') {
-	$survey_code->freeze();
-	$form->applyFilter('survey_code', 'api_strtoupper');
+
+// including additional libraries
+/** @todo check if these are all needed */
+/** @todo check if the starting / is needed. api_get_path probably ends with an / */
+//require_once (api_get_path(LIBRARY_PATH)."/survey.lib.php");
+require_once('survey.lib.php');
+require_once (api_get_path(LIBRARY_PATH).'/fileManage.lib.php');
+require_once (api_get_path(CONFIGURATION_PATH) ."/add_course.conf.php");
+require_once (api_get_path(LIBRARY_PATH)."/add_course.lib.inc.php");
+require_once (api_get_path(LIBRARY_PATH)."/course.lib.php");
+require_once (api_get_path(LIBRARY_PATH)."/groupmanager.lib.php");
+require_once (api_get_path(LIBRARY_PATH)."/usermanager.lib.php");
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+
+// Database table definitions
+$table_survey 				= Database :: get_course_table(TABLE_SURVEY);
+$table_user 				= Database :: get_main_table(TABLE_MAIN_USER);
+$table_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
+$table_course_survey_rel 	= Database :: get_main_table(TABLE_MAIN_COURSE_SURVEY);
+
+/** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
+// if user is not teacher or if he's a coach trying to access an element out of his session
+if (!api_is_allowed_to_edit())
+{
+	if(!api_is_course_coach() || (!empty($_GET['survey_id']) && !api_is_element_in_the_session(TOOL_SURVEY,intval($_GET['survey_id']))))
+	{
+		Display :: display_header();
+		Display :: display_error_message(get_lang('NotAllowed'), false);
+		Display :: display_footer();
+		exit;
+	}
+}
+
+// getting the survey information
+$survey_id  = Security::remove_XSS($_GET['survey_id']);
+$survey_data = survey_manager::get_survey($survey_id);
+
+$urlname = strip_tags(api_substr(api_html_entity_decode($survey_data['title'],ENT_QUOTES,$charset), 0, 40));
+if (api_strlen(strip_tags($survey_data['title'])) > 40) {
+	$urlname .= '...';
+}
+
+// breadcrumbs
+if ($_GET['action'] == 'add')
+{
+	$interbreadcrumb[] = array ("url" => "survey_list.php", "name" => get_lang('SurveyList'));
+	$tool_name = get_lang('CreateNewSurvey');
+}
+if ($_GET['action'] == 'edit' && is_numeric($survey_id))
+{
+	$interbreadcrumb[] = array ("url" => "survey_list.php", "name" => get_lang('SurveyList'));
+	$interbreadcrumb[] = array ("url" => "survey.php?survey_id=".$survey_id, "name" => strip_tags($urlname));
+	$tool_name = get_lang('EditSurvey');
+}
+
+// getting the default values
+if ($_GET['action'] == 'edit' AND isset($survey_id) AND is_numeric($survey_id))
+{
+	$defaults = $survey_data;
+	$defaults['survey_id'] = $survey_id;
+	/*
+	$defaults['survey_share'] = array();
+	$defaults['survey_share']['survey_share'] = $survey_data['survey_share'];
+
+	if (!is_numeric($survey_data['survey_share']) OR $survey_data['survey_share'] == 0)
+	{
+		$form_share_value = 'true';
+	}
+	else
+	{
+		$form_share_value = $defaults['survey_share']['survey_share'];
+	}
+	*/
+
+	$defaults['anonymous'] = $survey_data['anonymous'];
+}
+else
+{
+	$defaults['survey_language'] = $_course['language'];
+	$defaults['start_date'] = date('d-F-Y H:i');
+	$startdateandxdays = time() + 864000; // today + 10 days
+	$defaults['end_date'] = date('d-F-Y H:i', $startdateandxdays);
+	//$defaults['survey_share']['survey_share'] = 0;
+	//$form_share_value = 1;
+	$defaults['anonymous'] = 0;
+}
+
+// initiate the object
+$form = new FormValidator('survey', 'post', api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$survey_id);
+
+$form->addElement('header', '', $tool_name);
+
+// settting the form elements
+if ($_GET['action'] == 'edit' AND isset($survey_id) AND is_numeric($survey_id))
+{
+	$form->addElement('hidden', 'survey_id');
 }
-
-$form->addElement('html_editor', 'survey_title', get_lang('SurveyTitle'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '200'));
-$form->addElement('html_editor', 'survey_subtitle', get_lang('SurveySubTitle'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '100', 'ToolbarStartExpanded' => false));
-/*
-$lang_array = api_get_languages();
-foreach ($lang_array['name'] as $key=>$value) {
-	$languages[$lang_array['folder'][$key]] = $value;
-}
-$form->addElement('select', 'survey_language', get_lang('Language'), $languages);
-*/
-$form->addElement('datepickerdate', 'start_date', get_lang('StartDate'), array('form_name'=>'survey'));
-$form->addElement('datepickerdate', 'end_date', get_lang('EndDate'), array('form_name'=>'survey'));
-
-//$group='';
-//$group[] =& HTML_QuickForm::createElement('radio', 'survey_share',null, get_lang('Yes'),$form_share_value);
-/** TODO maybe it is better to change this into false instead see line 95 in survey.lib.php */
-//$group[] =& HTML_QuickForm::createElement('radio', 'survey_share',null, get_lang('No'),0);
-
-//$form->addGroup($group, 'survey_share', get_lang('ShareSurvey'), '&nbsp;');
-$form->addElement('checkbox', 'anonymous', get_lang('Anonymous'));
-$form->addElement('html_editor', 'survey_introduction', get_lang('SurveyIntroduction'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
-$form->addElement('html_editor', 'survey_thanks', get_lang('SurveyThanks'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
-
-
-/*
-// Aditional Parameters
-$form -> addElement('html','<div class="row">
-<div class="label">&nbsp;</div>
-<div class="formw">
-	<a href="javascript://" onclick="if(document.getElementById(\'options\').style.display == \'none\'){document.getElementById(\'options\').style.display = \'block\';}else{document.getElementById(\'options\').style.display = \'none\';}"><img src="../img/add_na.gif" alt="" />'.get_lang('AdvancedParameters').'</a>
-</div>
-</div>');*/
-
-// Personality/Conditional Test Options
-$surveytypes[0] = get_lang('Normal');
-$surveytypes[1] = get_lang('Conditional');
-
-
-if ($_GET['action'] == 'add')
+
+$survey_code = $form->addElement('text', 'survey_code', get_lang('SurveyCode'), array('size' => '20','maxlength'=>'20'));
+//$form->applyFilter('survey_code', 'html_filter');
+
+if ($_GET['action'] == 'edit') {
+	$survey_code->freeze();
+	$form->applyFilter('survey_code', 'api_strtoupper');
+}
+
+$form->addElement('html_editor', 'survey_title', get_lang('SurveyTitle'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '200'));
+$form->addElement('html_editor', 'survey_subtitle', get_lang('SurveySubTitle'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '100', 'ToolbarStartExpanded' => false));
+/*
+$lang_array = api_get_languages();
+foreach ($lang_array['name'] as $key=>$value) {
+	$languages[$lang_array['folder'][$key]] = $value;
+}
+$form->addElement('select', 'survey_language', get_lang('Language'), $languages);
+*/
+$form->addElement('datepickerdate', 'start_date', get_lang('StartDate'), array('form_name'=>'survey'));
+$form->addElement('datepickerdate', 'end_date', get_lang('EndDate'), array('form_name'=>'survey'));
+
+//$group='';
+//$group[] =& HTML_QuickForm::createElement('radio', 'survey_share',null, get_lang('Yes'),$form_share_value);
+/** TODO maybe it is better to change this into false instead see line 95 in survey.lib.php */
+//$group[] =& HTML_QuickForm::createElement('radio', 'survey_share',null, get_lang('No'),0);
+
+//$form->addGroup($group, 'survey_share', get_lang('ShareSurvey'), '&nbsp;');
+$form->addElement('checkbox', 'anonymous', get_lang('Anonymous'));
+$form->addElement('html_editor', 'survey_introduction', get_lang('SurveyIntroduction'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
+$form->addElement('html_editor', 'survey_thanks', get_lang('SurveyThanks'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
+
+
+/*
+// Aditional Parameters
+$form -> addElement('html','<div class="row">
+<div class="label">&nbsp;</div>
+<div class="formw">
+	<a href="javascript://" onclick="if(document.getElementById(\'options\').style.display == \'none\'){document.getElementById(\'options\').style.display = \'block\';}else{document.getElementById(\'options\').style.display = \'none\';}"><img src="../img/add_na.gif" alt="" />'.get_lang('AdvancedParameters').'</a>
+</div>
+</div>');*/
+
+// Personality/Conditional Test Options
+$surveytypes[0] = get_lang('Normal');
+$surveytypes[1] = get_lang('Conditional');
+
+
+if ($_GET['action'] == 'add')
 {
-	$form->addElement('hidden','survey_type',0);
+	$form->addElement('hidden','survey_type',0);
     $form -> addElement('html','<div id="options" style="display: none;">');
-	require_once(api_get_path(LIBRARY_PATH).'surveymanager.lib.php');
+	require_once(api_get_path(LIBRARY_PATH).'surveymanager.lib.php');
 	$survey_tree = new SurveyTree();
 	$list_surveys = $survey_tree->createList($survey_tree->surveylist);
 	$list_surveys[0]='';
-	$form->addElement('select', 'parent_id', get_lang('ParentSurvey'), $list_surveys);
-	$defaults['parent_id']=0;
+	$form->addElement('select', 'parent_id', get_lang('ParentSurvey'), $list_surveys);
+	$defaults['parent_id']=0;
 }
-
-if ($survey_data['survey_type']==1 || $_GET['action'] == 'add' )
-{
-	$form->addElement('checkbox', 'one_question_per_page', get_lang('OneQuestionPerPage'));
-	$form->addElement('checkbox', 'shuffle', get_lang('ActivateShuffle'));
-}
-
-if ((isset($_GET['action']) && $_GET['action'] == 'edit') && !empty($survey_id) )
+
+if ($survey_data['survey_type']==1 || $_GET['action'] == 'add' )
+{
+	$form->addElement('checkbox', 'one_question_per_page', get_lang('OneQuestionPerPage'));
+	$form->addElement('checkbox', 'shuffle', get_lang('ActivateShuffle'));
+}
+
+if ((isset($_GET['action']) && $_GET['action'] == 'edit') && !empty($survey_id) )
 {
-	if ($survey_data['anonymous']==0  ) {
-		// Aditional Parameters
-		$form -> addElement('html','<div class="row">
-		<div class="label">
-			<a href="javascript: void(0);" onclick="javascript: advanced_parameters();" ><span id="plus_minus">&nbsp;'.Display::return_icon('div_show.gif',null,array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'</span></a>
-		</div>
-		<div class="formw">
+	if ($survey_data['anonymous']==0  ) {
+		// Aditional Parameters
+		$form -> addElement('html','<div class="row">
+		<div class="label">
+			<a href="javascript: void(0);" onclick="javascript: advanced_parameters();" ><span id="plus_minus">&nbsp;'.Display::return_icon('div_show.gif',null,array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'</span></a>
+		</div>
+		<div class="formw">
 			&nbsp;
-		</div>
-		</div>');
+		</div>
+		</div>');
 		$form -> addElement('html','<div id="options" style="display:none">');
-		$form->addElement('checkbox', 'show_form_profile', get_lang('ShowFormProfile'),'','onclick="javascript:if(this.checked==true){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"');
-
-		if ($survey_data['show_form_profile']== 1) {
-		$form -> addElement('html','<div id="options_field" style="display:block">');
-		} else {
-			$form -> addElement('html','<div id="options_field" style="display:none">');
-		}
-
-		$field_list=SurveyUtil::make_field_list();
-		if (is_array ($field_list))
-		{
+		$form->addElement('checkbox', 'show_form_profile', get_lang('ShowFormProfile'),'','onclick="javascript:if(this.checked==true){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"');
+
+		if ($survey_data['show_form_profile']== 1) {
+		$form -> addElement('html','<div id="options_field" style="display:block">');
+		} else {
+			$form -> addElement('html','<div id="options_field" style="display:none">');
+		}
+
+		$field_list=SurveyUtil::make_field_list();
+		if (is_array ($field_list))
+		{
 			//TODO hide and show the list in a fancy DIV
-			foreach ($field_list  as $key=> $field)
-			{
-				if ($field['visibility']==1)
-				{
+			foreach ($field_list  as $key=> $field)
+			{
+				if ($field['visibility']==1)
+				{
 					$form->addElement('checkbox', 'profile_'.$key, ' ','&nbsp;&nbsp;'.$field['name'] );
-					$input_name_list.= 'profile_'.$key.',';
-				}
-			}
-			// necesary to know the fields
-			$form->addElement('hidden', 'input_name_list', $input_name_list );
+					$input_name_list.= 'profile_'.$key.',';
+				}
+			}
+			// necesary to know the fields
+			$form->addElement('hidden', 'input_name_list', $input_name_list );
 
 			//set defaults form fields
-			if ($survey_data['form_fields'])
-			{
-				$form_fields=explode('@',$survey_data['form_fields']);
-				foreach($form_fields as $field)
-				{
-					$field_value=explode(':',$field);
-					if ($field_value[0]!='' && $field_value[1]!= '')
-					{
-						$defaults[$field_value[0]]=$field_value[1];
-					}
-				}
-			}
+			if ($survey_data['form_fields'])
+			{
+				$form_fields=explode('@',$survey_data['form_fields']);
+				foreach($form_fields as $field)
+				{
+					$field_value=explode(':',$field);
+					if ($field_value[0]!='' && $field_value[1]!= '')
+					{
+						$defaults[$field_value[0]]=$field_value[1];
+					}
+				}
+			}
 		}
-		$form->addElement('html', '</div></div>');
-	}
-
-}
-$form -> addElement('html','</div><br />');
-if(isset($_GET['survey_id']) && $_GET['action']=='edit') {
-	$class="save";
-	$text=get_lang('ModifySurvey');
-} else {
-	$class="add";
+		$form->addElement('html', '</div></div>');
+	}
+
+}
+$form -> addElement('html','</div><br />');
+if(isset($_GET['survey_id']) && $_GET['action']=='edit') {
+	$class="save";
+	$text=get_lang('ModifySurvey');
+} else {
+	$class="add";
 	$text=get_lang('CreateSurvey');
-}
-$form->addElement('style_submit_button', 'submit_survey', $text, 'class="'.$class.'"');
-
-// setting the rules
-if ($_GET['action'] == 'add')
-{
-	$form->addRule('survey_code', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
-	$form->addRule('survey_code', '', 'maxlength',20);
-}
-$form->addRule('survey_title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
-$form->addRule('start_date', get_lang('InvalidDate'), 'date');
-$form->addRule('end_date', get_lang('InvalidDate'), 'date');
-$form->addRule(array ('start_date', 'end_date'), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
-
-// setting the default values
-$form->setDefaults($defaults);
-
-// The validation or display
-if( $form->validate() )
-{
-	// exporting the values
-	$values = $form->exportValues();
-	// storing the survey
-	$return = survey_manager::store_survey($values);
+}
+$form->addElement('style_submit_button', 'submit_survey', $text, 'class="'.$class.'"');
+
+// setting the rules
+if ($_GET['action'] == 'add')
+{
+	$form->addRule('survey_code', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
+	$form->addRule('survey_code', '', 'maxlength',20);
+}
+$form->addRule('survey_title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('start_date', get_lang('InvalidDate'), 'date');
+$form->addRule('end_date', get_lang('InvalidDate'), 'date');
+$form->addRule(array ('start_date', 'end_date'), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
+
+// setting the default values
+$form->setDefaults($defaults);
+
+// The validation or display
+if( $form->validate() )
+{
+	// exporting the values
+	$values = $form->exportValues();
+	// storing the survey
+	$return = survey_manager::store_survey($values);
 
 	/*// deleting the shared survey if the survey is getting unshared (this only happens when editing)
-	if (is_numeric($survey_data['survey_share']) AND $values['survey_share']['survey_share'] == 0 AND $values['survey_id']<>'')
-	{
-		survey_manager::delete_survey($survey_data['survey_share'], true);
-	}
-	// storing the already existing questions and options of a survey that gets shared (this only happens when editing)
-	if ($survey_data['survey_share']== 0 AND $values['survey_share']['survey_share'] !== 0 AND $values['survey_id']<>'')
-	{
-		survey_manager::get_complete_survey_structure($return['id']);
-	}
-	*/
-	if($return['type'] == 'error')
-	{
-		// Displaying the header
-		Display::display_header($tool_name);
-
-		// display the error
-		Display::display_error_message(get_lang($return['message']), false);
-
-		// display the form
-		$form->display();
-	}
-	if ($config['survey']['debug'])
-	{
-		// displaying a feedback message
-   		Display::display_confirmation_message($return['message'], false);
-	} else {
-   		// redirecting to the survey page (whilst showing the return message
-   		header('location:survey.php?survey_id='.$return['id'].'&message='.$return['message']);
-	}
-} else {
-	// Displaying the header
-	Display::display_header($tool_name);
-	// Displaying the tool title
-	//api_display_tool_title($tool_name);
-	// display the form
-	$form->display();
-}
-// Footer
-Display :: display_footer();
-?>
+	if (is_numeric($survey_data['survey_share']) AND $values['survey_share']['survey_share'] == 0 AND $values['survey_id']<>'')
+	{
+		survey_manager::delete_survey($survey_data['survey_share'], true);
+	}
+	// storing the already existing questions and options of a survey that gets shared (this only happens when editing)
+	if ($survey_data['survey_share']== 0 AND $values['survey_share']['survey_share'] !== 0 AND $values['survey_id']<>'')
+	{
+		survey_manager::get_complete_survey_structure($return['id']);
+	}
+	*/
+	if($return['type'] == 'error')
+	{
+		// Displaying the header
+		Display::display_header($tool_name);
+
+		// display the error
+		Display::display_error_message(get_lang($return['message']), false);
+
+		// display the form
+		$form->display();
+	}
+	if ($config['survey']['debug'])
+	{
+		// displaying a feedback message
+   		Display::display_confirmation_message($return['message'], false);
+	} else {
+   		// redirecting to the survey page (whilst showing the return message
+   		header('location:survey.php?survey_id='.$return['id'].'&message='.$return['message']);
+	}
+} else {
+	// Displaying the header
+	Display::display_header($tool_name);
+	// Displaying the tool title
+	//api_display_tool_title($tool_name);
+	// display the form
+	$form->display();
+}
+// Footer
+Display :: display_footer();
+?>

+ 173 - 173
main/survey/question.php

@@ -1,201 +1,201 @@
-<?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2008 Dokeos SPRL
-
-	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
-==============================================================================
-*/
-/**
-*	@package dokeos.survey
-* 	@author unknown, the initial survey that did not make it in 1.8 because of bad code
-* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts of the code
-* 	@version $Id: question.php 21734 2009-07-02 17:12:41Z cvargas1 $
-*/
-
-// name of the language file that needs to be included
-$language_file = 'survey';
-
-// including the global dokeos file
-require ('../inc/global.inc.php');
-
-// including additional libraries
-//require_once (api_get_path(LIBRARY_PATH)."/survey.lib.php");
-require_once('survey.lib.php');
-
-$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
-$htmlHeadXtra[] = '<script type="text/javascript">
-						$(document).ready( function() {
-							//Allow dokeos install in IE
-							$("button").click(function() {
-								$("#is_executable").attr("value",$(this).attr("name"));
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos SPRL
+
+	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
+==============================================================================
+*/
+/**
+*	@package dokeos.survey
+* 	@author unknown, the initial survey that did not make it in 1.8 because of bad code
+* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts of the code
+* 	@version $Id: question.php 21734 2009-07-02 17:12:41Z cvargas1 $
+*/
+
+// name of the language file that needs to be included
+$language_file = 'survey';
+
+// including the global dokeos file
+require ('../inc/global.inc.php');
+
+// including additional libraries
+//require_once (api_get_path(LIBRARY_PATH)."/survey.lib.php");
+require_once('survey.lib.php');
+
+$htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
+$htmlHeadXtra[] = '<script type="text/javascript">
+						$(document).ready( function() {
+							//Allow dokeos install in IE
+							$("button").click(function() {
+								$("#is_executable").attr("value",$(this).attr("name"));
 							});
-		 				} ); </script>';
-
-/** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
-if (!api_is_allowed_to_edit(false,true)) {
-	Display :: display_header();
-	Display :: display_error_message(get_lang('NotAllowed'), false);
-	Display :: display_footer();
-	exit;
-}
-
-//Is valid request
-$is_valid_request=$_REQUEST['is_executable'];
-if ($request_index<>$is_valid_request) {
-	if ($request_index=='save_question') {
-		unset($_POST[$request_index]);
-	} elseif ($request_index=='add_answer') {
+		 				} ); </script>';
+
+/** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
+if (!api_is_allowed_to_edit(false,true)) {
+	Display :: display_header();
+	Display :: display_error_message(get_lang('NotAllowed'), false);
+	Display :: display_footer();
+	exit;
+}
+
+//Is valid request
+$is_valid_request=$_REQUEST['is_executable'];
+if ($request_index<>$is_valid_request) {
+	if ($request_index=='save_question') {
 		unset($_POST[$request_index]);
-	} elseif($request_index=='remove_answer') {
+	} elseif ($request_index=='add_answer') {
 		unset($_POST[$request_index]);
-	}
+	} elseif($request_index=='remove_answer') {
+		unset($_POST[$request_index]);
+	}
+}
+
+// Database table definitions
+$table_survey 					= Database :: get_course_table(TABLE_SURVEY);
+$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
+$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
+$table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
+$table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+
+// getting the survey information
+$survey_data = survey_manager::get_survey($_GET['survey_id']);
+if (empty($survey_data)) {
+	Display :: display_header(get_lang('Survey'));
+	Display :: display_error_message(get_lang('InvallidSurvey'), false);
+	Display :: display_footer();
+	exit;
+}
+
+
+$urlname = api_substr(api_html_entity_decode($survey_data['title'],ENT_QUOTES,$charset), 0, 40);
+if (api_strlen(strip_tags($survey_data['title'])) > 40) {
+	$urlname .= '...';
 }
-
-// Database table definitions
-$table_survey 					= Database :: get_course_table(TABLE_SURVEY);
-$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
-$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
-$table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
-$table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-
-// getting the survey information
-$survey_data = survey_manager::get_survey($_GET['survey_id']);
-if (empty($survey_data)) {
-	Display :: display_header(get_lang('Survey'));
-	Display :: display_error_message(get_lang('InvallidSurvey'), false);
-	Display :: display_footer();
-	exit;
-}
-
-
-$urlname = api_substr(api_html_entity_decode($survey_data['title'],ENT_QUOTES,$charset), 0, 40);
-if (api_strlen(strip_tags($survey_data['title'])) > 40) {
-	$urlname .= '...';
-}
-
-if($survey_data['survey_type']==1) {
-	$sql = 'SELECT id FROM '.Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP).' WHERE survey_id = '.(int)$_GET['survey_id'].' LIMIT 1';
-	$rs = Database::query($sql,__FILE__,__LINE__);
-	if(Database::num_rows($rs)===0) {
-		header('Location: survey.php?survey_id='.(int)$_GET['survey_id'].'&message='.'YouNeedToCreateGroups');
+
+if($survey_data['survey_type']==1) {
+	$sql = 'SELECT id FROM '.Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP).' WHERE survey_id = '.(int)$_GET['survey_id'].' LIMIT 1';
+	$rs = Database::query($sql,__FILE__,__LINE__);
+	if(Database::num_rows($rs)===0) {
+		header('Location: survey.php?survey_id='.(int)$_GET['survey_id'].'&message='.'YouNeedToCreateGroups');
 		exit;
-	}
-}
-
-// breadcrumbs
-$interbreadcrumb[] = array ("url" => 'survey_list.php', 'name' => get_lang('SurveyList'));
-$interbreadcrumb[] = array ("url" => 'survey.php?survey_id='.Security::remove_XSS($_GET['survey_id']), 'name' => strip_tags($urlname));
-
-// Tool name
-if ($_GET['action'] == 'add') {
-	$tool_name = get_lang('AddQuestion');
-}
-if ($_GET['action'] == 'edit') {
-	$tool_name = get_lang('EditQuestion');
-}
-
-// the possible question types
-$possible_types = array('personality','yesno', 'multiplechoice', 'multipleresponse', 'open', 'dropdown', 'comment', 'pagebreak', 'percentage', 'score');
-
+	}
+}
+
+// breadcrumbs
+$interbreadcrumb[] = array ("url" => 'survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array ("url" => 'survey.php?survey_id='.Security::remove_XSS($_GET['survey_id']), 'name' => strip_tags($urlname));
+
+// Tool name
+if ($_GET['action'] == 'add') {
+	$tool_name = get_lang('AddQuestion');
+}
+if ($_GET['action'] == 'edit') {
+	$tool_name = get_lang('EditQuestion');
+}
+
+// the possible question types
+$possible_types = array('personality','yesno', 'multiplechoice', 'multipleresponse', 'open', 'dropdown', 'comment', 'pagebreak', 'percentage', 'score');
+
 // actions
-$actions = '<div class="actions">';
-$actions .= '<a href="survey.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.Display::return_icon('back.png',get_lang('BackToSurvey')).get_lang('BackToSurvey').'</a>';
-$actions .= '</div>';
-// checking if it is a valid type
-if (!in_array($_GET['type'], $possible_types))
-{
-	Display :: display_header($tool_name,'Survey');
+$actions = '<div class="actions">';
+$actions .= '<a href="survey.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.Display::return_icon('back.png',get_lang('BackToSurvey')).get_lang('BackToSurvey').'</a>';
+$actions .= '</div>';
+// checking if it is a valid type
+if (!in_array($_GET['type'], $possible_types))
+{
+	Display :: display_header($tool_name,'Survey');
 	echo $actions;
-	Display :: display_error_message(get_lang('TypeDoesNotExist'), false);
-	Display :: display_footer();
-}
-
-// displaying the form for adding or editing the question
-if (empty($_POST['save_question']) && in_array($_GET['type'],$possible_types)) {
-	if (!isset($_POST['save_question'])) {
-		// Displaying the header
+	Display :: display_error_message(get_lang('TypeDoesNotExist'), false);
+	Display :: display_footer();
+}
+
+// displaying the form for adding or editing the question
+if (empty($_POST['save_question']) && in_array($_GET['type'],$possible_types)) {
+	if (!isset($_POST['save_question'])) {
+		// Displaying the header
 		Display::display_header($tool_name,'Survey');
 		echo $actions;
 		$error_message='';
 		// Displys message if exists
 		if (isset($_SESSION['temp_sys_message'])) {
-			$error_message=$_SESSION['temp_sys_message'];
+			$error_message=$_SESSION['temp_sys_message'];
 			unset($_SESSION['temp_sys_message']);
-			if ($error_message=='PleaseEnterAQuestion' || $error_message=='PleasFillAllAnswer'|| $error_message=='PleaseChooseACondition'|| $error_message=='ChooseDifferentCategories') {
+			if ($error_message=='PleaseEnterAQuestion' || $error_message=='PleasFillAllAnswer'|| $error_message=='PleaseChooseACondition'|| $error_message=='ChooseDifferentCategories') {
 				Display::display_error_message(get_lang($error_message), true);
 			}
-		}
-	}
-	$form = new $_GET['type'];
-
-	// The defaults values for the form
-	$form_content['answers'] = array('', '');
-
-	if ($_GET['type'] == 'yesno') {
-		$form_content['answers'][0]=get_lang('Yes');
-		$form_content['answers'][1]=get_lang('No');
-	}
-
-	if ($_GET['type'] == 'personality') {
-		$form_content['answers'][0]=get_lang('1');
-		$form_content['answers'][1]=get_lang('2');
-		$form_content['answers'][2]=get_lang('3');
-		$form_content['answers'][3]=get_lang('4');
-		$form_content['answers'][4]=get_lang('5');
-
-		$form_content['values'][0]=0;
-		$form_content['values'][1]=0;
-		$form_content['values'][2]=1;
-		$form_content['values'][3]=2;
+		}
+	}
+	$form = new $_GET['type'];
+
+	// The defaults values for the form
+	$form_content['answers'] = array('', '');
+
+	if ($_GET['type'] == 'yesno') {
+		$form_content['answers'][0]=get_lang('Yes');
+		$form_content['answers'][1]=get_lang('No');
+	}
+
+	if ($_GET['type'] == 'personality') {
+		$form_content['answers'][0]=get_lang('1');
+		$form_content['answers'][1]=get_lang('2');
+		$form_content['answers'][2]=get_lang('3');
+		$form_content['answers'][3]=get_lang('4');
+		$form_content['answers'][4]=get_lang('5');
+
+		$form_content['values'][0]=0;
+		$form_content['values'][1]=0;
+		$form_content['values'][2]=1;
+		$form_content['values'][3]=2;
 		$form_content['values'][4]=3;
-	}
+	}
 
-	// We are editing a question
-	if (isset($_GET['question_id']) AND !empty($_GET['question_id'])) {
+	// We are editing a question
+	if (isset($_GET['question_id']) AND !empty($_GET['question_id'])) {
 		$form_content = survey_manager::get_question($_GET['question_id']);
-	}
-
-	// an action has been performed (for instance adding a possible answer, moving an answer, ...)
+	}
+
+	// an action has been performed (for instance adding a possible answer, moving an answer, ...)
 	if ($_POST) {
-		$form_content = $_POST;
-		$form_content = $form->handle_action($form_content);
-	}
+		$form_content = $_POST;
+		$form_content = $form->handle_action($form_content);
+	}
 
 	if ($error_message!='') {
-		$form_content['question']=$_SESSION['temp_user_message'];
-		$form_content['answers']=$_SESSION['temp_answers'];
-		$form_content['values']=$_SESSION['temp_values'];
-		$form_content['horizontalvertical'] = $_SESSION['temp_horizontalvertical'];
+		$form_content['question']=$_SESSION['temp_user_message'];
+		$form_content['answers']=$_SESSION['temp_answers'];
+		$form_content['values']=$_SESSION['temp_values'];
+		$form_content['horizontalvertical'] = $_SESSION['temp_horizontalvertical'];
 
 
-		unset($_SESSION['temp_user_message']);
-		unset($_SESSION['temp_answers']);
+		unset($_SESSION['temp_user_message']);
+		unset($_SESSION['temp_answers']);
 		unset($_SESSION['temp_values']);
-		unset($_SESSION['temp_horizontalvertical']);
-	}
+		unset($_SESSION['temp_horizontalvertical']);
+	}
 
-	$form->create_form($form_content);
+	$form->create_form($form_content);
 	$form->render_form();
 } else {
 	$form_content = $_POST;
-	$form = new question();
-	$form->handle_action($form_content);
-}
-
-// Footer
-Display :: display_footer();
-?>
+	$form = new question();
+	$form->handle_action($form_content);
+}
+
+// Footer
+Display :: display_footer();
+?>

+ 189 - 189
main/survey/survey_invitation.php

@@ -1,189 +1,189 @@
-<?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 des Palais 44 Paleizenstraat
-		B-1030 Brussels - Belgium
-		Tel. +32 (2) 211 34 56
-*/
-
-/**
-*	@package dokeos.survey
-* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts of the code
-* 	@version $Id: survey_invite.php 10680 2007-01-11 21:26:23Z pcool $
-*
-* 	@todo the answered column
-*/
-
-// name of the language file that needs to be included
-$language_file = 'survey';
-
-// including the global dokeos file
-require ('../inc/global.inc.php');
-
-// including additional libraries
-//require_once (api_get_path(LIBRARY_PATH)."/survey.lib.php");
-require_once('survey.lib.php');
-require_once (api_get_path(LIBRARY_PATH)."course.lib.php");
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once (api_get_path(LIBRARY_PATH)."mail.lib.inc.php");
-
-/** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
-if (!api_is_allowed_to_edit(false,true))
-{
-	Display :: display_header(get_lang('Survey'));
-	Display :: display_error_message(get_lang('NotAllowed'), false);
-	Display :: display_footer();
-	exit;
-}
-
-// Database table definitions
-$table_survey 					= Database :: get_course_table(TABLE_SURVEY);
-$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
-$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
-$table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
-$table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$table_survey_invitation 		= Database :: get_course_table(TABLE_SURVEY_INVITATION);
-
-$tool_name = get_lang('SurveyInvitations');
-
-
-// getting the survey information
-// We exit here if ther is no valid $_GET parameter
-if (!isset($_GET['survey_id']) OR !is_numeric($_GET['survey_id']))
-{
-	Display :: display_header($tool_name);
-	Display :: display_error_message(get_lang('InvallidSurvey'), false);
-	Display :: display_footer();
-	exit;
-}
-$survey_id = Security::remove_XSS($_GET['survey_id']);
-$survey_data = survey_manager::get_survey($survey_id);
-if (empty($survey_data)) {
-	Display :: display_header($tool_name);
-	Display :: display_error_message(get_lang('InvallidSurvey'), false);
-	Display :: display_footer();
-	exit;
-}
-$urlname =strip_tags(api_substr(api_html_entity_decode($survey_data['title'],ENT_QUOTES,$charset), 0, 40));
-if (api_strlen(strip_tags($survey_data['title'])) > 40) {
-	$urlname .= '...';
-}
-
-//breadcrumbs
-$interbreadcrumb[] = array ('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
-$interbreadcrumb[] = array ('url' => 'survey.php?survey_id='.$survey_id, 'name' => $urlname);
-
-
-// Displaying the header
-Display::display_header($tool_name);
-
-// Checking the parameters
-if (!is_numeric($survey_id))
-{
-	Display::display_error_message(get_lang('Error'), false);
-	Display::display_footer();
-	exit;
-}
-
-// Getting all the people who have filled this survey
-$answered_data = survey_manager::get_people_who_filled_survey($survey_id);
-if ($survey_data['anonymous'] == 1)
-{
-	Display::display_normal_message(get_lang('AnonymousSurveyCannotKnowWhoAnswered').' '.count($answered_data).' '.get_lang('PeopleAnswered'));
-	$answered_data = array();
-}
-
-//
-if (!isset($_GET['view']) OR $_GET['view'] == 'invited')
-{
-	echo get_lang('ViewInvited'). ' | ';
-}
-else
-{
-	echo '	<a href="'.api_get_self().'?survey_id='.$survey_id.'&amp;view=invited">'.get_lang('ViewInvited').'</a> |';
-}
-if ($_GET['view'] == 'answered')
-{
-	echo get_lang('ViewAnswered').' | ';
-}
-else
-{
-	echo '	<a href="'.api_get_self().'?survey_id='.$survey_id.'&amp;view=answered">'.get_lang('ViewAnswered').'</a> |';
-}
-if ($_GET['view'] == 'unanswered')
-{
-	echo get_lang('ViewUnanswered');
-}
-else
-{
-	echo '	<a href="'.api_get_self().'?survey_id='.$survey_id.'&amp;view=unanswered">'.get_lang('ViewUnanswered').'</a>';
-}
-
-// table header
-echo '<table class="data_table">';
-echo '	<tr>';
-echo '		<th>'.get_lang('User').'</th>';
-echo '		<th>'.get_lang('InvitationDate').'</th>';
-echo '		<th>'.get_lang('Answered').'</th>';
-echo '	</tr>';
-
-$sql = "SELECT survey_invitation.*, user.firstname, user.lastname, user.email FROM $table_survey_invitation survey_invitation
-			LEFT JOIN $table_user user ON  survey_invitation.user = user.user_id
-			WHERE survey_invitation.survey_code = '".Database::escape_string($survey_data['code'])."'";
-$res = Database::query($sql, __FILE__, __LINE__);
-while ($row = mysql_fetch_assoc($res))
-{
-	if (!$_GET['view'] OR $_GET['view'] == 'invited' OR ($_GET['view'] == 'answered' AND in_array($row['user'], $answered_data)) OR ($_GET['view'] == 'unanswered' AND !in_array($row['user'], $answered_data)))
-	{
-		echo '<tr>';
-		if (is_numeric($row['user']))
-		{
-			echo '			<td><a href="../user/userInfo.php?editMainUserInfo='.$row['user'].'">'.api_get_person_name($row['firstname'], $row['lastname']).'</a></td>';
-		}
-		else
-		{
-				echo '	<td>'.$row['user'].'</td>';
-		}
-		echo '	<td>'.$row['invitation_date'].'</td>';
-		echo '	<td>';
-		if (in_array($row['user'], $answered_data))
-		{
-			echo '<a href="reporting.php?action=userreport&amp;survey_id='.$survey_id.'&amp;user='.$row['user'].'">'.get_lang('ViewAnswers').'</a>';
-		}
-		else
-		{
-			echo '-';
-		}
-		echo '	</td>';
-		echo '</tr>';
-	}
-}
-// closing the table
-echo '</table>';
-
-// Footer
-Display :: display_footer();
-/**
- * @todo add the additional parameters
- */
-/*
-$table = new SortableTable('survey_invitations', 'get_number_of_survey_invitations', 'get_survey_invitations_data',2);
-$table->set_additional_parameters($parameters);
-$table->set_header(0, get_lang('User'));
-$table->set_header(1, get_lang('InvitationCode'));
-$table->set_header(2, get_lang('InvitationDate'));
-$table->set_header(3, get_lang('Answered'));
-$table->set_column_filter(3, 'SurveyUtil::modify_filter');
-$table->display();
-*/
+<?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 des Palais 44 Paleizenstraat
+		B-1030 Brussels - Belgium
+		Tel. +32 (2) 211 34 56
+*/
+
+/**
+*	@package dokeos.survey
+* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts of the code
+* 	@version $Id: survey_invite.php 10680 2007-01-11 21:26:23Z pcool $
+*
+* 	@todo the answered column
+*/
+
+// name of the language file that needs to be included
+$language_file = 'survey';
+
+// including the global dokeos file
+require ('../inc/global.inc.php');
+
+// including additional libraries
+//require_once (api_get_path(LIBRARY_PATH)."/survey.lib.php");
+require_once('survey.lib.php');
+require_once (api_get_path(LIBRARY_PATH)."course.lib.php");
+require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require_once (api_get_path(LIBRARY_PATH)."mail.lib.inc.php");
+
+/** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
+if (!api_is_allowed_to_edit(false,true))
+{
+	Display :: display_header(get_lang('Survey'));
+	Display :: display_error_message(get_lang('NotAllowed'), false);
+	Display :: display_footer();
+	exit;
+}
+
+// Database table definitions
+$table_survey 					= Database :: get_course_table(TABLE_SURVEY);
+$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
+$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
+$table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
+$table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$table_survey_invitation 		= Database :: get_course_table(TABLE_SURVEY_INVITATION);
+
+$tool_name = get_lang('SurveyInvitations');
+
+
+// getting the survey information
+// We exit here if ther is no valid $_GET parameter
+if (!isset($_GET['survey_id']) OR !is_numeric($_GET['survey_id']))
+{
+	Display :: display_header($tool_name);
+	Display :: display_error_message(get_lang('InvallidSurvey'), false);
+	Display :: display_footer();
+	exit;
+}
+$survey_id = Security::remove_XSS($_GET['survey_id']);
+$survey_data = survey_manager::get_survey($survey_id);
+if (empty($survey_data)) {
+	Display :: display_header($tool_name);
+	Display :: display_error_message(get_lang('InvallidSurvey'), false);
+	Display :: display_footer();
+	exit;
+}
+$urlname =strip_tags(api_substr(api_html_entity_decode($survey_data['title'],ENT_QUOTES,$charset), 0, 40));
+if (api_strlen(strip_tags($survey_data['title'])) > 40) {
+	$urlname .= '...';
+}
+
+//breadcrumbs
+$interbreadcrumb[] = array ('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array ('url' => 'survey.php?survey_id='.$survey_id, 'name' => $urlname);
+
+
+// Displaying the header
+Display::display_header($tool_name);
+
+// Checking the parameters
+if (!is_numeric($survey_id))
+{
+	Display::display_error_message(get_lang('Error'), false);
+	Display::display_footer();
+	exit;
+}
+
+// Getting all the people who have filled this survey
+$answered_data = survey_manager::get_people_who_filled_survey($survey_id);
+if ($survey_data['anonymous'] == 1)
+{
+	Display::display_normal_message(get_lang('AnonymousSurveyCannotKnowWhoAnswered').' '.count($answered_data).' '.get_lang('PeopleAnswered'));
+	$answered_data = array();
+}
+
+//
+if (!isset($_GET['view']) OR $_GET['view'] == 'invited')
+{
+	echo get_lang('ViewInvited'). ' | ';
+}
+else
+{
+	echo '	<a href="'.api_get_self().'?survey_id='.$survey_id.'&amp;view=invited">'.get_lang('ViewInvited').'</a> |';
+}
+if ($_GET['view'] == 'answered')
+{
+	echo get_lang('ViewAnswered').' | ';
+}
+else
+{
+	echo '	<a href="'.api_get_self().'?survey_id='.$survey_id.'&amp;view=answered">'.get_lang('ViewAnswered').'</a> |';
+}
+if ($_GET['view'] == 'unanswered')
+{
+	echo get_lang('ViewUnanswered');
+}
+else
+{
+	echo '	<a href="'.api_get_self().'?survey_id='.$survey_id.'&amp;view=unanswered">'.get_lang('ViewUnanswered').'</a>';
+}
+
+// table header
+echo '<table class="data_table">';
+echo '	<tr>';
+echo '		<th>'.get_lang('User').'</th>';
+echo '		<th>'.get_lang('InvitationDate').'</th>';
+echo '		<th>'.get_lang('Answered').'</th>';
+echo '	</tr>';
+
+$sql = "SELECT survey_invitation.*, user.firstname, user.lastname, user.email FROM $table_survey_invitation survey_invitation
+			LEFT JOIN $table_user user ON  survey_invitation.user = user.user_id
+			WHERE survey_invitation.survey_code = '".Database::escape_string($survey_data['code'])."'";
+$res = Database::query($sql, __FILE__, __LINE__);
+while ($row = mysql_fetch_assoc($res))
+{
+	if (!$_GET['view'] OR $_GET['view'] == 'invited' OR ($_GET['view'] == 'answered' AND in_array($row['user'], $answered_data)) OR ($_GET['view'] == 'unanswered' AND !in_array($row['user'], $answered_data)))
+	{
+		echo '<tr>';
+		if (is_numeric($row['user']))
+		{
+			echo '			<td><a href="../user/userInfo.php?editMainUserInfo='.$row['user'].'">'.api_get_person_name($row['firstname'], $row['lastname']).'</a></td>';
+		}
+		else
+		{
+				echo '	<td>'.$row['user'].'</td>';
+		}
+		echo '	<td>'.$row['invitation_date'].'</td>';
+		echo '	<td>';
+		if (in_array($row['user'], $answered_data))
+		{
+			echo '<a href="reporting.php?action=userreport&amp;survey_id='.$survey_id.'&amp;user='.$row['user'].'">'.get_lang('ViewAnswers').'</a>';
+		}
+		else
+		{
+			echo '-';
+		}
+		echo '	</td>';
+		echo '</tr>';
+	}
+}
+// closing the table
+echo '</table>';
+
+// Footer
+Display :: display_footer();
+/**
+ * @todo add the additional parameters
+ */
+/*
+$table = new SortableTable('survey_invitations', 'get_number_of_survey_invitations', 'get_survey_invitations_data',2);
+$table->set_additional_parameters($parameters);
+$table->set_header(0, get_lang('User'));
+$table->set_header(1, get_lang('InvitationCode'));
+$table->set_header(2, get_lang('InvitationDate'));
+$table->set_header(3, get_lang('Answered'));
+$table->set_column_filter(3, 'SurveyUtil::modify_filter');
+$table->display();
+*/

+ 1 - 1
main/survey/survey_invite.php

@@ -59,7 +59,7 @@ $table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
 $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
 $table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$user_info 			= Database::get_main_table(TABLE_MAIN_SURVEY_REMINDER); // TODO: To be checked. TABLE_MAIN_SURVEY_REMINDER has not been defined.
+$user_info 			= Database::get_main_table(TABLE_MAIN_SURVEY_REMINDER); // TODO: To be checked. TABLE_MAIN_SURVEY_REMINDER has not been defined.
 
 // getting the survey information
 $survey_id = Security::remove_XSS($_GET['survey_id']);

+ 113 - 113
main/template/exampletables.php

@@ -1,145 +1,145 @@
 <?php // $Id: exampletables.php,v 1.2 2006/03/15 14:34:45 pcool Exp $
-/*
+/*
 ==============================================================================
-	Dokeos - elearning and course management software
+	Dokeos - elearning and course management software
 
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Vrije Universiteit Brussel (VUB)
+	Copyright (c) 2004 Dokeos S.A.
+	Copyright (c) 2003 Ghent University (UGent)
+	Copyright (c) 2001 Universite catholique de Louvain (UCL)
+	Copyright (c) Vrije Universiteit Brussel (VUB)
 
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
+	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.
+	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.
+	See the GNU General Public License for more details.
 
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
+	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
 ==============================================================================
-*/
-/**
+*/
+/**
 ==============================================================================
 *	This file is a code template;
-*	copy the code and paste it in a new file to begin your own work.
-*
-*	@package dokeos.plugin
+*	copy the code and paste it in a new file to begin your own work.
+*
+*	@package dokeos.plugin
 ==============================================================================
-*/
+*/
 
-/*
+/*
 ==============================================================================
-		INIT SECTION
+		INIT SECTION
 ==============================================================================
-*/
-
+*/
+
 // global settings initialisation
-// also provides access to main api (inc/lib/main_api.lib.php)
+// also provides access to main api (inc/lib/main_api.lib.php)
 include("../inc/global.inc.php");
-
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
+
+/*
+-----------------------------------------------------------
+	Libraries
+-----------------------------------------------------------
 */
-
-//main_api.lib.php by default included
-//also the display and database libraries are loaded by default
-
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-
+
+//main_api.lib.php by default included
+//also the display and database libraries are loaded by default
+
+/*
+-----------------------------------------------------------
+	Header
+-----------------------------------------------------------
+*/
+
 $nameTools = "Table examples (for developers)"; // title of the page (should come from the language file)
-Display::display_header($nameTools);
-/*
------------------------------------------------------------
-	Constants
------------------------------------------------------------
+Display::display_header($nameTools);
+/*
+-----------------------------------------------------------
+	Constants
+-----------------------------------------------------------
 */
-
-define ("REPEAT_COUNT", "5");
-
-
-/*
+
+define ("REPEAT_COUNT", "5");
+
+
+/*
 ==============================================================================
-		FUNCTIONS
+		FUNCTIONS
 ==============================================================================
-*/
+*/
 
-/*
+/*
 ==============================================================================
-		MAIN CODE
+		MAIN CODE
 ==============================================================================
 */
-
-api_display_tool_title($nameTools);
-
-$row = 0;
-$column_header[$row++] = "Column 1";
-$column_header[$row++] = "Column 2";
-$column_header[$row++] = "Column 3";
-
-/*
-	An important parameter for display_complex_table_header
-	is $properties, an array with elements, all of which have defaults
-
-	"width" - the table width, e.g. "85%"
-	"class" - the class to use for the table, e.g. "class=\"data_table\""
-				by default class is  "class=\"data_table\""
-	"cellpadding" - the extra border in each cell, e.g. "8"
-*/
-
-/*
------------------------------------------------------------
-	Table that hilites
------------------------------------------------------------
+
+api_display_tool_title($nameTools);
+
+$row = 0;
+$column_header[$row++] = "Column 1";
+$column_header[$row++] = "Column 2";
+$column_header[$row++] = "Column 3";
+
+/*
+	An important parameter for display_complex_table_header
+	is $properties, an array with elements, all of which have defaults
+
+	"width" - the table width, e.g. "85%"
+	"class" - the class to use for the table, e.g. "class=\"data_table\""
+				by default class is  "class=\"data_table\""
+	"cellpadding" - the extra border in each cell, e.g. "8"
 */
-
-Display::display_normal_message("The following table hilites on mouseover (hover), this is the Display API default.");
-
-Display::display_complex_table_header($properties, $column_header);
-for ($i = 0; $i < REPEAT_COUNT; $i++)
-{
-	$row = 0;
-	$table_row[$row++] = "First";
-	$table_row[$row++] = "Second";
-	$table_row[$row++] = "Third";
-	Display::display_table_row($bgcolor, $table_row, true);
-}
-Display::display_table_footer();
-
-echo "<br/><br/>";
-
-/*
------------------------------------------------------------
-	Table that alternates row colours
------------------------------------------------------------
+
+/*
+-----------------------------------------------------------
+	Table that hilites
+-----------------------------------------------------------
 */
-Display::display_normal_message("The following table has alternating row colours and no hilite");
-
-$properties["class"] = ""; //no hilite
-$bgcolour = Display::display_complex_table_header($properties, $column_header);
-for ($i = 0; $i < REPEAT_COUNT; $i++)
-{
-	$row = 0;
-	$table_row[$row++] = "First";
-	$table_row[$row++] = "Second";
-	$table_row[$row++] = "Third";
-	$bgcolour = Display::display_table_row($bgcolour, $table_row, true);
-}
-Display::display_table_footer();
-
-/*
+
+Display::display_normal_message("The following table hilites on mouseover (hover), this is the Display API default.");
+
+Display::display_complex_table_header($properties, $column_header);
+for ($i = 0; $i < REPEAT_COUNT; $i++)
+{
+	$row = 0;
+	$table_row[$row++] = "First";
+	$table_row[$row++] = "Second";
+	$table_row[$row++] = "Third";
+	Display::display_table_row($bgcolor, $table_row, true);
+}
+Display::display_table_footer();
+
+echo "<br/><br/>";
+
+/*
+-----------------------------------------------------------
+	Table that alternates row colours
+-----------------------------------------------------------
+*/
+Display::display_normal_message("The following table has alternating row colours and no hilite");
+
+$properties["class"] = ""; //no hilite
+$bgcolour = Display::display_complex_table_header($properties, $column_header);
+for ($i = 0; $i < REPEAT_COUNT; $i++)
+{
+	$row = 0;
+	$table_row[$row++] = "First";
+	$table_row[$row++] = "Second";
+	$table_row[$row++] = "Third";
+	$bgcolour = Display::display_table_row($bgcolour, $table_row, true);
+}
+Display::display_table_footer();
+
+/*
 ==============================================================================
 		FOOTER
 ==============================================================================
 */
-
-Display::display_footer();
+
+Display::display_footer();
 ?>

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů