Browse Source

Feature #272 - The "Documents" tool, part 3: Revision, code conventions and cleaning.

Ivan Tcholakov 15 years ago
parent
commit
ccdbbbb36f

+ 3 - 1
main/document/create_document.php

@@ -172,7 +172,7 @@ $nameTools = get_lang('CreateDocument');
 
 /*	Constants and variables */
 
-$dir = isset($_GET['dir']) ? Security::remove_XSS($_GET['dir']) : Security::remove_XSS($_POST['dir']); // please do not modify this dirname formatting
+$dir = isset($_GET['dir']) ? Security::remove_XSS($_GET['dir']) : Security::remove_XSS($_POST['dir']);
 
 /*	MAIN CODE */
 
@@ -180,6 +180,8 @@ if (api_is_in_group()) {
 	$group_properties = GroupManager::get_group_properties($_SESSION['_gid']);
 }
 
+// Please, do not modify this dirname formatting
+
 if (strstr($dir, '..')) {
 	$dir = '/';
 }

+ 225 - 255
main/document/edit_document.php

@@ -1,37 +1,35 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
-==============================================================================
-* This file allows editing documents.
-*
-* Based on create_document, this file allows
-* - edit name
-* - edit comments
-* - edit metadata (requires a document table entry)
-* - edit html content (only for htm/html files)
-*
-* For all files
-* - show editable name field
-* - show editable comments field
-* Additionally, for html and text files
-* - show RTE
-*
-* Remember, all files and folders must always have an entry in the
-* database, regardless of wether they are visible/invisible, have
-* comments or not.
-*
-* @package dokeos.document
-* @todo improve script structure (FormValidator is used to display form, but
-* not for validation at the moment)
-==============================================================================
-*/
-// name of the language file that needs to be included
+ * This file allows editing documents.
+ *
+ * Based on create_document, this file allows
+ * - edit name
+ * - edit comments
+ * - edit metadata (requires a document table entry)
+ * - edit html content (only for htm/html files)
+ *
+ * For all files
+ * - show editable name field
+ * - show editable comments field
+ * Additionally, for html and text files
+ * - show RTE
+ *
+ * Remember, all files and folders must always have an entry in the
+ * database, regardless of wether they are visible/invisible, have
+ * comments or not.
+ *
+ * @package chamilo.document
+ * @todo improve script structure (FormValidator is used to display form, but
+ * not for validation at the moment)
+ */
+
+// Name of the language file that needs to be included
 $language_file = 'document';
-/*
-------------------------------------------------------------------------------
-	Included libraries
-------------------------------------------------------------------------------
-*/
+
+/*	Included libraries */
+
 require_once '../inc/global.inc.php';
 
 // Template's javascript
@@ -58,7 +56,7 @@ function InnerDialogLoaded()
 		// We need a sure method to locate the frame that contains the online editor.
 		for ( var i = 0, n = window.frames.length ; i < n ; i++ )
 		{
-			if ( window.frames[i].location.toString().indexOf(\'InstanceName=texte\') != -1 )
+			if ( window.frames[i].location.toString().indexOf(\'InstanceName=content\') != -1 )
 			{
 				EditorFrame = window.frames[i] ;
 			}
@@ -79,11 +77,10 @@ function FCKeditor_OnComplete( editorInstance )
 	document.getElementById(\'frmModel\').innerHTML = "<iframe style=\'height: 525px; width: 180px;\' scrolling=\'no\' frameborder=\'0\' src=\''.api_get_path(WEB_LIBRARY_PATH).'fckeditor/editor/fckdialogframe.html \'>";
 }
 
-
 </script>';
 
 $_SESSION['whereami'] = 'document/create';
-$this_section=SECTION_COURSES;
+$this_section = SECTION_COURSES;
 $lib_path = api_get_path(LIBRARY_PATH);
 
 require_once $lib_path.'fileManage.lib.php';
@@ -99,32 +96,32 @@ if (api_is_in_group()) {
 }
 
 $file = $_GET['file'];
-//echo('file: '.$file.'<br>');
-$doc=basename($file);
-//echo('doc: '.$doc.'<br>');
-$dir=Security::remove_XSS($_GET['curdirpath']);
-//echo('dir: '.$dir.'<br>');
+//echo('file: '.$file.'<br />');
+$doc = basename($file);
+//echo('doc: '.$doc.'<br />');
+$dir = Security::remove_XSS($_GET['curdirpath']);
+//echo('dir: '.$dir.'<br />');
 $file_name = $doc;
-//echo('file_name: '.$file_name.'<br>');
+//echo('file_name: '.$file_name.'<br />');
 
 $baseServDir = api_get_path(SYS_COURSE_PATH);
-$baseServUrl = $_configuration['url_append']."/";
-$courseDir   = $_course['path']."/document";
+$baseServUrl = $_configuration['url_append'].'/';
+$courseDir   = $_course['path'].'/document';
 $baseWorkDir = $baseServDir.$courseDir;
 $group_document = false;
 $current_session_id = api_get_session_id();
-$doc_tree= explode('/', $file);
-$count_dir = count($doc_tree) -2; // "2" because at the begin and end there are 2 "/"
+$doc_tree = explode('/', $file);
+$count_dir = count($doc_tree) - 2; // "2" because at the begin and end there are 2 "/"
 // Level correction for group documents.
 if (!empty($group_properties['directory'])) {
 	$count_dir = $count_dir > 0 ? $count_dir - 1 : 0;
 }
-$relative_url='';
-for ($i=0;$i<($count_dir);$i++) {
-	$relative_url.='../';
+$relative_url = '';
+for ($i = 0; $i < ($count_dir); $i++) {
+	$relative_url .= '../';
 }
 
-$is_allowed_to_edit = api_is_allowed_to_edit(null,true);
+$is_allowed_to_edit = api_is_allowed_to_edit(null, true);
 
 $html_editor_config = array(
 	'ToolbarSet' => ($is_allowed_to_edit ? 'Documents' :'DocumentsStudent'),
@@ -139,51 +136,46 @@ $html_editor_config = array(
 	'BaseHref' =>  api_get_path('WEB_COURSE_PATH').$_course['path'].'/document'.$dir
 );
 
-$use_document_title = (api_get_setting('use_document_title')=='true') ? true : false;
-$noPHP_SELF=true;
+$use_document_title = api_get_setting('use_document_title') == 'true';
+$noPHP_SELF = true;
 
-/*
-------------------------------------------------------------------------------
-	Other init code
-------------------------------------------------------------------------------
-*/
+/*	Other initialization code */
 
-/* please do not modify this dirname formatting */
+/* Please, do not modify this dirname formatting */
 
-if (strstr($dir,'..')) {
-	$dir='/';
+if (strstr($dir, '..')) {
+	$dir = '/';
 }
 
 if ($dir[0] == '.') {
-	$dir=substr($dir,1);
+	$dir = substr($dir, 1);
 }
 
 if ($dir[0] != '/') {
-	$dir='/'.$dir;
+	$dir = '/'.$dir;
 }
 
-if ($dir[strlen($dir)-1] != '/') {
-	$dir.='/';
+if ($dir[strlen($dir) - 1] != '/') {
+	$dir .= '/';
 }
 
 $filepath = api_get_path('SYS_COURSE_PATH').$_course['path'].'/document'.$dir;
 
 if (!is_dir($filepath)) {
-	$filepath=api_get_path('SYS_COURSE_PATH').$_course['path'].'/document/';
-	$dir='/';
+	$filepath = api_get_path('SYS_COURSE_PATH').$_course['path'].'/document/';
+	$dir = '/';
 }
 
-/**************************************************/
 $dbTable = Database::get_course_table(TABLE_DOCUMENT);
 
 if (!empty($_SESSION['_gid'])) {
 	$req_gid = '&amp;gidReq='.$_SESSION['_gid'];
-	$interbreadcrumb[]= array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['_gid'], "name"=> get_lang('GroupSpace'));
+	$interbreadcrumb[] = array ('url' => '../group/group_space.php?gidReq='.$_SESSION['_gid'], 'name' => get_lang('GroupSpace'));
 	$group_document = true;
-	$noPHP_SELF=true;
+	$noPHP_SELF = true;
 }
-$my_cur_dir_path=Security::remove_XSS($_GET['curdirpath']);
-$interbreadcrumb[]=array("url"=>"./document.php?curdirpath=".urlencode($my_cur_dir_path).$req_gid, "name"=> get_lang('Documents'));
+$my_cur_dir_path = Security::remove_XSS($_GET['curdirpath']);
+$interbreadcrumb[] = array('url' => './document.php?curdirpath='.urlencode($my_cur_dir_path).$req_gid, 'name' => get_lang('Documents'));
 
 $is_allowedToEdit = is_allowed_to_edit() || $_SESSION['group_member_with_upload_rights'];
 
@@ -191,81 +183,80 @@ if (!$is_allowedToEdit) {
 	api_not_allowed(true);
 }
 
-
 $user_id = api_get_user_id();
 event_access_tool(TOOL_DOCUMENT);
 
 if (!is_allowed_to_edit()) {
-	if (DocumentManager::check_readonly($_course,$user_id,$file)) {
+	if (DocumentManager::check_readonly($_course, $user_id, $file)) {
 		api_not_allowed();
 	}
 }
 
 /* MAIN TOOL CODE */
+
 /* General functions */
+
 /*
 	Workhorse functions
 
 	These do the actual work that is expected from of this tool, other functions
 	are only there to support these ones.
 */
+
 /**
 	This function changes the name of a certain file.
 	It needs no global variables, it takes all info from parameters.
 	It returns nothing.
 */
-function change_name($baseWorkDir, $sourceFile, $renameTo, $dir, $doc) {
-	$file_name_for_change = $baseWorkDir.$dir.$sourceFile;
-	//api_display_debug_info("call my_rename: params $file_name_for_change, $renameTo");
-    	$renameTo = disable_dangerous_file($renameTo); //avoid renaming to .htaccess file
-	$renameTo = my_rename($file_name_for_change, stripslashes($renameTo)); //fileManage API
-
-	if ($renameTo) {
-		if (isset($dir) && $dir != "") {
-			$sourceFile = $dir.$sourceFile;
-			$new_full_file_name = dirname($sourceFile)."/".$renameTo;
+function change_name($base_work_dir, $source_file, $rename_to, $dir, $doc) {
+	$file_name_for_change = $base_work_dir.$dir.$source_file;
+	//api_display_debug_info("call my_rename: params $file_name_for_change, $rename_to");
+    $rename_to = disable_dangerous_file($rename_to); // Avoid renaming to .htaccess file
+	$rename_to = my_rename($file_name_for_change, stripslashes($rename_to)); // fileManage API
+
+	if ($rename_to) {
+		if (isset($dir) && $dir != '') {
+			$source_file = $dir.$source_file;
+			$new_full_file_name = dirname($source_file).'/'.$rename_to;
 		} else {
-			$sourceFile = "/".$sourceFile;
-			$new_full_file_name = "/".$renameTo;
+			$source_file = '/'.$source_file;
+			$new_full_file_name = '/'.$rename_to;
 		}
 
-		update_db_info("update", $sourceFile, $new_full_file_name); //fileManage API
-		$name_changed = get_lang("ElRen");
+		update_db_info('update', $source_file, $new_full_file_name); // fileManage API
+		$name_changed = get_lang('ElRen');
 		$info_message = get_lang('fileModified');
 
-		$GLOBALS['file_name'] = $renameTo;
-		$GLOBALS['doc'] = $renameTo;
+		$GLOBALS['file_name'] = $rename_to;
+		$GLOBALS['doc'] = $rename_to;
 
 		return $info_message;
 	} else {
-		$dialogBox = get_lang('FileExists');
+		$dialogBox = get_lang('FileExists'); // TODO: This variable is not used.
 
-		/* return to step 1 */
-		$rename = $sourceFile;
-		unset($sourceFile);
+		/* Return to step 1 */
+		$rename = $source_file;
+		unset($source_file);
 	}
 }
 
-/*
-------------------------------------------------------------------------------
-	Code to change the comment
-------------------------------------------------------------------------------
+/*	Code to change the comment
 	Step 2. React on POST data
-	(Step 1 see below)
-*/
+	(Step 1 see below) */
+
 if (isset($_POST['newComment'])) {
-	//to try to fix the path if it is wrong
-	$commentPath = str_replace("//", "/", Database::escape_string(Security::remove_XSS($_POST['commentPath'])));
-	$newComment = trim(Database::escape_string(Security::remove_XSS($_POST['newComment']))); // remove spaces
-	$newTitle = trim(Database::escape_string(Security::remove_XSS($_POST['newTitle']))); // remove spaces
-	// Check if there is already a record for this file in the DB
+	// Fixing the path if it is wrong
+	$commentPath = str_replace('//', '/', Database::escape_string(Security::remove_XSS($_POST['commentPath'])));
+	$newComment = trim(Database::escape_string(Security::remove_XSS($_POST['newComment']))); // Remove spaces
+	$newTitle = trim(Database::escape_string(Security::remove_XSS($_POST['newTitle']))); // Remove spaces
+	// Check whether there is already a database record for this file
 	$result = Database::query ("SELECT * FROM $dbTable WHERE path LIKE BINARY '".$commentPath."'");
 	while ($row = Database::fetch_array($result, 'ASSOC')) {
 		$attribute['path'      ] = $row['path' ];
 		$attribute['comment'   ] = $row['title'];
 	}
-	//Determine the correct query to the DB
-	//new code always keeps document in database
+	// Determine the correct query to the DB,
+	// new code always keeps document in database
 	$query = "UPDATE $dbTable
 		SET comment='".$newComment."', title='".$newTitle."'
 		WHERE path
@@ -277,34 +268,29 @@ if (isset($_POST['newComment'])) {
 	$info_message = get_lang('fileModified');
 }
 
-/*
-------------------------------------------------------------------------------
-	Code to change the name
-------------------------------------------------------------------------------
+/*	Code to change the name
 	Step 2. react on POST data - change the name
-	(Step 1 see below)
-*/
+	(Step 1 see below) */
 
 if (isset($_POST['renameTo'])) {
 	$info_message = change_name($baseWorkDir, $_GET['sourceFile'], $_POST['renameTo'], $dir, $doc);
 	//assume name change was successful
 }
 
-/*
-------------------------------------------------------------------------------
-	Code to change the comment
-------------------------------------------------------------------------------
-	Step 1. Create dialog box.
-*/
+/*	Code to change the comment
+	Step 1. Create dialog box. */
 
-/** TODO check if this code is still used **/
+/** TODO: Check whether this code is still used **/
 /* Search the old comment */  // RH: metadata: added 'id,'
 $result = Database::query("SELECT id,comment,title FROM $dbTable WHERE path LIKE BINARY '$dir$doc'");
 
-$message = "<i>Debug info</i><br>directory = $dir<br>";
-$message .= "document = $file_name<br>";
-$message .= "comments file = " . $file . "<br>";
-//Display::display_normal_message($message);
+/*
+// Debug info - enable on temporary needs only.
+$message = '<i>Debug info</i><br />directory = '.$dir.'<br />';
+$message .= 'document = '.$file_name.'<br />';
+$message .= 'comments file = '.$file.'<br />';
+Display::display_normal_message($message);
+*/
 
 while ($row = Database::fetch_array($result, 'ASSOC')) {
 	$oldComment = $row['comment'];
@@ -312,111 +298,100 @@ while ($row = Database::fetch_array($result, 'ASSOC')) {
 	$docId = $row['id'];  // RH: metadata
 }
 
-/*
-------------------------------------------------------------------------------
-	WYSIWYG HTML EDITOR - Program Logic
-------------------------------------------------------------------------------
-*/
+/*	WYSIWYG HTML EDITOR - Program Logic */
 
 if ($is_allowedToEdit) {
-	if ($_POST['formSent']==1) {
+	if ($_POST['formSent'] == 1) {
 		if (isset($_POST['renameTo'])) {
-			$_POST['filename']=disable_dangerous_file($_POST['renameTo']);
+			$_POST['filename'] = disable_dangerous_file($_POST['renameTo']);
 
-			$extension=explode('.',$_POST['filename']);
-			$extension=$extension[sizeof($extension)-1];
+			$extension = explode('.', $_POST['filename']);
+			$extension = $extension[sizeof($extension) - 1];
 
-			$_POST['filename']=str_replace('.'.$extension,'',$_POST['filename']);
+			$_POST['filename'] = str_replace('.'.$extension, '', $_POST['filename']);
 		}
 
-		$filename=stripslashes($_POST['filename']);
+		$filename = stripslashes($_POST['filename']);
 
-		$texte=trim(str_replace(array("\r","\n"),"",stripslashes($_POST['texte'])));
-		$texte=Security::remove_XSS($texte,COURSEMANAGERLOWSECURITY);
+		$content = trim(str_replace(array("\r", "\n"), '', stripslashes($_POST['content'])));
+		$content = Security::remove_XSS($content, COURSEMANAGERLOWSECURITY);
 
-		if (!strstr($texte,'/css/frames.css')) {
-			$texte=str_replace('</title></head>','</title><link rel="stylesheet" href="../css/frames.css" type="text/css" /></head>',$texte);
+		if (!strstr($content, '/css/frames.css')) {
+			$content=str_replace('</title></head>', '</title><link rel="stylesheet" href="../css/frames.css" type="text/css" /></head>', $content);
 		}
         if (!ctype_alnum($_POST['extension'])) {
             header('Location: document.php?msg=WeirdExtensionDeniedInPost');
             exit ();
 	    }
         $extension = $_POST['extension'];
-		$file=$dir.$filename.'.'.$extension;
-		$read_only_flag=$_POST['readonly'];
-		if (!empty($read_only_flag)) {
-			$read_only_flag=1;
-		} else {
-			$read_only_flag=0;
-		}
+		$file = $dir.$filename.'.'.$extension;
+		$read_only_flag = $_POST['readonly'];
+		$read_only_flag = empty($read_only_flag) ? 0 : 1;
 
-		$show_edit=$_SESSION['showedit'];
+		$show_edit = $_SESSION['showedit'];
 		//unset($_SESSION['showedit']);
 		api_session_unregister('showedit');
 
-
 		if (empty($filename)) {
-			$msgError=get_lang('NoFileName');
+			$msgError = get_lang('NoFileName');
 		} else {
-			if ($read_only_flag==0) {
-				if (!empty($texte)) {
-					if ($fp = @fopen($filepath.$filename.'.'.$extension,'w')) {
-						$texte = text_filter($texte);
-						//if flv player, change absolute paht temporarely to prevent from erasing it in the following lines
-						$texte = str_replace('flv=h','flv=h|',$texte);
-						$texte = str_replace('flv=/','flv=/|',$texte);
-
-						// change the path of mp3 to absolute
-						// first regexp deals with ../../../ urls
+			if ($read_only_flag == 0) {
+				if (!empty($content)) {
+					if ($fp = @fopen($filepath.$filename.'.'.$extension, 'w')) {
+						$content = text_filter($content);
+						// For flv player, change absolute paht temporarely to prevent from erasing it in the following lines
+						$content = str_replace(array('flv=h', 'flv=/'), array('flv=h|', 'flv=/|'), $content);
+
+						// Change the path of mp3 to absolute
+						// The first regexp deals with ../../../ urls
 						// Disabled by Ivan Tcholakov.
-						//$texte = preg_replace("|(flashvars=\"file=)(\.+/)+|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',$texte);
-						//second regexp deals with audio/ urls
+						//$content = preg_replace("|(flashvars=\"file=)(\.+/)+|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',$content);
+						// The second regexp deals with audio/ urls
 						// Disabled by Ivan Tcholakov.
-						//$texte = preg_replace("|(flashvars=\"file=)([^/]+)/|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',$texte);
+						//$content = preg_replace("|(flashvars=\"file=)([^/]+)/|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',$content);
 
-
- 						fputs($fp,$texte);
+ 						fputs($fp, $content);
 						fclose($fp);
 						if (!is_dir($filepath.'css')) {
 							mkdir($filepath.'css', api_get_permissions_for_new_directories());
-							$doc_id = add_document($_course,$dir.'css','folder',0,'css');
-							api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'],null,null,null,null,$current_session_id);
-							api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'],null,null,null,null,$current_session_id);
+							$doc_id = add_document($_course, $dir.'css', 'folder', 0, 'css');
+							api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'], null, null, null, null, $current_session_id);
+							api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], null, null, null, null, $current_session_id);
 						}
 
 						if (!is_file($filepath.'css/frames.css')) {
 							$platform_theme = api_get_setting('stylesheets');
 							if (file_exists(api_get_path(SYS_CODE_PATH).'css/'.$platform_theme.'/frames.css')) {
-								copy(api_get_path(SYS_CODE_PATH).'css/'.$platform_theme.'/frames.css',$filepath.'css/frames.css');
-								$doc_id=add_document($_course,$dir.'css/frames.css','file',filesize($filepath.'css/frames.css'),'frames.css');
-								api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'],null,null,null,null,$current_session_id);
-								api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'],null,null,null,null,$current_session_id);
+								copy(api_get_path(SYS_CODE_PATH).'css/'.$platform_theme.'/frames.css', $filepath.'css/frames.css');
+								$doc_id = add_document($_course, $dir.'css/frames.css', 'file', filesize($filepath.'css/frames.css'), 'frames.css');
+								api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], null, null, null, null, $current_session_id);
+								api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], null, null, null, null, $current_session_id);
 							}
 						}
 
-						// "WHAT'S NEW" notification: update table item_property (previously last_tooledit)
-						$document_id = DocumentManager::get_document_id($_course,$file);
+						// "WHAT'S NEW" notification: update table item_property
+						$document_id = DocumentManager::get_document_id($_course, $file);
 						if ($document_id) {
 							$file_size = filesize($filepath.$filename.'.'.$extension);
-							update_existing_document($_course, $document_id,$file_size,$read_only_flag);
-							api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $_user['user_id'],null,null,null,null,$current_session_id);
-							//update parent folders
-							item_property_update_on_folder($_course,$dir,$_user['user_id']);
-							$dir = substr($dir,0,-1);
+							update_existing_document($_course, $document_id, $file_size, $read_only_flag);
+							api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $_user['user_id'], null, null, null, null, $current_session_id);
+							// Update parent folders
+							item_property_update_on_folder($_course, $dir,$_user['user_id']);
+							$dir = substr($dir, 0, -1);
 							header('Location: document.php?curdirpath='.urlencode($dir));
 							exit ();
 						} else {
-							//$msgError=get_lang('Impossible');
+							//$msgError = get_lang('Impossible');
 						}
 					} else {
-						$msgError=get_lang('Impossible');
+						$msgError = get_lang('Impossible');
 					}
 				} else {
 					if (is_file($filepath.$filename.'.'.$extension)) {
 						$file_size = filesize($filepath.$filename.'.'.$extension);
-						$document_id = DocumentManager::get_document_id($_course,$file);
+						$document_id = DocumentManager::get_document_id($_course, $file);
 						if ($document_id) {
-							update_existing_document($_course, $document_id,$file_size,$read_only_flag);
+							update_existing_document($_course, $document_id, $file_size, $read_only_flag);
 						}
 					}
 				}
@@ -424,20 +399,20 @@ if ($is_allowedToEdit) {
 
 				if (is_file($filepath.$filename.'.'.$extension)) {
 					$file_size = filesize($filepath.$filename.'.'.$extension);
-					$document_id = DocumentManager::get_document_id($_course,$file);
+					$document_id = DocumentManager::get_document_id($_course, $file);
 
 					if ($document_id) {
-						update_existing_document($_course, $document_id,$file_size,$read_only_flag);
+						update_existing_document($_course, $document_id, $file_size, $read_only_flag);
 					}
 				}
 
-				if (empty($document_id)) { //or if is folder
-					$folder=$_POST['file_path'];
-					$document_id = DocumentManager::get_document_id($_course,$folder);
+				if (empty($document_id)) { // or if is a folder
+					$folder = $_POST['file_path'];
+					$document_id = DocumentManager::get_document_id($_course, $folder);
 
 					if (DocumentManager::is_folder($_course, $document_id)) {
 						if ($document_id) {
-							update_existing_document($_course, $document_id,$file_size,$read_only_flag);
+							update_existing_document($_course, $document_id, $file_size, $read_only_flag);
 						}
 					}
 				}
@@ -446,125 +421,119 @@ if ($is_allowedToEdit) {
 	}
 }
 
-
-//replace relative paths by absolute web paths  (e.g. "./" => "http://www.dokeos.com/courses/ABC/document/")
+// Replace relative paths by absolute web paths (e.g. './' => 'http://www.chamilo.org/courses/ABC/document/')
 if (file_exists($filepath.$doc)) {
-	$extension=explode('.',$doc);
-	$extension=$extension[sizeof($extension)-1];
-	$filename=str_replace('.'.$extension,'',$doc);
-	$extension=strtolower($extension);
-
-	if (in_array($extension,array('html','htm'))) {
-		$texte=file($filepath.$doc);
-		$texte=implode('',$texte);
-		$path_to_append=api_get_path('WEB_COURSE_PATH').$_course['path'].'/document'.$dir;
-		$texte=str_replace('="./','="'.$path_to_append,$texte);
-		$texte=str_replace('mp3player.swf?son=.%2F','mp3player.swf?son='.urlencode($path_to_append),$texte);
+	$extension = explode('.', $doc);
+	$extension = $extension[sizeof($extension) - 1];
+	$filename = str_replace('.'.$extension, '', $doc);
+	$extension = strtolower($extension);
+
+	if (in_array($extension, array('html', 'htm'))) {
+		$content = file($filepath.$doc);
+		$content = implode('', $content);
+		$path_to_append = api_get_path('WEB_COURSE_PATH').$_course['path'].'/document'.$dir;
+		$content = str_replace('="./', '="'.$path_to_append, $content);
+		$content = str_replace('mp3player.swf?son=.%2F', 'mp3player.swf?son='.urlencode($path_to_append), $content);
 	}
 }
 
-/*
-==============================================================================
-		- display user interface
-==============================================================================
-*/
-// display the header
-$nameTools = get_lang("EditDocument") . ': '.$file_name;
-Display::display_header($nameTools,"Doc");
+/*	Display user interface */
 
-// display the tool title
+// Display the header
+$nameTools = get_lang('EditDocument') . ': '.$file_name;
+Display::display_header($nameTools, 'Doc');
+
+// Display the tool title
 //api_display_tool_title($nameTools);
 
 if (isset($msgError)) {
-	Display::display_error_message($msgError); //main API
+	Display::display_error_message($msgError);
 }
 
-if ( isset($info_message)) {
-	Display::display_confirmation_message($info_message); //main API
+if (isset($info_message)) {
+	Display::display_confirmation_message($info_message);
 	if (isset($_POST['origin'])) {
-		$slide_id=$_POST['origin_opt'];
+		$slide_id = $_POST['origin_opt'];
 		nav_to_slideshow($slide_id);
 	}
 }
 
-
-// readonly
+// Readonly
 $sql = 'SELECT id, readonly FROM '.$dbTable.' WHERE path LIKE BINARY "'.$dir.$doc.'"';
 $rs = Database::query($sql);
-$readonly = Database::result($rs,0,'readonly');
-$doc_id = Database::result($rs,0,'id');
+$readonly = Database::result($rs, 0, 'readonly');
+$doc_id = Database::result($rs, 0, 'id');
 
-// owner
+// Owner
 $sql = 'SELECT insert_user_id FROM '.Database::get_course_table(TABLE_ITEM_PROPERTY).'
 		WHERE tool LIKE "document"
 		AND ref='.intval($doc_id);
 $rs = Database::query($sql);
-$owner_id = Database::result($rs,0,'insert_user_id');
+$owner_id = Database::result($rs, 0, 'insert_user_id');
 
 
-if ($owner_id == $_user['user_id'] || api_is_platform_admin() || $is_allowed_to_edit || GroupManager :: is_user_in_group($_user['user_id'],$_SESSION['_gid'] )) {
-	$get_cur_path=Security::remove_XSS($_GET['curdirpath']);
-	$get_file=Security::remove_XSS($_GET['file']);
-	$action =  api_get_self().'?sourceFile='.urlencode($file_name).'&curdirpath='.urlencode($get_cur_path).'&file='.urlencode($get_file).'&doc='.urlencode($doc);
-	$form = new FormValidator('formEdit','post',$action);
+if ($owner_id == $_user['user_id'] || api_is_platform_admin() || $is_allowed_to_edit || GroupManager :: is_user_in_group($_user['user_id'], $_SESSION['_gid'] )) {
+	$get_cur_path = Security::remove_XSS($_GET['curdirpath']);
+	$get_file = Security::remove_XSS($_GET['file']);
+	$action = api_get_self().'?sourceFile='.urlencode($file_name).'&curdirpath='.urlencode($get_cur_path).'&file='.urlencode($get_file).'&doc='.urlencode($doc);
+	$form = new FormValidator('formEdit', 'post', $action);
 
-	// form title
+	// Form title
 	$form->addElement('header', '', $nameTools);
 
 	$renderer = $form->defaultRenderer();
 
-	$form->addElement('hidden','filename');
-	$form->addElement('hidden','extension');
-	$form->addElement('hidden','file_path');
-	$form->addElement('hidden','commentPath');
-	$form->addElement('hidden','showedit');
-	$form->addElement('hidden','origin');
-	$form->addElement('hidden','origin_opt');
+	$form->addElement('hidden', 'filename');
+	$form->addElement('hidden', 'extension');
+	$form->addElement('hidden', 'file_path');
+	$form->addElement('hidden', 'commentPath');
+	$form->addElement('hidden', 'showedit');
+	$form->addElement('hidden', 'origin');
+	$form->addElement('hidden', 'origin_opt');
 
-	if($use_document_title) {
-		$form->add_textfield('newTitle',get_lang('Title'));
+	if ($use_document_title) {
+		$form->add_textfield('newTitle', get_lang('Title'));
 		$defaults['newTitle'] = $oldTitle;
 	} else {
-		$form->addElement('hidden','renameTo');
+		$form->addElement('hidden', 'renameTo');
 	}
 
-	$form->addElement('hidden','formSent');
+	$form->addElement('hidden', 'formSent');
 	$defaults['formSent'] = 1;
 
-
-	$read_only_flag=$_POST['readonly'];
+	$read_only_flag = $_POST['readonly'];
 
 	// Desactivation of IE proprietary commenting tags inside the text before loading it on the online editor.
 	// This fix has been proposed by Hubert Borderiou, see Bug #573, http://support.chamilo.org/issues/573
-	$defaults['texte'] = str_replace('<!--[', '<!-- [', $texte);
+	$defaults['content'] = str_replace('<!--[', '<!-- [', $content);
 
-	//if($extension == 'htm' || $extension == 'html')
+	//if ($extension == 'htm' || $extension == 'html')
 	// HotPotatoes tests are html files, but they should not be edited in order their functionality to be preserved.
 	if (($extension == 'htm' || $extension == 'html') && stripos($dir, '/HotPotatoes_files') === false) {
-		if (empty($readonly) && $readonly==0) {
-			$_SESSION['showedit']=1;
-			$renderer->setElementTemplate('<div class="row"><div class="label" id="frmModel" style="overflow: visible;"></div><div class="formw">{element}</div></div>', 'texte');
-			$form->add_html_editor('texte', '', false, true, $html_editor_config);
+		if (empty($readonly) && $readonly == 0) {
+			$_SESSION['showedit'] = 1;
+			$renderer->setElementTemplate('<div class="row"><div class="label" id="frmModel" style="overflow: visible;"></div><div class="formw">{element}</div></div>', 'content');
+			$form->add_html_editor('content', '', false, true, $html_editor_config);
 		}
 	}
 
-	if(!$group_document) {
+	if (!$group_document) {
 		$metadata_link = '<a href="../metadata/index.php?eid='.urlencode('Document.'.$docId).'">'.get_lang('AddMetadata').'</a>';
-		$form->addElement('static',null,get_lang('Metadata'),$metadata_link);
+		$form->addElement('static', null, get_lang('Metadata'), $metadata_link);
 	}
 
-	$form->addElement('textarea','newComment',get_lang('Comment'),'rows="3" style="width:300px;"');
+	$form->addElement('textarea', 'newComment', get_lang('Comment'), 'rows="3" style="width:300px;"');
 	/*
 	$renderer = $form->defaultRenderer();
 	*/
 	if ($owner_id == $_user['user_id'] || api_is_platform_admin()) {
 		$renderer->setElementTemplate('<div class="row"><div class="label"></div><div class="formw">{element}{label}</div></div>', 'readonly');
-		$checked =&$form->addElement('checkbox','readonly',get_lang('ReadOnly'));
-		if ($readonly==1) {
+		$checked =& $form->addElement('checkbox', 'readonly', get_lang('ReadOnly'));
+		if ($readonly == 1) {
 			$checked->setChecked(true);
 		}
 	}
-	$form->addElement('style_submit_button','submit',get_lang('SaveDocument'), 'class="save"');
+	$form->addElement('style_submit_button', 'submit', get_lang('SaveDocument'), 'class="save"');
 
 	$defaults['filename'] = $filename;
 	$defaults['extension'] = $extension;
@@ -576,20 +545,20 @@ if ($owner_id == $_user['user_id'] || api_is_platform_admin() || $is_allowed_to_
 	$defaults['origin_opt'] = Security::remove_XSS($_GET['origin_opt']);
 
 	$form->setDefaults($defaults);
-	// show templates
+	// Show templates
 	/*
-	$form->addElement('html','<div id="frmModel" style="display:block; height:525px; width:240px; position:absolute; top:115px; left:1px;"></div>');
+	$form->addElement('html', '<div id="frmModel" style="display:block; height:525px; width:240px; position:absolute; top:115px; left:1px;"></div>');
 	*/
-	$origin=Security::remove_XSS($_GET['origin']);
-	if ($origin=='slideshow') {
-		$slide_id=$_GET['origin_opt'];
+	$origin = Security::remove_XSS($_GET['origin']);
+	if ($origin == 'slideshow') {
+		$slide_id = $_GET['origin_opt'];
 		nav_to_slideshow($slide_id);
 	}
 	$form->display();
-	//Display::display_error_message(get_lang('ReadOnlyFile')); //main API
+	//Display::display_error_message(get_lang('ReadOnlyFile'));
 }
 
-//for better navigation when a slide is been commented
+// For better navigation when a slide is been commented
 function nav_to_slideshow($slide_id) {
 	$path = Security::remove_XSS($_GET['curdirpath']);
 	$pathurl = urlencode($path);
@@ -598,4 +567,5 @@ function nav_to_slideshow($slide_id) {
 	//echo '<a href="'.api_get_path(WEB_PATH).'main/document/slideshow.php?slide_id='.$slide_id.'&curdirpath='.Security::remove_XSS(urlencode($_GET['curdirpath'])).'">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('ViewSlideshow')).get_lang('BackTo').' '.get_lang('ViewSlideshow').'</a>';
 	echo '</div>';
 }
-Display::display_footer();
+
+Display::display_footer();

+ 53 - 10
main/document/footerpage.php

@@ -1,18 +1,61 @@
 <?php
+/* For licensing terms, see /license.txt */
+
 /**
-==============================================================================
-*	@package dokeos.document
-==============================================================================
-*/
+ *	@package chamilo.document
+ *	TODO: There is no indication that this file us used for something.
+ */
+
 require_once '../inc/global.inc.php';
-?>
 
-<html>
+$platform_theme = api_get_setting('stylesheets'); 	// plataform's css
+$my_style = $platform_theme;
+
+if (api_get_setting('user_selected_theme') == 'true') {
+	$useri = api_get_user_info();
+	$user_theme = $useri['theme'];
+	if (!empty($user_theme) && $user_theme != $my_style) {
+		$my_style = $user_theme;					// user's css
+	}
+}
+$mycourseid = api_get_course_id();
+if (!empty($mycourseid) && $mycourseid != -1) {
+	if (api_get_setting('allow_course_theme') == 'true') {
+		$mycoursetheme=api_get_course_setting('course_theme');
+
+		if (!empty($mycoursetheme) && $mycoursetheme != -1) {
+			if (!empty($mycoursetheme) && $mycoursetheme != $my_style) {
+				$my_style = $mycoursetheme;			// course's css
+			}
+		}
+
+		$mycourselptheme = api_get_course_setting('allow_learning_path_theme');
+		if (!empty($mycourselptheme) && $mycourselptheme != -1 && $mycourselptheme == 1) {
+
+			global $lp_theme_css; //  it comes from the lp_controller.php
+			global $lp_theme_config; // it comes from the lp_controller.php
+
+			if (!$lp_theme_config) {
+				if ($lp_theme_css != '') {
+					$theme = $lp_theme_css;
+					if (!empty($theme) && $theme != $my_style) {
+						$my_style = $theme;	 // LP's css
+					}
+				}
+			}
+		}
+	}
+}
+
+?><!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="<?php echo api_get_language_isocode(); ?>" lang="<?php echo api_get_language_isocode(); ?>">
 <head>
-<link rel="stylesheet" href="<?php echo $clarolineRepositoryWeb ?>css/default.css" type="text/css">
+<meta http-equiv="Content-Type" content="text/html; charset=<?php echo api_get_system_encoding(); ?>" />
+<link rel="stylesheet" href="<?php echo api_get_path(WEB_CSS_PATH).$my_style; ?>/default.css" type="text/css">
 </head>
-</html>
-
+<body dir="<?php echo api_get_text_direction(); ?>">
 <?php
+
 Display::display_footer();
-?>

+ 23 - 21
main/document/headerpage.php

@@ -1,32 +1,34 @@
 <?php
+/* For licensing terms, see /license.txt */
+
 /**
-==============================================================================
-*	@package dokeos.document
-==============================================================================
-*/
-	// name of the language file that needs to be included
+ *	@package chamilo.document
+ */
+
+// Name of the language file that needs to be included
 $language_file = 'document';
+
 require_once '../inc/global.inc.php';
-$noPHP_SELF=true;
-$header_file= Security::remove_XSS($_GET['file']);
-$path_array=explode('/',str_replace('\\','/',$header_file));
-$path_array = array_map('urldecode',$path_array);
-$header_file=implode('/',$path_array);
+
+$noPHP_SELF = true;
+$header_file = Security::remove_XSS($_GET['file']);
+$path_array = explode('/', str_replace('\\', '/', $header_file));
+$path_array = array_map('urldecode', $path_array);
+$header_file = implode('/', $path_array);
 $nameTools = $header_file;
 
-if(isset($_SESSION['_gid']) && $_SESSION['_gid']!='') {
+if (isset($_SESSION['_gid']) && $_SESSION['_gid'] != '') {
 	$req_gid = '&amp;gidReq='.$_SESSION['_gid'];
-	$interbreadcrumb[]= array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['_gid'], "name"=> get_lang('GroupSpace'));
+	$interbreadcrumb[] = array('url' => '../group/group_space.php?gidReq='.$_SESSION['_gid'], 'name' => get_lang('GroupSpace'));
 }
 
-$interbreadcrumb[]= array ("url"=>"./document.php?curdirpath=".dirname($header_file).$req_gid, "name"=> get_lang('Documents'));
-$interbreadcrumb[]= array ("url"=>"showinframes.php?file=".$header_file, "name"=>$header_file);
-$file_url_sys=api_get_path(SYS_COURSE_PATH).'document'.$header_file;
-$path_info= pathinfo($file_url_sys);
+$interbreadcrumb[] = array('url' => './document.php?curdirpath='.dirname($header_file).$req_gid, 'name' => get_lang('Documents'));
+$interbreadcrumb[] = array('url' => 'showinframes.php?file='.$header_file, 'name' => $header_file);
+$file_url_sys = api_get_path(SYS_COURSE_PATH).'document'.$header_file;
+$path_info = pathinfo($file_url_sys);
 $this_section = SECTION_COURSES;
 
-Display::display_header(null,"Doc");
-echo "<div align=\"center\">";
-$file_url_web=api_get_path('WEB_COURSE_PATH').$_course['path'].'/document'.$header_file."?".api_get_cidreq();
-echo "<a href='".$file_url_web."' target='blank'>".get_lang('_cut_paste_link')."</a></div>";
-?>
+Display::display_header(null, 'Doc');
+echo '<div align="center">';
+$file_url_web = api_get_path('WEB_COURSE_PATH').$_course['path'].'/document'.$header_file.'?'.api_get_cidreq();
+echo '<a href="'.$file_url_web.'" target="blank">'.get_lang('_cut_paste_link').'</a></div>';

+ 61 - 89
main/document/quota.php

@@ -1,131 +1,103 @@
-<?php // $Id: quota.php 21106 2009-05-30 16:25:16Z iflorespaz $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
+<?php
+/* For licensing terms, see /license.txt */
 
-	Copyright (c) 2004 Dokeos S.A.
-	Copyright (c) 2005 Roan Embrechts, Vrije Universiteit Brussel
-
-	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 displays info about the course disk use and quota:
-*	how large (in megabytes) is the documents area of the course,
-*	what is the maximum allowed for this course...
-*
-*	@author Roan Embrechts
-*	@package dokeos.document
-==============================================================================
-*/
-
-// name of the language file that needs to be included
+ *	This script displays info about the course disk use and quota:
+ *	how large (in megabytes) is the documents area of the course,
+ *	what is the maximum allowed for this course...
+ *
+ *	@author Roan Embrechts
+ *	@package chamilo.document
+ */
+
+// Name of the language file that needs to be included
 $language_file = 'document';
 
-// including the global dokeos file
-require_once "../inc/global.inc.php";
+// Including the global dokeos file
+require_once '../inc/global.inc.php';
 
-// including additional libraries
-require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'document.lib.php';
+// Including additional libraries
+require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 
-// some constants and variables
-$courseDir   = $_course['path']."/document";
+// Some constants and variables
+$courseDir = $_course['path'].'/document';
 $maxFilledSpace = DEFAULT_DOCUMENT_QUOTA;
 
-// breadcrumbs
-$interbreadcrumb[]=array("url" => "document.php","name" => get_lang('ToolDocument'));
-
-// title of the page
-$nameTools = get_lang("DocumentQuota");
+// Breadcrumbs
+$interbreadcrumb[] = array('url' => 'document.php','name' => get_lang('ToolDocument'));
 
-// display the header
-Display::display_header($nameTools,"Doc");
+// Title of the page
+$nameTools = get_lang('DocumentQuota');
 
+// Display the header
+Display::display_header($nameTools,'Doc');
 
-
-/*
-==============================================================================
-		FUNCTIONS
-==============================================================================
-*/
+/*	FUNCTIONS */
 
 /**
-*	Here we count 1 kilobyte = 1000 byte, 12 megabyte = 1000 kilobyte.
-*/
-function display_quota($course_quota, $already_consumed_space)
-{
+ *	Here we count 1 kilobyte = 1000 byte, 12 megabyte = 1000 kilobyte.
+ */
+function display_quota($course_quota, $already_consumed_space) {
 	$course_quota_m = round($course_quota / 1000000);
 	$already_consumed_space_m = round($already_consumed_space / 1000000);
-	$message = get_lang("CourseCurrentlyUses") . " <strong>" . $already_consumed_space_m . " megabyte</strong>.<br/>". get_lang("MaximumAllowedQuota") . " <strong>$course_quota_m megabyte</strong>.<br/>";
+	$message = get_lang('CourseCurrentlyUses') . ' <strong>' . $already_consumed_space_m . ' megabyte</strong>.<br />'. get_lang('MaximumAllowedQuota') . ' <strong>'.$course_quota_m.' megabyte</strong>.<br />';
 
 	$percentage = $already_consumed_space / $course_quota * 100;
 	$percentage = round($percentage);
 
-	if ($percentage < 100) $other_percentage = 100 - $percentage;
-	else $other_percentage = 0;
+	$other_percentage = $percentage < 100 ? 100 - $percentage : 0;
 
-	//decide where to place percentage in graph
-	if ($percentage >= 50)
-	{
-		$text_in_filled = "&nbsp;$other_percentage%".
-		$text_in_unfilled = "";
-	}
-	else
-	{
-		$text_in_unfilled = "&nbsp;$other_percentage%".
-		$text_in_filled = "";
+	// Decide where to place percentage in graph
+	if ($percentage >= 50) {
+		$text_in_filled = '&nbsp;'.$other_percentage.'%';
+		$text_in_unfilled = '';
+	} else {
+		$text_in_unfilled = '&nbsp;'.$other_percentage.'%';
+		$text_in_filled = '';
 	}
 
-	//decide the background colour of the graph
-	if ($percentage < 65) $colour = "#00BB00"; //safe - green
-	else if ($percentage < 90) $colour = "#ffd400"; //filling up - yelloworange
-	else $colour = "#DD0000"; //full - red
+	// Decide the background colour of the graph
+	if ($percentage < 65) {
+		$colour = '#00BB00';		// Safe - green
+	} elseif ($percentage < 90) {
+		$colour = '#ffd400';		// Filling up - yelloworange
+	} else {
+		$colour = '#DD0000';		// Full - red
+	}
 
-	//this is used for the table width: a table of only 100 pixels looks too small
+	// This is used for the table width: a table of only 100 pixels looks too small
 	$visual_percentage = 4 * $percentage;
 	$visual_other_percentage = 4 * $other_percentage;
 
-	$message .=  get_lang("PercentageQuotaInUse") . ": <strong>$percentage%</strong>.<br/>" .
-				get_lang("PercentageQuotaFree") . ": <strong>$other_percentage%</strong>.<br>";
-
-	$message .= "<br/><table cellpadding=\"\" cellspacing=\"0\" height=\"40\"><tr>
-				<td bgcolor=\"$colour\" width=\"$visual_percentage\"></td>
-				<td bgcolor=\"Silver\" width=\"$visual_other_percentage\">&nbsp;$other_percentage%</td>
-				</tr></table>";
+	$message .= get_lang('PercentageQuotaInUse') . ': <strong>'.$percentage.'%</strong>.<br />' .
+				get_lang('PercentageQuotaFree') . ': <strong>'.$other_percentage.'%</strong>.<br />';
 
+	$show_percentage = $percentage >= 10 ? '&nbsp;'.$percentage.'%' : '';
+	$message .= '<br /><table cellpadding="" cellspacing="0" height="40"><tr>
+				<td bgcolor="'.$colour.'" width="'.$visual_percentage.'">'.$show_percentage.'</td>
+				<td bgcolor="Silver" width="'.$visual_other_percentage.'">&nbsp;'.$other_percentage.'%</td>
+				</tr></table>';
 	echo $message;
 }
 
-// actions
+// Actions
 echo '<div class="actions">';
 // link back to the documents overview
-echo '<a href="document.php">'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('DocumentsOverview')).get_lang('BackTo').' '.get_lang('DocumentsOverview').'</a>';
+echo '<a href="document.php">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('DocumentsOverview')).get_lang('BackTo').' '.get_lang('DocumentsOverview').'</a>';
 echo '</div>';
 
-// getting the course quota
+// Getting the course quota
 $course_quota = DocumentManager::get_course_quota();
 
-// setting the full path
-$full_path = $baseWorkDir . $courseDir;
+// Setting the full path
+$full_path = $baseWorkDir.$courseDir;
 
-// calculating the total space
+// Calculating the total space
 $already_consumed_space = documents_total_space($_course);
 
-// displaying the quota
+// Displaying the quota
 display_quota($course_quota, $already_consumed_space);
 
-// display the footer
+// Display the footer
 Display::display_footer();
-?>

+ 73 - 106
main/document/showinframes.php

@@ -1,86 +1,56 @@
-<?php // $Id: showinframes.php 22177 2009-07-16 22:30:39Z iflorespaz $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos S.A.
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Hugues Peeters
-	Copyright (c) Roan Embrechts
-
-	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
+/* For licensing terms, see /license.txt */
 
 /**
-==============================================================================
-*	This file will show documents in a separate frame.
-*	We don't like frames, but it was the best of two bad things.
-*
-*	display html files within Dokeos - html files have the Dokeos header.
-*
-*	--- advantages ---
-*	users "feel" like they are in Dokeos,
-*	and they can use the navigation context provided by the header.
-*
-*	--- design ---
-*	a file gets a parameter (an html file)
-*	and shows
-*	- dokeos header
-*	- html file from parameter
-*	- (removed) dokeos footer
-*
-*	@version 0.6
-*	@author Roan Embrechts (roan.embrechts@vub.ac.be)
-*	@package dokeos.document
-==============================================================================
-*/
+ *	This file will show documents in a separate frame.
+ *	We don't like frames, but it was the best of two bad things.
+ *
+ *	display html files within Dokeos - html files have the Dokeos header.
+ *
+ *	--- advantages ---
+ *	users "feel" like they are in Dokeos,
+ *	and they can use the navigation context provided by the header.
+ *
+ *	--- design ---
+ *	a file gets a parameter (an html file)
+ *	and shows
+ *	- dokeos header
+ *	- html file from parameter
+ *	- (removed) dokeos footer
+ *
+ *	@version 0.6
+ *	@author Roan Embrechts (roan.embrechts@vub.ac.be)
+ *	@package dokeos.document
+ */
+
+/*   INITIALIZATION */
 
-/*
-==============================================================================
-	   DOKEOS INIT
-==============================================================================
-*/
 $language_file[] = 'document';
 require_once '../inc/global.inc.php';
-require_once(api_get_path(LIBRARY_PATH).'glossary.lib.php');
+require_once api_get_path(LIBRARY_PATH).'glossary.lib.php';
 
-$language_file = 'document';
-require_once '../inc/global.inc.php';
-$noPHP_SELF=true;
-$header_file= Security::remove_XSS($_GET['file']);
-$path_array=explode('/',str_replace('\\','/',$header_file));
-$path_array = array_map('urldecode',$path_array);
-$header_file=implode('/',$path_array);
+$noPHP_SELF = true;
+$header_file = Security::remove_XSS($_GET['file']);
+$path_array = explode('/', str_replace('\\', '/', $header_file));
+$path_array = array_map('urldecode', $path_array);
+$header_file = implode('/', $path_array);
 $nameTools = $header_file;
 
-if(isset($_SESSION['_gid']) && $_SESSION['_gid']!='') {
+if (isset($_SESSION['_gid']) && $_SESSION['_gid'] != '') {
 	$req_gid = '&amp;gidReq='.$_SESSION['_gid'];
-	$interbreadcrumb[]= array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['_gid'], "name"=> get_lang('GroupSpace'));
+	$interbreadcrumb[] = array('url' => '../group/group_space.php?gidReq='.$_SESSION['_gid'], 'name' => get_lang('GroupSpace'));
 }
 
-$interbreadcrumb[]= array ("url"=>"./document.php?curdirpath=".dirname($header_file).$req_gid, "name"=> get_lang('Documents'));
-$interbreadcrumb[]= array ("url"=>"showinframes.php?file=".$header_file, "name"=>$header_file);
-$file_url_sys=api_get_path(SYS_COURSE_PATH).'document'.$header_file;
-$path_info= pathinfo($file_url_sys);
+$interbreadcrumb[] = array('url' => './document.php?curdirpath='.dirname($header_file).$req_gid, 'name' => get_lang('Documents'));
+$interbreadcrumb[] = array('url' => 'showinframes.php?file='.$header_file, 'name' => $header_file);
+$file_url_sys = api_get_path(SYS_COURSE_PATH).'document'.$header_file;
+$path_info = pathinfo($file_url_sys);
 $this_section = SECTION_COURSES;
 
 /*
 if (!empty($_GET['nopages'])) {
-	$nopages=Security::remove_XSS($_GET['nopages']);
-	if ($nopages==1) {
+	$nopages = Security::remove_XSS($_GET['nopages']);
+	if ($nopages == 1) {
 		require_once api_get_path(INCLUDE_PATH).'reduced_header.inc.php';
 		Display::display_error_message(get_lang('FileNotFound'));
 	}
@@ -90,14 +60,12 @@ if (!empty($_GET['nopages'])) {
 
 $_SESSION['whereami'] = 'document/view';
 
-$interbreadcrumb[]= array ('url'=>'./document.php', 'name'=> get_lang('Documents'));
+$interbreadcrumb[] = array('url' => './document.php', 'name' => get_lang('Documents'));
 $nameTools = get_lang('Documents');
 $file = Security::remove_XSS(urldecode($_GET['file']));
-/*
-==============================================================================
-		Main section
-==============================================================================
-*/
+
+/*	Main section */
+
 header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
 //header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
 header('Last-Modified: Wed, 01 Jan 2100 00:00:00 GMT');
@@ -105,48 +73,47 @@ header('Last-Modified: Wed, 01 Jan 2100 00:00:00 GMT');
 header('Cache-Control: no-cache, must-revalidate');
 header('Pragma: no-cache');
 
-$browser_display_title = "Dokeos Documents - " . Security::remove_XSS($_GET['cidReq']) . " - " . $file;
+$browser_display_title = 'Documents - '.Security::remove_XSS($_GET['cidReq']).' - '.$file;
 
-//only admins get to see the "no frames" link in pageheader.php, so students get a header that's not so high
+// Only admins get to see the "no frames" link in pageheader.php, so students get a header that's not so high
 $frameheight = 135;
-if($is_courseAdmin) {
+if ($is_courseAdmin) {
 	$frameheight = 165;
 }
 
-$file_root=$_course['path'].'/document'.str_replace('%2F', '/',$file);
-$file_url_sys=api_get_path(SYS_COURSE_PATH).$file_root;
-$file_url_web=api_get_path(WEB_COURSE_PATH).$file_root;
-$path_info= pathinfo($file_url_sys);
-
+$file_root = $_course['path'].'/document'.str_replace('%2F', '/', $file);
+$file_url_sys = api_get_path(SYS_COURSE_PATH).$file_root;
+$file_url_web = api_get_path(WEB_COURSE_PATH).$file_root;
+$path_info = pathinfo($file_url_sys);
 
 $js_glossary_in_documents = '';
 if (api_get_setting('show_glossary_in_documents') == 'ismanual') {
 	$js_glossary_in_documents = '	//	    $(document).ready(function() {
-									$.frameReady(function() {   
-								       //  $("<div>I am a div courses</div>").prependTo("body");		     
-								      }, "top.mainFrame",   
-								      { load: [   
+									$.frameReady(function() {
+								       //  $("<div>I am a div courses</div>").prependTo("body");
+								      }, "top.mainFrame",
+								      { load: [
 								      		{type:"script", id:"_fr1", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js"},
 								            {type:"script", id:"_fr2", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.highlight.js"},
 								            {type:"script", id:"_fr3", src:"'.api_get_path(WEB_LIBRARY_PATH).'fckeditor/editor/plugins/glossary/fck_glossary_manual.js"}
-								      	 ] 
-								      }		   
+								      	 ]
+								      }
 								      );
 								    //});';
-} elseif(api_get_setting('show_glossary_in_documents') == 'isautomatic') {
+} elseif (api_get_setting('show_glossary_in_documents') == 'isautomatic') {
 	$js_glossary_in_documents =	'//    $(document).ready(function() {
-								      $.frameReady(function(){   
+								      $.frameReady(function(){
 								       //  $("<div>I am a div courses</div>").prependTo("body");
-								     
-								      }, "top.mainFrame",   
-								      { load: [   
+
+								      }, "top.mainFrame",
+								      { load: [
 								      		{type:"script", id:"_fr1", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js"},
 								            {type:"script", id:"_fr2", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.highlight.js"},
 								            {type:"script", id:"_fr3", src:"'.api_get_path(WEB_LIBRARY_PATH).'fckeditor/editor/plugins/glossary/fck_glossary_automatic.js"}
-								      	 ] 
-								      }								   
+								      	 ]
+								      }
 								      );
-								//   });';	
+								//   });';
 }
 
 $htmlHeadXtra[] = '<script language="javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js"></script>';
@@ -156,9 +123,9 @@ $htmlHeadXtra[] = '<script type="text/javascript">
 <!--
 	var updateContentHeight = function() {
 		HeaderHeight = document.getElementById("header").offsetHeight;
-		FooterHeight = document.getElementById("footer").offsetHeight;		 
+		FooterHeight = document.getElementById("footer").offsetHeight;
 		docHeight = document.body.clientHeight;
-		document.getElementById("mainFrame").style.height = ((docHeight-(parseInt(HeaderHeight)+parseInt(FooterHeight)))-60)+"px";						
+		document.getElementById("mainFrame").style.height = ((docHeight-(parseInt(HeaderHeight)+parseInt(FooterHeight)))-60)+"px";
 	};
 
 	// Fixes the content height of the frame
@@ -169,20 +136,20 @@ $htmlHeadXtra[] = '<script type="text/javascript">
 -->
 </script>';
 
-//Display::display_header($tool_name, "User");
+//Display::display_header($tool_name, 'User');
 
-Display::display_header(null,"Doc");
+Display::display_header(null, 'Doc');
 echo "<div align=\"center\">";
-$file_url_web=api_get_path('WEB_COURSE_PATH').$_course['path'].'/document'.$header_file."?".api_get_cidreq();
-echo "<a href='".$file_url_web."' target='blank'>".get_lang('_cut_paste_link')."</a></div>";
+$file_url_web = api_get_path('WEB_COURSE_PATH').$_course['path'].'/document'.$header_file.'?'.api_get_cidreq();
+echo '<a href="'.$file_url_web.'" target="_blank">'.get_lang('_cut_paste_link').'</a></div>';
 //echo '<div>';
 
-if (file_exists($file_url_sys)) {			
-	echo '<iframe border="0" frameborder="0" scrolling="auto"  style="width:100%;"  id="mainFrame" name="mainFrame" src="'.$file_url_web.'?'.api_get_cidreq().'&rand='.mt_rand(1,10000).'"></iframe>';
-} else {				
+if (file_exists($file_url_sys)) {
+	echo '<iframe border="0" frameborder="0" scrolling="auto"  style="width:100%;"  id="mainFrame" name="mainFrame" src="'.$file_url_web.'?'.api_get_cidreq().'&rand='.mt_rand(1, 10000).'"></iframe>';
+} else {
 	echo '<frame name="mainFrame" id="mainFrame" src=showinframes.php?nopages=1 />';
 }
 
 //echo '</div>';
 
-Display::display_footer();
+Display::display_footer();

+ 21 - 96
main/document/slideshow.inc.php

@@ -1,33 +1,13 @@
 <?php
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004 Dokeos S.A.
-	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.
+/* For licensing terms, see /license.txt */
 
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
 /**
-==============================================================================
-*	@author Patrick Cool
-*	@package dokeos.document
-*	@todo convert comments to be understandable to phpDocumentor
-==============================================================================
-*/
+ *	@author Patrick Cool
+ *	@package ghamilo.document
+ *	@todo convert comments to be understandable to phpDocumentor
+ */
+
 /*
-==============================================================================
 Developped by Patrick Cool
 patrick.cool@UGent.be
 Ghent University
@@ -39,10 +19,9 @@ I wrote this quite quick and didn't think too much about it in advance.
 It is not perfect at all but it is workable and usefull (I think)
 Do not consider this as a powerpoint replacement, although it has
 the same starting point.
-==============================================================================
 */
+
 /*
-==============================================================================
 Description:
 	This is a plugin for the documents tool. It looks for .jpg, .jpeg, .gif, .png
 	files (since these are the files that can be viewed in a browser) and creates
@@ -55,78 +34,25 @@ Description:
 	This file has two large sections.
 	1. code that belongs in document.php, but to avoid clutter I put the code here
 	2. the function resize_image that handles the image resizing
-==============================================================================
-
 */
 
 
 
-// ====================================================================================================
-//				function resize_image($image, $target_width, $target_height, $slideshow=0)
-// ====================================================================================================
-// this functions calculates the resized width and resized heigt according to the source and target widths
-// and heights, height so that no distortions occur
-// parameters
-// $image = the absolute path to the image
-// $target_width = how large do you want your resized image
-// $target_height = how large do you want your resized image
-// $slideshow (default=0) = indicates weither we are generating images for a slideshow or not, t
-//							this overrides the $_SESSION["image_resizing"] a bit so that a thumbnail
-//							view is also possible when you choose not to resize the source images
-
-function resize_image($image, $target_width, $target_height, $slideshow=0) {
-/*  // Replaced fragment of code by Ivan Tcholakov, 04-MAY-2009.
-	// 1. grabbing the image height and width of the original image
-		$image_properties=getimagesize($image);
-		$source_width=$image_properties["0"];
-		$source_height=$image_properties["1"];
-		//print_r($image_properties);
-
-	// 2. calculate the resize factor
-	if ($_SESSION["image_resizing"]=="resizing" or $slideshow==1)
-		{
-		$resize_factor_width=$target_width/$source_width;
-		$resize_factor_height=$target_height/$source_height;
-		//echo $resize_factor_width."//".$resize_factor_height."<br>";
-		} // if ($_SESSION["image_resizing"]=="resizing")
-
-	// 4. calculate the resulting heigt and width
-	if ($_SESSION["image_resizing"]=="resizing" or $slideshow==1)
-		{
-		if ($resize_factor_width<=1 and $resize_factor_height<=1)
-			{
-			if ($resize_factor_width > $resize_factor_height)
-				{
-				$image_width=$target_width;
-				$image_height=ceil($source_height*$resize_factor_width);
-				}
-			if ($resize_factor_width < $resize_factor_height)
-				{
-				$image_width=ceil($source_width*$resize_factor_height);
-				$image_height=$target_height;
-				}
-			else // both resize factors are equal
-				{
-				$image_width=ceil($source_width*$resize_factor_width);
-				$image_height=ceil($source_height*$resize_factor_height);
-				}
-			//echo "image width=".$image_width."<br>";
-			//echo "image height=".$image_height;
-		} //if ($resize_factor_width<=1 and $resize_factor_height<=1)
-	else // no resizing required
-		{
-		$image_width=$source_width;
-		$image_height=$source_height;
-		}
-} //if ($_SESSION["image_resizing"]=="resizing")
-
-// storing the resulting height and width in an array and returning it
-$image_height_width[]=$image_height;
-$image_height_width[]=$image_width;
-return $image_height_width;
-*/
+/**
+ * This function calculates the resized width and resized heigt according to the source and target widths
+ * and heights, height so that no distortions occur
+ * parameters
+ * $image = the absolute path to the image
+ * $target_width = how large do you want your resized image
+ * $target_height = how large do you want your resized image
+ * $slideshow (default=0) = indicates weither we are generating images for a slideshow or not, t
+ *							this overrides the $_SESSION["image_resizing"] a bit so that a thumbnail
+ *							view is also possible when you choose not to resize the source images
+ */
+function resize_image($image, $target_width, $target_height, $slideshow = 0) {
+	// Modifications by Ivan Tcholakov, 04-MAY-2009.
 	$result = array();
-	if ($_SESSION['image_resizing'] == 'resizing' or $slideshow==1) {
+	if ($_SESSION['image_resizing'] == 'resizing' or $slideshow == 1) {
 		$new_sizes = api_resize_image($image, $target_width, $target_height);
 		$result[] = $new_sizes['height'];
 		$result[] = $new_sizes['width'];
@@ -136,4 +62,3 @@ return $image_height_width;
 	}
 	return $result;
 }
-?>

+ 103 - 149
main/document/slideshow.php

@@ -1,97 +1,70 @@
-<?php // $Id: slideshow.php 21107 2009-05-30 16:27:09Z iflorespaz $
-
-/*
-==============================================================================
-	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)
-
-	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.
+<?php
+/* For licensing terms, see /license.txt */
 
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
 /**
-==============================================================================
-*	@author Patrick Cool
-*   @author Julio Montoya Lots of improvements, cleaning, adding security
-*	@package dokeos.document
-==============================================================================
-*/
+ *	@author Patrick Cool
+ *   @author Julio Montoya Lots of improvements, cleaning, adding security
+ *	@package dokeos.document
+ */
+
 /*
-==============================================================================
 Developped by Patrick Cool
 patrick.cool@UGent.be
 Ghent University
 Mai 2004
 http://icto.UGent.be
 
-Improve by Juan Carlos Ra�a Trabado
+Improved by Juan Carlos Raña Trabado
 herodoto@telefonica.net
 January 2008
-
-==============================================================================
 */
-// including the language file
 
-// name of the language file that needs to be included
-$language_file = array ('slideshow', 'document');
+// Language files that need to be included
+$language_file = array('slideshow', 'document');
+
 require_once '../inc/global.inc.php';
+
 $noPHP_SELF = true;
 $path = Security::remove_XSS($_GET['curdirpath']);
 $pathurl = urlencode($path);
 $slide_id = Security::remove_XSS($_GET['slide_id']);
-if ($path <> '/') {
+if ($path != '/') {
 	$folder = $path.'/';
 } else {
 	$folder = '/';
 }
 $sys_course_path = api_get_path(SYS_COURSE_PATH);
 
-// including the functions for the slideshow
+// Including the functions for the slideshow
 require_once 'slideshow.inc.php';
 
-// breadcrumb navigation
-$url = "document.php?curdirpath=".$pathurl;
+// Breadcrumb navigation
+$url = 'document.php?curdirpath='.$pathurl;
 $originaltoolname = get_lang('Documents');
-$interbreadcrumb[] = array ("url" => Security::remove_XSS($url), "name" => $originaltoolname);
+$interbreadcrumb[] = array('url' => Security::remove_XSS($url), 'name' => $originaltoolname);
 
-// because $nametools uses $_SERVER['PHP_SELF'] for the breadcrumbs instead of $_SERVER['REQUEST_URI'], I had to
+// Because $nametools uses $_SERVER['PHP_SELF'] for the breadcrumbs instead of $_SERVER['REQUEST_URI'], I had to
 // bypass the $nametools thing and use <b></b> tags in the $interbreadcrump array
-//$url = "slideshow.php?curdirpath=".$pathurl;
+//$url = 'slideshow.php?curdirpath='.$pathurl;
 $originaltoolname = get_lang('SlideShow');
-//$interbreadcrumb[]= array ("url"=>$url, "name"=>$originaltoolname );
+//$interbreadcrumb[] = array('url'=>$url, 'name' => $originaltoolname);
 
-Display :: display_header($originaltoolname, "Doc");
+Display :: display_header($originaltoolname, 'Doc');
 
-// loading the slides from the session
-if (isset($_SESSION["image_files_only"])) {
-	$image_files_only = $_SESSION["image_files_only"];
+// Loading the slides from the session
+if (isset($_SESSION['image_files_only'])) {
+	$image_files_only = $_SESSION['image_files_only'];
 }
 
-// calculating the current slide, next slide, previous slide and the number of slides
-if ($slide_id <> "all") {
-	if ($slide_id) {
-		$slide = $slide_id;
-	} else {
-		$slide = 0;
-	}
-	$previous_slide = $slide -1;
-	$next_slide = $slide +1;
-} // if ($slide_id<>"all")
+// Calculating the current slide, next slide, previous slide and the number of slides
+if ($slide_id != 'all') {
+	$slide = $slide_id ? $slide_id : 0;
+	$previous_slide = $slide - 1;
+	$next_slide = $slide + 1;
+}
 $total_slides = count($image_files_only);
 ?>
-<script language="JavaScript" type="text/JavaScript">
+<script language="JavaScript" type="text/javascript">
 <!--
 function MM_openBrWindow(theURL,winName,features) { //v2.0
   window.open(theURL,winName,features);
@@ -101,16 +74,16 @@ function MM_openBrWindow(theURL,winName,features) { //v2.0
 
 <div class="actions">
 	<?php
-	// exit the slideshow
+	// Exit the slideshow
 	echo '<a href="document.php?action=exit_slideshow&curdirpath='.$pathurl.'">'.Display::return_icon('back.png').get_lang('BackTo').' '.get_lang('DocumentsOverview').'</a>&nbsp;';
 
-	// show thumbnails
-	if ($slide_id <> "all") {
+	// Show thumbnails
+	if ($slide_id != 'all') {
 		echo '<a href="slideshow.php?slide_id=all&curdirpath='.$pathurl.'"><img src="'.api_get_path(WEB_IMG_PATH).'thumbnails.png" alt="">'.get_lang('_show_thumbnails').'</a>&nbsp;';
 	} else {
 		echo '<img src="'.api_get_path(WEB_IMG_PATH).'thumbnails_na.png" alt="">'.get_lang('_show_thumbnails').'&nbsp;';
 	}
-	// slideshow options
+	// Slideshow options
 	echo '<a href="slideshowoptions.php?curdirpath='.$pathurl.'"><img src="'.api_get_path(WEB_IMG_PATH).'acces_tool.gif" alt="">'.get_lang('_set_slideshow_options').'</a> &nbsp;';
 ?>
 </div>
@@ -118,12 +91,11 @@ function MM_openBrWindow(theURL,winName,features) { //v2.0
 <?php
 echo '<br />';
 
-// =======================================================================
-//				TREATING THE POST DATA FROM SLIDESHOW OPTIONS
-// =======================================================================
-// if we come from slideshowoptions.php we sessionize (new word !!! ;-) the options
-if (isset ($_POST['Submit'])) {
-	// we come from slideshowoptions.php
+/*	TREATING THE POST DATA FROM SLIDESHOW OPTIONS */
+
+// If we come from slideshowoptions.php we sessionize (new word !!! ;-) the options
+if (isset($_POST['Submit'])) {
+	// We come from slideshowoptions.php
 	$_SESSION["image_resizing"] = Security::remove_XSS($_POST['radio_resizing']);
 	if ($_POST['radio_resizing'] == "resizing" && $_POST['width'] != '' && $_POST['height'] != '') {
 		//echo "resizing";
@@ -134,8 +106,7 @@ if (isset ($_POST['Submit'])) {
 		$_SESSION["image_resizing_width"] = null;
 		$_SESSION["image_resizing_height"] = null;
 	}
-} // if ($submit)
-
+}
 
 // The target height and width depends if we choose resizing or no resizing
 if ($_SESSION["image_resizing"] == "resizing") {
@@ -146,87 +117,75 @@ if ($_SESSION["image_resizing"] == "resizing") {
 	$image_height = $source_height;
 }
 
-// =======================================================================
-//						THUMBNAIL VIEW
-// =======================================================================
-// this is for viewing all the images in the slideshow as thumbnails.
+/*	THUMBNAIL VIEW */
+
+// This is for viewing all the images in the slideshow as thumbnails.
 $image_tag = array ();
-if ($slide_id == "all") {
+if ($slide_id == 'all') {
 	$thumbnail_width = 100;
 	$thumbnail_height = 100;
 	$row_items = 4;
 	if (is_array($image_files_only)) {
 		foreach ($image_files_only as $one_image_file) {
-			$image = $sys_course_path.$_course['path']."/document".$folder.$one_image_file;
+			$image = $sys_course_path.$_course['path'].'/document'.$folder.$one_image_file;
 			if (file_exists($image)) {
 				$image_height_width = resize_image($image, $thumbnail_width, $thumbnail_height, 1);
 
 				$image_height = $image_height_width[0];
 				$image_width = $image_height_width[1];
 
-				if ($path and $path !== "/") {
-					$doc_url = $path."/".$one_image_file;
-				} else {
-					$doc_url = $path.$one_image_file;
-				}
-				$image_tag[] = "<img src='download.php?doc_url=".$doc_url."' border='0' width='".$image_width."' height='".$image_height."' title='".$one_image_file."'>";
+				$doc_url = ($path && $path !== '/') ? $path.'/'.$one_image_file : $path.$one_image_file;
+
+				$image_tag[] = '<img src="download.php?doc_url='.$doc_url.'" border="0" width="'.$image_width.'" height="'.$image_height.'" title="'.$one_image_file.'">';
 			}
-		} // foreach ($image_files_only as $one_image_file)
+		}
 	}
-} // if ($slide_id=="all")
+}
 
-// creating the table
-$html_table='';
+// Creating the table
+$html_table = '';
 echo '<table align="center" width="760px" border="0" cellspacing="10">';
 $i = 0;
-$count_image=count($image_tag);
-$number_image=6;
-$number_iteration=ceil($count_image/$number_image);
-$p=0;
-for ($k=0;$k<$number_iteration;$k++) {
+$count_image = count($image_tag);
+$number_image = 6;
+$number_iteration = ceil($count_image/$number_image);
+$p = 0;
+for ($k = 0; $k < $number_iteration; $k++) {
 	echo '<tr height="'.$thumbnail_height.'">';
-	for ($i=0;$i<$number_image;$i++) {
-			if (!is_null($image_tag[$p])) {
-				echo '<td  style="border:1px solid; border-color: #CCCCCC #666666 #666666 #CCCCCC;">';
-				echo '<div align="center"><a href="slideshow.php?slide_id='.$p.'&curdirpath='.$pathurl.' ">'.$image_tag[$p].'</a>';
-				echo '</div></td>';
-			}
-			$p++;
+	for ($i = 0; $i < $number_image; $i++) {
+		if (!is_null($image_tag[$p])) {
+			echo '<td  style="border:1px solid; border-color: #CCCCCC #666666 #666666 #CCCCCC;">';
+			echo '<div align="center"><a href="slideshow.php?slide_id='.$p.'&curdirpath='.$pathurl.' ">'.$image_tag[$p].'</a>';
+			echo '</div></td>';
 		}
+		$p++;
+	}
 	echo '</tr>';
 }
 echo '</table>';
 
-// =======================================================================
-//						ONE AT A TIME VIEW
-// =======================================================================
-// this is for viewing all the images in the slideshow one at a time.
-if ($slide_id !== "all") {
-	$image = $sys_course_path.$_course['path']."/document".$folder.$image_files_only[$slide];
+/*	ONE AT A TIME VIEW */
+
+// This is for viewing all the images in the slideshow one at a time.
+if ($slide_id != 'all') {
+	$image = $sys_course_path.$_course['path'].'/document'.$folder.$image_files_only[$slide];
 	if (file_exists($image)) {
 		$image_height_width = resize_image($image, $target_width, $target_height);
 
 		$image_height = $image_height_width[0];
 		$image_width = $image_height_width[1];
 
-		if ($_SESSION["image_resizing"] == "resizing") {
+		if ($_SESSION['image_resizing'] == 'resizing') {
 			$height_width_tags = 'width="'.$image_width.'" height="'.$image_height.'"';
-
-			/* // Removed by Ivan Tcholakov, 04-MAY-2009. After some changes this fragment of code is not needed anymore.
-			//adjust proportions. Juan Carlos Raсa Trabado TODO: replace resize_image function ?
-			$size = @ getimagesize($image);
-			$height_width_tags = (($size[1] > $image_width) ? 'width="'.$image_width.'"' : '');
-			$height_width_tags = (($size[1] > $image_height) ? 'height="'.$image_height.'"' : '');
-			*/
 		}
 
-		// showing the comment of the image, Patrick Cool, 8 april 2005
-		// this is done really quickly and should be cleaned up a little bit using the API functions
+		// Showing the comment of the image, Patrick Cool, 8 april 2005
+		// This is done really quickly and should be cleaned up a little bit using the API functions
 		$tbl_documents = Database::get_course_table(TABLE_DOCUMENT);
-		if ($path=='/') {
-			$pathpart='/';
+		if ($path == '/') {
+			$pathpart = '/';
 		} else {
-			$pathpart=$path.'/';
+			$pathpart = $path.'/';
 		}
 		$sql = "SELECT * FROM $tbl_documents WHERE path='".Database::escape_string($pathpart.$image_files_only[$slide])."'";
 		$result = Database::query($sql);
@@ -240,13 +199,13 @@ if ($slide_id !== "all") {
 		echo '</tr>';
 		echo '<tr>';
 		echo '<td align="center">';
-		if ($slide < $total_slides -1 and $slide_id <> "all") {
-			echo "<a href='slideshow.php?slide_id=".$next_slide."&curdirpath=$pathurl'>";	
+		if ($slide < $total_slides - 1 && $slide_id != 'all') {
+			echo "<a href='slideshow.php?slide_id=".$next_slide."&curdirpath=$pathurl'>";
 		} else {
 			echo "<a href='slideshow.php?slide_id=0&curdirpath=$pathurl'>";
 		}
 		echo "<img src='download.php?doc_url=$path/".$image_files_only[$slide]."' alt='".$image_files_only[$slide]."' border='0'".$height_width_tags.">";
-		echo "</a>";
+		echo '</a>';
 		echo '</td>';
 		echo '</tr>';
 		echo '<tr>';
@@ -256,31 +215,27 @@ if ($slide_id !== "all") {
 		echo '</tr>';
 		echo '</table>';
 		echo '<table align="center" border="0">';
-		if (api_is_allowed_to_edit(null,true))
-		{
+		if (api_is_allowed_to_edit(null, true)) {
 			echo '<tr>';
 			echo '<td align="center">';
 			echo '<a href="edit_document.php?'.api_get_cidreq().'&curdirpath='.$pathurl.'&amp;origin=slideshow&amp;origin_opt='.$slide_id.'&amp;file='.urlencode($path).'/'.$image_files_only[$slide].'"><img src="../img/edit.gif" border="0" title="'.get_lang('Modify').'" alt="'.get_lang('Modify').'" /></a><br />';
-			$aux= explode(".", htmlspecialchars($image_files_only[$slide]));
-			$ext= $aux[count($aux)-1];
+			$aux = explode('.', htmlspecialchars($image_files_only[$slide]));
+			$ext = $aux[count($aux) - 1];
 			echo $image_files_only[$slide].' <br />';
 			list($width, $high) = getimagesize($image);
 			echo $width.' x '.$high.' <br />';
-			echo round((filesize($image)/1024),2).' KB';
+			echo round((filesize($image)/1024), 2).' KB';
 			echo ' - '.$ext;
 			echo '</td>';
 			echo '</tr>';
 			echo '<tr>';
 			echo '<td align="center">';
-			if($_SESSION['image_resizing']=="resizing")
-			{
-				$resize_info=get_lang('_resizing').'</br>';
-				$resize_widht=$_SESSION["image_resizing_width"].' x ';
-				$resize_height=$_SESSION['image_resizing_height'];
-			}
-			else
-			{
-				$resize_info=get_lang('_no_resizing').'</br>';
+			if ($_SESSION['image_resizing'] == 'resizing') {
+				$resize_info = get_lang('_resizing').'<br />';
+				$resize_widht = $_SESSION["image_resizing_width"].' x ';
+				$resize_height = $_SESSION['image_resizing_height'];
+			} else {
+				$resize_info = get_lang('_no_resizing').'<br />';
 			}
 			echo $resize_info;
 			echo $resize_widht;
@@ -290,53 +245,53 @@ if ($slide_id !== "all") {
 		}
 		echo '</table>';
 
-		echo '<br/>';
+		echo '<br />';
 
-		// back forward buttons
+		// Back forward buttons
 		echo '<table align="center" border="0">';
 		echo '<tr>';
 		echo '<td align="center" >';
-		if ($slide == 0){
+		if ($slide == 0) {
 			$imgp = 'slide_previous_na.png';
 			$first = '<img src="'.api_get_path(WEB_IMG_PATH).'slide_first_na.png">';
 		} else {
 			$imgp = 'slide_previous.png';
 			$first = '<a href="slideshow.php?slide_id=0&curdirpath='.$pathurl.'"><img src="'.api_get_path(WEB_IMG_PATH).'slide_first.png" title="'.get_lang('FirstSlide').'" alt="'.get_lang('FirstSlide').'">&nbsp;&nbsp;</a>';
 		}
-		// first slide
+		// First slide
 		echo $first;
-		// previous slide
+		// Previous slide
 		if ($slide > 0) {
 			echo '<a href="slideshow.php?slide_id='.$previous_slide.'&amp;curdirpath='.$pathurl.'">';
 		}
 
 		echo '<img src="'.api_get_path(WEB_IMG_PATH).$imgp.'" title="'.get_lang('Previous').'" alt="'.get_lang('Previous').'">';
 		if ($slide > 0) {
-			echo "</a> ";
+			echo '</a> ';
 		}
-		// divider
-		if ($slide_id <> "all") {
+		// Divider
+		if ($slide_id != 'all') {
 			echo '</td><td valign="middle"> [ '.$next_slide.'/'.$total_slides.' ] </td><td>';
 		}
-		// next slide
+		// Next slide
 		if ($slide < $total_slides -1 and $slide_id <> "all") {
 			echo "<a href='slideshow.php?slide_id=".$next_slide."&curdirpath=$pathurl'>";
 
 		}
-		
-		if ($slide == $total_slides-1){
+
+		if ($slide == $total_slides - 1) {
 			$imgn = 'slide_next_na.png';
 			$last = '<img src="'.api_get_path(WEB_IMG_PATH).'slide_last_na.png" title="'.get_lang('LastSlide').'" alt="'.get_lang('LastSlide').'">';
 		} else {
 			$imgn = 'slide_next.png';
 			$last = '<a href="slideshow.php?slide_id='.($total_slides-1).'&curdirpath='.$pathurl.'"><img src="'.api_get_path(WEB_IMG_PATH).'slide_last.png" title="'.get_lang('LastSlide').'" alt="'.get_lang('LastSlide').'"></a>';
 		}
-		
+
 		echo '<img src="'.api_get_path(WEB_IMG_PATH).$imgn.'" title="'.get_lang('Next').'" alt="'.get_lang('Next').'">';
 		if ($slide > 0) {
 			echo '</a>';
 		}
-		// last slide
+		// Last slide
 		echo '&nbsp;&nbsp;'.$last;
 		echo '</td>';
 		echo '</tr>';
@@ -345,7 +300,6 @@ if ($slide_id !== "all") {
 	} else {
 		Display::display_warning_message(get_lang('FileNotFound'));
 	}
-} // if ($slide_id!=="all")
+}
 
 Display :: display_footer();
-?>

+ 57 - 94
main/document/slideshowoptions.php

@@ -1,34 +1,12 @@
-<?php // $Id: slideshowoptions.php 22565 2009-08-02 21:12:59Z yannoo $
-/*
-==============================================================================
-	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)
-
-	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.
+<?php
+/* For licensing terms, see /license.txt */
 
-	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
 /**
-==============================================================================
-*	@author Patrick Cool
-*	@package dokeos.document
-==============================================================================
-*/
+ *	@author Patrick Cool
+ *	@package chamilo.document
+ */
 
 /*
-==============================================================================
 Developped by Patrick Cool
 patrick.cool@UGent.be
 Ghent University
@@ -40,10 +18,9 @@ I wrote this quite quick and didn't think too much about it in advance.
 It is not perfect at all but it is workable and usefull (I think)
 Do not consider this as a powerpoint replacement, although it has
 the same starting point.
-==============================================================================
 */
+
 /*
-==============================================================================
 Description:
 	This is a plugin for the documents tool. It looks for .jpg, .jpeg, .gif, .png
 	files (since these are the files that can be viewed in a browser) and creates
@@ -55,51 +32,46 @@ Description:
 
 	On this page the options of the slideshow can be set: maintain the original file
 	or resize the file to a given width.
-==============================================================================
-
 */
-// including the language file
-// name of the language file that needs to be included
-$language_file = array ('slideshow', 'document');
+
+// Language files that need to be included
+$language_file = array('slideshow', 'document');
 
 require_once '../inc/global.inc.php';
 
 $path = Security::remove_XSS($_GET['curdirpath']);
 $pathurl = urlencode($path);
 
-// breadcrumb navigation
-$url="document.php?curdirpath=".$pathurl;
-$originaltoolname=get_lang('Documents');
-$interbreadcrumb[]= array ("url"=>$url, "name"=>$originaltoolname );
+// Breadcrumb navigation
+$url = 'document.php?curdirpath='.$pathurl;
+$originaltoolname = get_lang('Documents');
+$interbreadcrumb[] = array('url' => $url, 'name' => $originaltoolname);
 
-$url="slideshow.php?curdirpath=".$pathurl;
-$originaltoolname=get_lang('SlideShow');
-$interbreadcrumb[]= array ("url"=>$url, "name"=>$originaltoolname );
+$url = 'slideshow.php?curdirpath='.$pathurl;
+$originaltoolname = get_lang('SlideShow');
+$interbreadcrumb[] = array('url' => $url, 'name' => $originaltoolname);
 
-// because $nametools uses $_SERVER['PHP_SELF'] for the breadcrumbs instead of $_SERVER['REQUEST_URI'], I had to
+// Because $nametools uses $_SERVER['PHP_SELF'] for the breadcrumbs instead of $_SERVER['REQUEST_URI'], I had to
 // bypass the $nametools thing and use <b></b> tags in the $interbreadcrump array
-$url="slideshowoptions.php?curdirpath=".$pathurl;
-$originaltoolname="<b>".get_lang('_slideshow_options')."</b>";
-$interbreadcrumb[]= array ("url"=>$url, "name"=>$originaltoolname );
+$url = 'slideshowoptions.php?curdirpath='.$pathurl;
+$originaltoolname = '<b>'.get_lang('_slideshow_options').'</b>';
+$interbreadcrumb[] = array('url' => $url, 'name' => $originaltoolname );
 
-Display::display_header($originalToolName,"Doc");
+Display::display_header($originalToolName, 'Doc');
 
 // can't remember why I put this here. This is probably obsolete code
 // loading the slides from the session
-//$image_files_only = $_SESSION["image_files_only"];
+//$image_files_only = $_SESSION['image_files_only'];
 
 // calculating the current slide, next slide, previous slide and the number of slides
-/*if ($slide_id)
-	{
-	$slide=$slide_id;
-	}
-else
-	{
-	$slide=0;
-	}
-$previous_slide=$slide-1;
-$next_slide=$slide+1;
-$total_slides=count($image_files_only);
+/*if ($slide_id) {
+	$slide = $slide_id;
+} else {
+	$slide = 0;
+}
+$previous_slide = $slide - 1;
+$next_slide = $slide + 1;
+$total_slides = count($image_files_only);
 */
 ?>
 <style type="text/css">
@@ -113,10 +85,9 @@ $total_slides=count($image_files_only);
 -->
 </style>
 
-<script language="JavaScript" type="text/JavaScript">
+<script language="JavaScript" type="text/javascript">
 <!--
 
-
 function enableresizing() { //v2.0
 	document.options.width.disabled=false;
 	document.options.width.className='enabled_input';
@@ -135,7 +106,6 @@ window.onload = <?php echo $_SESSION['image_resizing'] == 'resizing' ? 'enablere
 //-->
 </script>
 
-
 <?php
 echo '<div class="actions">';
 echo '<a href="document.php?action=exit_slideshow&curdirpath='.$pathurl.'">'.Display::return_icon('back.png').get_lang('BackTo').' '.get_lang('DocumentsOverview').'</a>';
@@ -149,55 +119,47 @@ echo '</div>';
 
 	<div class="row">
 		<div class="label">
-			<input class="checkbox" name="radio_resizing" type="radio" onClick="disableresizing()" value="noresizing"
-	  <?php
-	  $image_resizing=$_SESSION["image_resizing"];
-	  if($image_resizing=="noresizing" or $image_resizing=="")
-	  	{
-		echo " checked";
-		}
+			<input class="checkbox" name="radio_resizing" type="radio" onClick="disableresizing()" value="noresizing" <?php
+	$image_resizing = $_SESSION['image_resizing'];
+	if ($image_resizing == 'noresizing' || $image_resizing == '') {
+		echo ' checked';
+	}
 			?>>
 		</div>
 		<div class="formw"><?php echo get_lang('_no_resizing');?><br /><?php echo get_lang('_no_resizing_comment');?>
 		</div>
 	</div>
 
-
-
 	<div class="row">
 		<div class="label">
-			<input class="checkbox" name="radio_resizing" type="radio" onClick="enableresizing()" value="resizing"
-	  <?php
-	  $image_resizing=$_SESSION["image_resizing"];
-	  if($image_resizing=="resizing")
-	  	{
-		echo " checked";
-		$width=$_SESSION["image_resizing_width"];
-		$height=$_SESSION["image_resizing_height"];
-		}
+			<input class="checkbox" name="radio_resizing" type="radio" onClick="javascript: enableresizing();" value="resizing" <?php
+	$image_resizing = $_SESSION['image_resizing'];
+	if ($image_resizing == 'resizing') {
+		echo ' checked';
+		$width = $_SESSION['image_resizing_width'];
+		$height = $_SESSION['image_resizing_height'];
+	}
 			?>>
 		</div>
 		<div class="formw">
-			<?php echo get_lang('_resizing');?><br /><?php echo get_lang('_resizing_comment');?><br />
-        <?php echo get_lang('_width');?>:
-	    &nbsp;<input name="width" type="text" id="width"
-		<?php
-		if ($image_resizing=="resizing") {
-			echo " value='".$width."'";
-			echo " class=\"enabled_input\"";
+			<?php echo get_lang('_resizing'); ?><br /><?php echo get_lang('_resizing_comment'); ?><br />
+        <?php echo get_lang('_width'); ?>:
+	    &nbsp;<input name="width" type="text" id="width" <?php
+		if ($image_resizing == 'resizing') {
+			echo ' value="'.$width.'"';
+			echo ' class="enabled_input"';
 	    } else {
-            echo " class=\"disabled_input\"";
+            echo ' class="disabled_input"';
         }
 		?> >
         <br />
         <?php echo get_lang('_height');?>:
-        &nbsp;&nbsp;&nbsp;&nbsp;<input name="height" type="text" id="height"
-		<?php
-		if ($image_resizing=="resizing") {
-			echo " value='".$height."'";
-			echo " class=\"enabled_input\"";
+        &nbsp;&nbsp;&nbsp;&nbsp;<input name="height" type="text" id="height" <?php
+		if ($image_resizing == 'resizing') {
+			echo ' value="'.$height.'"';
+			echo ' class="enabled_input"';
 		} else {
-            echo " class=\"disabled_input\"";
+            echo ' class="disabled_input"';
         }
 		?> >
 		</div>
@@ -212,4 +174,5 @@ echo '</div>';
 	</div>
 </form>
 <?php
-Display::display_footer();
+
+Display::display_footer();

+ 343 - 388
main/document/upload.php

@@ -1,53 +1,52 @@
-<?php // $Id: upload.php 22201 2009-07-17 19:57:03Z cfasanando $
-/* For licensing terms, see /chamilo_license.txt */
+<?php
+/* For licensing terms, see /license.txt */
+
 /**
-==============================================================================
-* Main script for the documents tool
-*
-* This script allows the user to manage files and directories on a remote http server.
-*
-* The user can : - navigate through files and directories.
-*				 - upload a file
-*				 - delete, copy a file or a directory
-*				 - edit properties & content (name, comments, html content)
-*
-* The script is organised in four sections.
-*
-* 1) Execute the command called by the user
-*				Note: somme commands of this section are organised in two steps.
-*			    The script always begins with the second step,
-*			    so it allows to return more easily to the first step.
-*
-*				Note (March 2004) some editing functions (renaming, commenting)
-*				are moved to a separate page, edit_document.php. This is also
-*				where xml and other stuff should be added.
-*
-* 2) Define the directory to display
-*
-* 3) Read files and directories from the directory defined in part 2
-* 4) Display all of that on an HTML page
-*
-* @todo eliminate code duplication between
-* document/document.php, scormdocument.php
-*
-* @package dokeos.document
-==============================================================================
-*/
-
-// name of the language file that needs to be included
+ * Main script for the documents tool
+ *
+ * This script allows the user to manage files and directories on a remote http server.
+ *
+ * The user can : - navigate through files and directories.
+ *				 - upload a file
+ *				 - delete, copy a file or a directory
+ *				 - edit properties & content (name, comments, html content)
+ *
+ * The script is organised in four sections.
+ *
+ * 1) Execute the command called by the user
+ *				Note: somme commands of this section are organised in two steps.
+ *				The script always begins with the second step,
+ *				so it allows to return more easily to the first step.
+ *
+ *				Note (March 2004) some editing functions (renaming, commenting)
+ *				are moved to a separate page, edit_document.php. This is also
+ *				where xml and other stuff should be added.
+ *
+ * 2) Define the directory to display
+ *
+ * 3) Read files and directories from the directory defined in part 2
+ * 4) Display all of that on an HTML page
+ *
+ * @todo eliminate code duplication between
+ * document/document.php, scormdocument.php
+ *
+ * @package dokeos.document
+ */
+
+// Name of the language file that needs to be included
 $language_file = 'document';
 
-// including the global Dokeos file
+// Including the global initialization file
 require_once '../inc/global.inc.php';
 
-// including additional libraries
-require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'document.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
-require_once api_get_path(LIBRARY_PATH)	. 'formvalidator/FormValidator.class.php';
+// Including additional libraries
+require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+require_once api_get_path(LIBRARY_PATH).'document.lib.php';
+require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 require_once 'document.inc.php';
 
-// adding extra javascript to the form
+// Adding extra javascript to the form
 $htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>';
 $htmlHeadXtra[] = '<script type="text/javascript">
 
@@ -87,436 +86,396 @@ function setFocus(){
 function get_text_content($doc_path, $doc_mime) {
 	// TODO: review w$ compatibility
 
-	// use usual exec output lines array to store stdout instead of a temp file
+	// Use usual exec output lines array to store stdout instead of a temp file
 	// because we need to store it at RAM anyway before index on DokeosIndexer object
-	$ret_val = NULL;
+	$ret_val = null;
 	switch ($doc_mime) {
 		case 'text/plain':
-			$handle = fopen($doc_path, "r");
+			$handle = fopen($doc_path, 'r');
 			$output = array(fread($handle, filesize($doc_path)));
 			fclose($handle);
 			break;
 		case 'application/pdf':
-		    exec("pdftotext $doc_path -", $output, $ret_val);
-		    break;
+			exec("pdftotext $doc_path -", $output, $ret_val);
+			break;
 		case 'application/postscript':
-			$temp_file = tempnam(sys_get_temp_dir(), 'dokeos');
-		    exec("ps2pdf $doc_path $temp_file", $output, $ret_val);
-		    if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
-			    return FALSE;
-		    }
-		    exec("pdftotext $temp_file -", $output, $ret_val);
-		    unlink($temp_file);
-		    var_dump($output);
-		    break;
+			$temp_file = tempnam(sys_get_temp_dir(), 'chamilo');
+			exec("ps2pdf $doc_path $temp_file", $output, $ret_val);
+			if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
+				return false;
+			}
+			exec("pdftotext $temp_file -", $output, $ret_val);
+			unlink($temp_file);
+			//var_dump($output);
+			break;
 		case 'application/msword':
-		    exec("catdoc $doc_path", $output, $ret_val);
-		    var_dump($output);
-		    break;
+			exec("catdoc $doc_path", $output, $ret_val);
+			//var_dump($output);
+			break;
 		case 'text/html':
-		    exec("html2text $doc_path", $output, $ret_val);
-		    break;
-        case 'text/rtf':
-            // note: correct handling of code pages in unrtf
-            // on debian lenny unrtf v0.19.2 can not, but unrtf v0.20.5 can
-            exec("unrtf --text $doc_path", $output, $ret_val);
-            if ($ret_val == 127) { // command not found
-                return FALSE;
-            }
-            // avoid index unrtf comments
-            if (is_array($output) && count($output)>1) {
-                $parsed_output = array();
-                foreach ($output as $line) {
-                    if (!preg_match('/^###/', $line, $matches)) {
-                        if (!empty($line)) {
-                            $parsed_output[] = $line;
-                        }
-                    }
-                }
-                $output = $parsed_output;
-            }
-            break;
-        case 'application/vnd.ms-powerpoint':
-            exec("catppt $doc_path", $output, $ret_val);
-            break;
-        case 'application/vnd.ms-excel':
-	        exec("xls2csv -c\" \" $doc_path", $output, $ret_val);
-	        break;
+			exec("html2text $doc_path", $output, $ret_val);
+			break;
+		case 'text/rtf':
+			// Note: correct handling of code pages in unrtf
+			// on debian lenny unrtf v0.19.2 can not, but unrtf v0.20.5 can
+			exec("unrtf --text $doc_path", $output, $ret_val);
+			if ($ret_val == 127) { // command not found
+				return false;
+			}
+			// Avoid index unrtf comments
+			if (is_array($output) && count($output) > 1) {
+				$parsed_output = array();
+				foreach ($output as & $line) {
+					if (!preg_match('/^###/', $line, $matches)) {
+						if (!empty($line)) {
+							$parsed_output[] = $line;
+						}
+					}
+				}
+				$output = $parsed_output;
+			}
+			break;
+		case 'application/vnd.ms-powerpoint':
+			exec("catppt $doc_path", $output, $ret_val);
+			break;
+		case 'application/vnd.ms-excel':
+			exec("xls2csv -c\" \" $doc_path", $output, $ret_val);
+			break;
 	}
 
 	$content = '';
 	if (!is_null($ret_val)) {
 		if ($ret_val !== 0) { // shell fail, probably 127 (command not found)
-			return FALSE;
+			return false;
 		}
 	}
 	if (isset($output)) {
-		foreach ( $output as $line ) {
-			$content .= $line ."\n";
+		foreach ($output as & $line) {
+			$content .= $line."\n";
 		}
 		return $content;
 	}
 	else {
-		return FALSE;
+		return false;
 	}
 }
 
-// variables
-
-$is_allowed_to_edit = api_is_allowed_to_edit(null,true);
+// Variables
 
+$is_allowed_to_edit = api_is_allowed_to_edit(null, true);
 
-$courseDir   = $_course['path']."/document";
+$courseDir = $_course['path'].'/document';
 $sys_course_path = api_get_path(SYS_COURSE_PATH);
 $base_work_dir = $sys_course_path.$courseDir;
-$noPHP_SELF=true;
+$noPHP_SELF = true;
 
-
-//what's the current path?
-if(isset($_GET['curdirpath']) && $_GET['curdirpath']!='')
-{
+// What's the current path?
+if (isset($_GET['curdirpath']) && $_GET['curdirpath'] != '') {
 	$path = $_GET['curdirpath'];
-}
-elseif (isset($_POST['curdirpath']))
-{
+} elseif (isset($_POST['curdirpath'])) {
 	$path = $_POST['curdirpath'];
-}
-else
-{
+} else {
 	$path = '/';
 }
 
-//check the path: if the path is not found (no document id), set the path to /
-if(!DocumentManager::get_document_id($_course,$path))
-{
+// Check the path: if the path is not found (no document id), set the path to /
+if (!DocumentManager::get_document_id($_course, $path)) {
 	$path = '/';
 }
 
-//this needs cleaning!
-if(isset($_SESSION['_gid']) && $_SESSION['_gid']!='') //if the group id is set, check if the user has the right to be here
-{
-	//needed for group related stuff
+// This needs cleaning!
+if (isset($_SESSION['_gid']) && $_SESSION['_gid'] != '') { // If the group id is set, check if the user has the right to be here
+	// Needed for group related stuff
 	require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
-	//get group info
+	// Get group info
 	$group_properties = GroupManager::get_group_properties($_SESSION['_gid']);
-	$noPHP_SELF=true;
+	$noPHP_SELF = true;
 
-	if($is_allowed_to_edit || GroupManager::is_user_in_group($_user['user_id'],$_SESSION['_gid'])) //only courseadmin or group members allowed
-	{
+	if ($is_allowed_to_edit || GroupManager::is_user_in_group($_user['user_id'],$_SESSION['_gid'])) { // Only courseadmin or group members allowed
 		$to_group_id = $_SESSION['_gid'];
 		$req_gid = '&amp;gidReq='.$_SESSION['_gid'];
-		$interbreadcrumb[]= array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['_gid'], "name"=> get_lang('GroupSpace'));
-	}
-	else
-	{
+		$interbreadcrumb[] = array('url' => '../group/group_space.php?gidReq='.$_SESSION['_gid'], 'name' => get_lang('GroupSpace'));
+	} else {
 		api_not_allowed(true);
 	}
-}
-elseif($is_allowed_to_edit || is_my_shared_folder($_user['user_id'], $path)) //admin for "regular" upload, no group documents. And check if is my shared folder
-{
+} elseif ($is_allowed_to_edit || is_my_shared_folder($_user['user_id'], $path)) { // Admin for "regular" upload, no group documents. And check if is my shared folder
 	$to_group_id = 0;
 	$req_gid = '';
-}
-else  //no course admin and no group member...
-{
+} else { // No course admin and no group member...
 	api_not_allowed(true);
 }
 
 
-//group docs can only be uploaded in the group directory
-if($to_group_id!=0 && $path=='/')
-{
+// Group docs can only be uploaded in the group directory
+if ($to_group_id != 0 && $path == '/') {
 	$path = $group_properties['directory'];
 }
 
-//if we want to unzip a file, we need the library
+// If we want to unzip a file, we need the library
 if (isset($_POST['unzip']) && $_POST['unzip'] == 1) {
 	require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
 }
 
-// variables
+// Variables
 $max_filled_space = DocumentManager::get_course_quota();
 
-// title of the tool
-if($to_group_id !=0) //add group name after for group documents
-{
+// Title of the tool
+if ($to_group_id != 0) { // Add group name after for group documents
 	$add_group_to_title = ' ('.$group_properties['name'].')';
 }
 $nameTools = get_lang('UplUploadDocument').$add_group_to_title;
 
-// breadcrumbs
-$interbreadcrumb[] = array('url' =>'./document.php?curdirpath='.urlencode($path).$req_gid, 'name'=> get_lang('Documents'));
+// Breadcrumbs
+$interbreadcrumb[] = array('url' => './document.php?curdirpath='.urlencode($path).$req_gid, 'name' => get_lang('Documents'));
 
-// display the header
+// Display the header
 Display::display_header($nameTools, 'Doc');
 
+/*	Here we do all the work */
 
-
-/*
------------------------------------------------------------
-	Here we do all the work
------------------------------------------------------------
-*/
-
-//user has submitted a file
-if(isset($_FILES['user_upload'])) {
-	//echo("<pre>");
+// User has submitted a file
+if (isset($_FILES['user_upload'])) {
+	//echo('<pre>');
 	//print_r($_FILES['user_upload']);
-	//echo("</pre>");
+	//echo('</pre>');
 
 	$upload_ok = process_uploaded_file($_FILES['user_upload']);
-	if($upload_ok) {
-		//file got on the server without problems, now process it
-		$new_path = handle_uploaded_document($_course, $_FILES['user_upload'],$base_work_dir,$_POST['curdirpath'],$_user['user_id'],$to_group_id,$to_user_id,$max_filled_space,$_POST['unzip'],$_POST['if_exists']);
-
-    	$new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
-    	$new_title = isset($_POST['title']) ? trim($_POST['title']) : '';
-
-    	if ($new_path && ($new_comment || $new_title))
-    	if (($docid = DocumentManager::get_document_id($_course, $new_path)))
-    	{
-        	$table_document = Database::get_course_table(TABLE_DOCUMENT);
-        	$ct = '';
-        	if ($new_comment) $ct .= ", comment='$new_comment'";
-        	if ($new_title)   $ct .= ", title='$new_title'";
-        	Database::query("UPDATE $table_document SET" . substr($ct, 1) .
-        	    " WHERE id = '$docid'");
-    	}
-    	//showing message when sending zip files
-    	if ($new_path === true && $_POST['unzip'] == 1) {
-    		Display::display_confirmation_message(get_lang('UplUploadSucceeded')."<br/>",false);
-    	}
-
-      if ( (api_get_setting('search_enabled')=='true') && ($docid = DocumentManager::get_document_id($_course, $new_path))) {
-        $table_document = Database::get_course_table(TABLE_DOCUMENT);
-        $result = Database::query("SELECT * FROM $table_document WHERE id = '$docid' LIMIT 1");
-        if (Database::num_rows($result) == 1) {
-          $row = Database::fetch_array($result);
-          $doc_path = api_get_path(SYS_COURSE_PATH) . $courseDir. $row['path'];
-          //TODO: mime_content_type is deprecated, fileinfo php extension is enabled by default as of PHP 5.3.0
-          // now versions of PHP on Debian testing(5.2.6-5) and Ubuntu(5.2.6-2ubuntu) are lower, so wait for a while
-          $doc_mime = mime_content_type($doc_path);
-          //echo $doc_mime;
-          //TODO: more mime types
-          $allowed_mime_types = array('text/plain', 'application/pdf', 'application/postscript', 'application/msword', 'text/html', 'text/rtf', 'application/vnd.ms-powerpoint', 'application/vnd.ms-excel');
-
-          // mime_content_type does not detect correctly some formats that are going to be supported for index, so an extensions array is used by the moment
-          if (empty($doc_mime)) {
-          	$allowed_extensions = array('ppt', 'pps', 'xls');
-            $extensions = preg_split("/[\/\\.]/", $doc_path) ;
-            $doc_ext = strtolower($extensions[count($extensions)-1]);
-            if (in_array($doc_ext, $allowed_extensions)) {
-            	switch ($doc_ext) {
-                    case 'ppt':
-                    case 'pps':
-                        $doc_mime = 'application/vnd.ms-powerpoint';
-                        break;
-                    case 'xls':
-                        $doc_mime = 'application/vnd.ms-excel';
-                        break;
-            	}
-            }
-          }
-
-          if (in_array($doc_mime, $allowed_mime_types) && isset($_POST['index_document']) && $_POST['index_document']) {
-            $file_title = $row['title'];
-            $file_content = get_text_content($doc_path, $doc_mime);
-            $courseid = api_get_course_id();
-            isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
-
-            require_once api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php';
-            require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
-
-            $ic_slide = new IndexableChunk();
-            $ic_slide->addValue("title", $file_title);
-            $ic_slide->addCourseId($courseid);
-            $ic_slide->addToolId(TOOL_DOCUMENT);
-            $xapian_data = array(
-              SE_COURSE_ID => $courseid,
-              SE_TOOL_ID => TOOL_DOCUMENT,
-              SE_DATA => array('doc_id' => (int)$docid),
-              SE_USER => (int)api_get_user_id(),
-            );
-            $ic_slide->xapian_data = serialize($xapian_data);
-            $di = new DokeosIndexer();
-            $di->connectDb(NULL, NULL, $lang);
-
-            $specific_fields = get_specific_field_list();
-
-            // process different depending on what to do if file exists
-            /**
-             * FIXME: Find a way to really verify if the file had been
-             * overwriten. Now all work is done at
-             * handle_uploaded_document() and it's difficult to verify it
-             */
-			if (!empty($_POST['if_exists']) && $_POST['if_exists'] == 'overwrite') {
-				// overwrite the file on search engine
-				// actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
-
-				// get search_did
-				$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 LIMIT 1';
-				$sql = sprintf($sql, $tbl_se_ref, $courseid, TOOL_DOCUMENT, $docid);
-				$res = Database::query($sql);
-
-				if (Database::num_rows($res) > 0) {
-					$se_ref = Database::fetch_array($res);
-					$di->remove_document((int)$se_ref['search_did']);
-					$all_specific_terms = '';
-					foreach ($specific_fields as $specific_field) {
-						delete_all_specific_field_value($courseid, $specific_field['id'], TOOL_DOCUMENT, $docid);
-						//update search engine
-						$sterms = trim($_REQUEST[$specific_field['code']]);
-						$all_specific_terms .= ' '. $sterms;
-						$sterms = explode(',', $sterms);
-						foreach ($sterms as $sterm) {
-							$sterm = trim($sterm);
-							if (!empty($sterm)) {
-								$ic_slide->addTerm($sterm, $specific_field['code']);
-								add_specific_field_value($specific_field['id'], $courseid, TOOL_DOCUMENT, $docid, $value);
-							}
+	if ($upload_ok) {
+		// File got on the server without problems, now process it
+		$new_path = handle_uploaded_document($_course, $_FILES['user_upload'], $base_work_dir, $_POST['curdirpath'], $_user['user_id'], $to_group_id, $to_user_id, $max_filled_space, $_POST['unzip'], $_POST['if_exists']);
+
+		$new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
+		$new_title = isset($_POST['title']) ? trim($_POST['title']) : '';
+
+		if ($new_path && ($new_comment || $new_title)) {
+			if (($docid = DocumentManager::get_document_id($_course, $new_path))) {
+				$table_document = Database::get_course_table(TABLE_DOCUMENT);
+				$ct = '';
+				if ($new_comment) $ct .= ", comment='$new_comment'";
+				if ($new_title)   $ct .= ", title='$new_title'";
+				Database::query("UPDATE $table_document SET".substr($ct, 1)." WHERE id = '$docid'");
+			}
+		}
+		// Showing message when sending zip files
+		if ($new_path === true && $_POST['unzip'] == 1) {
+			Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />', false);
+		}
+
+		if ((api_get_setting('search_enabled') == 'true') && ($docid = DocumentManager::get_document_id($_course, $new_path))) {
+			$table_document = Database::get_course_table(TABLE_DOCUMENT);
+			$result = Database::query("SELECT * FROM $table_document WHERE id = '$docid' LIMIT 1");
+			if (Database::num_rows($result) == 1) {
+				$row = Database::fetch_array($result);
+				$doc_path = api_get_path(SYS_COURSE_PATH).$courseDir.$row['path'];
+				//TODO: mime_content_type is deprecated, fileinfo php extension is enabled by default as of PHP 5.3.0
+				// now versions of PHP on Debian testing(5.2.6-5) and Ubuntu(5.2.6-2ubuntu) are lower, so wait for a while
+				$doc_mime = mime_content_type($doc_path);
+				//echo $doc_mime;
+				//TODO: more mime types
+				$allowed_mime_types = array('text/plain', 'application/pdf', 'application/postscript', 'application/msword', 'text/html', 'text/rtf', 'application/vnd.ms-powerpoint', 'application/vnd.ms-excel');
+
+				// mime_content_type does not detect correctly some formats that are going to be supported for index, so an extensions array is used by the moment
+				if (empty($doc_mime)) {
+					$allowed_extensions = array('ppt', 'pps', 'xls');
+					$extensions = preg_split("/[\/\\.]/", $doc_path) ;
+					$doc_ext = strtolower($extensions[count($extensions)-1]);
+					if (in_array($doc_ext, $allowed_extensions)) {
+						switch ($doc_ext) {
+							case 'ppt':
+							case 'pps':
+								$doc_mime = 'application/vnd.ms-powerpoint';
+								break;
+							case 'xls':
+								$doc_mime = 'application/vnd.ms-excel';
+								break;
 						}
 					}
-					// add terms also to content to make terms findable by probabilistic search
-					$file_content = $all_specific_terms .' '. $file_content;
-					$ic_slide->addValue("content", $file_content);
-					$di->addChunk($ic_slide);
-					//index and return a new search engine document id
-					$did = $di->index();
-					if ($did) {
-						// update the search_did on db
+				}
+
+				if (in_array($doc_mime, $allowed_mime_types) && isset($_POST['index_document']) && $_POST['index_document']) {
+					$file_title = $row['title'];
+					$file_content = get_text_content($doc_path, $doc_mime);
+					$courseid = api_get_course_id();
+					$lang = isset($_POST['language']) ? Database::escape_string($_POST['language']) : 'english';
+
+					require_once api_get_path(LIBRARY_PATH).'search/DokeosIndexer.class.php';
+					require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
+
+					$ic_slide = new IndexableChunk();
+					$ic_slide->addValue("title", $file_title);
+					$ic_slide->addCourseId($courseid);
+					$ic_slide->addToolId(TOOL_DOCUMENT);
+					$xapian_data = array(
+						SE_COURSE_ID => $courseid,
+						SE_TOOL_ID => TOOL_DOCUMENT,
+						SE_DATA => array('doc_id' => (int)$docid),
+						SE_USER => (int)api_get_user_id(),
+					);
+					$ic_slide->xapian_data = serialize($xapian_data);
+					$di = new DokeosIndexer();
+					$di->connectDb(NULL, NULL, $lang);
+
+					$specific_fields = get_specific_field_list();
+
+					// process different depending on what to do if file exists
+					/**
+					 * FIXME: Find a way to really verify if the file had been
+					 * overwriten. Now all work is done at
+					 * handle_uploaded_document() and it's difficult to verify it
+					 */
+					if (!empty($_POST['if_exists']) && $_POST['if_exists'] == 'overwrite') {
+						// overwrite the file on search engine
+						// actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
+
+						// Get search_did
 						$tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
-						$sql = 'UPDATE %s SET search_did=%d WHERE id=%d LIMIT 1';
-						$sql = sprintf($sql, $tbl_se_ref, (int)$did, (int)$se_ref['id']);
-						Database::query($sql);
-					}
+						$sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
+						$sql = sprintf($sql, $tbl_se_ref, $courseid, TOOL_DOCUMENT, $docid);
+						$res = Database::query($sql);
+
+						if (Database::num_rows($res) > 0) {
+							$se_ref = Database::fetch_array($res);
+							$di->remove_document((int)$se_ref['search_did']);
+							$all_specific_terms = '';
+							foreach ($specific_fields as $specific_field) {
+								delete_all_specific_field_value($courseid, $specific_field['id'], TOOL_DOCUMENT, $docid);
+								// Update search engine
+								$sterms = trim($_REQUEST[$specific_field['code']]);
+								$all_specific_terms .= ' '. $sterms;
+								$sterms = explode(',', $sterms);
+								foreach ($sterms as $sterm) {
+									$sterm = trim($sterm);
+									if (!empty($sterm)) {
+										$ic_slide->addTerm($sterm, $specific_field['code']);
+										add_specific_field_value($specific_field['id'], $courseid, TOOL_DOCUMENT, $docid, $value);
+									}
+								}
+							}
+							// Add terms also to content to make terms findable by probabilistic search
+							$file_content = $all_specific_terms .' '. $file_content;
+							$ic_slide->addValue("content", $file_content);
+							$di->addChunk($ic_slide);
+							// Index and return a new search engine document id
+							$did = $di->index();
+							if ($did) {
+								// update the search_did on db
+								$tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
+								$sql = 'UPDATE %s SET search_did=%d WHERE id=%d LIMIT 1';
+								$sql = sprintf($sql, $tbl_se_ref, (int)$did, (int)$se_ref['id']);
+								Database::query($sql);
+							}
 
-				}
-			} else {
-				// add all terms
-				$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']);
-								add_specific_field_value($specific_field['id'], $courseid, TOOL_DOCUMENT, $docid, $sterm);
+						}
+					} else {
+						// Add all terms
+						$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']);
+										add_specific_field_value($specific_field['id'], $courseid, TOOL_DOCUMENT, $docid, $sterm);
+									}
+								}
 							}
 						}
+						// Add terms also to content to make terms findable by probabilistic search
+						$file_content = $all_specific_terms .' '. $file_content;
+						$ic_slide->addValue('content', $file_content);
+						$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, search_did)
+								VALUES (NULL , \'%s\', \'%s\', %s, %s)';
+							$sql = sprintf($sql, $tbl_se_ref, $courseid, TOOL_DOCUMENT, $docid, $did);
+							Database::query($sql);
+						}
 					}
 				}
-				// add terms also to content to make terms findable by probabilistic search
-				$file_content = $all_specific_terms .' '. $file_content;
-				$ic_slide->addValue("content", $file_content);
-				$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, search_did)
-						VALUES (NULL , \'%s\', \'%s\', %s, %s)';
-					$sql = sprintf($sql, $tbl_se_ref, $courseid, TOOL_DOCUMENT, $docid, $did);
-					Database::query($sql);
-				}
 			}
-          }
-
-        }
-
-      }
+		}
 
-		//check for missing images in html files
+		// Check for missing images in html files
 		$missing_files = check_for_missing_files($base_work_dir.$new_path);
-		if($missing_files)
-		{
-			//show a form to upload the missing files
-			Display::display_normal_message(build_missing_files_form($missing_files,$_POST['curdirpath'],$_FILES['user_upload']['name']),false);
+		if ($missing_files) {
+			// Show a form to upload the missing files
+			Display::display_normal_message(build_missing_files_form($missing_files, $_POST['curdirpath'], $_FILES['user_upload']['name']), false);
 		}
 	}
 }
-//missing images are submitted
-if(isset($_POST['submit_image']))
-{
+
+// Missing images are submitted
+if(isset($_POST['submit_image'])) {
 	$number_of_uploaded_images = count($_FILES['img_file']['name']);
 	//if images are uploaded
-	if ($number_of_uploaded_images > 0)
-	{
-		//we could also create a function for this, I'm not sure...
-		//create a directory for the missing files
-		$img_directory = str_replace('.','_',$_POST['related_file']."_files");
-		$missing_files_dir = create_unexisting_directory($_course,$_user['user_id'],$to_group_id,$to_user_id,$base_work_dir,$img_directory);
-		//put the uploaded files in the new directory and get the paths
-		$paths_to_replace_in_file = move_uploaded_file_collection_into_directory($_course, $_FILES['img_file'],$base_work_dir,$missing_files_dir,$_user['user_id'],$to_group_id,$to_user_id,$max_filled_space);
-		//open the html file and replace the paths
-		replace_img_path_in_html_file($_POST['img_file_path'],$paths_to_replace_in_file,$base_work_dir.$_POST['related_file']);
-		//update parent folders
-		item_property_update_on_folder($_course,$_POST['curdirpath'],$_user['user_id']);
+	if ($number_of_uploaded_images > 0) {
+		// We could also create a function for this, I'm not sure...
+		// Create a directory for the missing files
+		$img_directory = str_replace('.', '_', $_POST['related_file'].'_files');
+		$missing_files_dir = create_unexisting_directory($_course, $_user['user_id'], $to_group_id, $to_user_id, $base_work_dir, $img_directory);
+		// Put the uploaded files in the new directory and get the paths
+		$paths_to_replace_in_file = move_uploaded_file_collection_into_directory($_course, $_FILES['img_file'], $base_work_dir, $missing_files_dir, $_user['user_id'], $to_group_id, $to_user_id, $max_filled_space);
+		// Open the html file and replace the paths
+		replace_img_path_in_html_file($_POST['img_file_path'], $paths_to_replace_in_file, $base_work_dir.$_POST['related_file']);
+		// Update parent folders
+		item_property_update_on_folder($_course, $_POST['curdirpath'], $_user['user_id']);
 	}
 }
-//they want to create a directory
-if(isset($_POST['create_dir']) && $_POST['dirname']!='')
-{
-	$added_slash = ($path=='/')?'':'/';
+
+// They want to create a directory
+if (isset($_POST['create_dir']) && $_POST['dirname'] != '') {
+	$added_slash = ($path=='/') ? '' : '/';
 	$dir_name = $path.$added_slash.replace_dangerous_char($_POST['dirname']);
-	$created_dir = create_unexisting_directory($_course,$_user['user_id'],$to_group_id,$to_user_id,$base_work_dir,$dir_name,$_POST['dirname']);
-	if($created_dir)
-	{
-		Display::display_confirmation_message(get_lang('DirCr'),false);
+	$created_dir = create_unexisting_directory($_course, $_user['user_id'], $to_group_id, $to_user_id, $base_work_dir, $dir_name, $_POST['dirname']);
+	if ($created_dir) {
+		Display::display_confirmation_message(get_lang('DirCr'), false);
 		$path = $created_dir;
-	}
-	else
-	{
+	} else {
 		display_error(get_lang('CannotCreateDir'));
 	}
 }
 
-//tracking not needed here?
+// Tracking not needed here?
 //event_access_tool(TOOL_DOCUMENT);
 
-/*============================================================================*/
-?>
+/* They want to create a new directory */
 
-<?php
-//=======================================//
-//they want to create a new directory//
-//=======================================//
-
-if(isset($_GET['createdir']))
-{
-	//create the form that asks for the directory name
+if (isset($_GET['createdir'])) {
+	// create the form that asks for the directory name
 	$new_folder_text = '<form action="'.api_get_self().'" method="POST">';
 	$new_folder_text .= '<input type="hidden" name="curdirpath" value="'.$path.'"/>';
 	$new_folder_text .= get_lang('NewDir') .' ';
 	$new_folder_text .= '<input type="text" name="dirname"/>';
 	$new_folder_text .= '<button type="submit" class="save" name="create_dir">'.get_lang('CreateFolder').'</button>';
 	$new_folder_text .= '</form>';
-	//show the form
+	// Show the form
 	//Display::display_normal_message($new_folder_text, false);
 
 	echo create_dir_form();
 }
 
-// actions
+// Actions
 echo '<div class="actions">';
 
-// link back to the documents overview
+// Link back to the documents overview
 echo '<a href="document.php?curdirpath='.$path.'">'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('DocumentsOverview')).get_lang('BackTo').' '.get_lang('DocumentsOverview').'</a>';
 
-// link to create a folder
-if(!isset($_GET['createdir']) && !is_my_shared_folder($_user['user_id'], $path))
-{
+// Link to create a folder
+if (!isset($_GET['createdir']) && !is_my_shared_folder($_user['user_id'], $path)) {
 	echo '<a href="'.api_get_self().'?path='.$path.'&amp;createdir=1">'.Display::return_icon('folder_new.gif', get_lang('CreateDir')).get_lang('CreateDir').'</a>';
 }
 echo '</div>';
 
-//form to select directory
-$folders = DocumentManager::get_all_document_folders($_course,$to_group_id,$is_allowed_to_edit);
+// Form to select directory
+$folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit);
 
-echo(build_directory_selector($folders,$path,$group_properties['directory']));
+echo build_directory_selector($folders, $path, $group_properties['directory']);
 
 ?>
 
@@ -524,65 +483,61 @@ echo(build_directory_selector($folders,$path,$group_properties['directory']));
 
 <?php
 
-$form = new FormValidator('upload','POST',api_get_self(),'','enctype="multipart/form-data"');
-$form->addElement('hidden','curdirpath',$path);
-$form->addElement('file','user_upload',get_lang('File'),'id="user_upload" size="45"');
+$form = new FormValidator('upload', 'POST', api_get_self(), '', 'enctype="multipart/form-data"');
+$form->addElement('hidden', 'curdirpath', $path);
+$form->addElement('file', 'user_upload', get_lang('File'), 'id="user_upload" size="45"');
 
-if(api_get_setting('use_document_title')=='true') {
-	$form->addElement('text','title',get_lang('Title'),array('size'=>'20','style' => 'width:300px','id' => 'title_file'));
-	$form->addElement('textarea','comment',get_lang('Comment'),'wrap="virtual" style="width:300px;"');
+if (api_get_setting('use_document_title') == 'true') {
+	$form->addElement('text', 'title', get_lang('Title'), array('size' => '20', 'style' => 'width:300px', 'id' => 'title_file'));
+	$form->addElement('textarea', 'comment', get_lang('Comment'), 'wrap="virtual" style="width:300px;"');
 }
-//Advanced parameters
-	$form -> addElement('html','<div class="row">
+// Advanced parameters
+$form -> addElement('html', '<div class="row">
 			<div class="label">&nbsp;</div>
 			<div class="formw">
 				<a href="javascript://" onclick=" return advanced_parameters()"><span id="img_plus_and_minus"><div style="vertical-align:top;" ><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'</div></span></a>
 			</div>
 			</div>');
-$form -> addElement('html','<div id="options" style="display:none">');
+$form -> addElement('html', '<div id="options" style="display:none">');
 
-//check box options
-$form->addElement('checkbox','unzip',get_lang('Options'),get_lang('Uncompress'),'onclick="check_unzip()" value="1"');
+// Check box options
+$form->addElement('checkbox', 'unzip', get_lang('Options'), get_lang('Uncompress'), 'onclick="javascript: check_unzip();" value="1"');
 
-if(api_get_setting('search_enabled')=='true')
-{
+if (api_get_setting('search_enabled') == 'true') {
 	//TODO: include language file
 	$supported_formats = 'Supported formats for index: Text plain, PDF, Postscript, MS Word, HTML, RTF, MS Power Point';
-    $form -> addElement ('checkbox', 'index_document','', get_lang('SearchFeatureDoIndexDocument') . '<div style="font-size: 80%" >'. $supported_formats .'</div>');
-    $form -> addElement ('html','<br /><div class="row">');
-    $form -> addElement ('html', '<div class="label">'. get_lang('SearchFeatureDocumentLanguage') .'</div>');
-    $form -> addElement ('html', '<div class="formw">'. api_get_languages_combo() .'</div>');
-    $form -> addElement ('html','</div><div class="sub-form">');
-    $specific_fields = get_specific_field_list();
-    foreach ($specific_fields as $specific_field) {
-        $form -> addElement ('text', $specific_field['code'], $specific_field['name'].' : ');
-    }
-    $form -> addElement ('html','</div>');
+	$form -> addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument').'<div style="font-size: 80%" >'.$supported_formats.'</div>');
+	$form -> addElement('html', '<br /><div class="row">');
+	$form -> addElement('html', '<div class="label">'.get_lang('SearchFeatureDocumentLanguage').'</div>');
+	$form -> addElement('html', '<div class="formw">'.api_get_languages_combo().'</div>');
+	$form -> addElement('html', '</div><div class="sub-form">');
+	$specific_fields = get_specific_field_list();
+	foreach ($specific_fields as $specific_field) {
+		$form -> addElement('text', $specific_field['code'], $specific_field['name'].' : ');
+	}
+	$form -> addElement('html', '</div>');
 }
 
 $form->addElement('radio', 'if_exists', get_lang('UplWhatIfFileExists'), get_lang('UplDoNothing'), 'nothing');
 $form->addElement('radio', 'if_exists', '', get_lang('UplOverwriteLong'), 'overwrite');
 $form->addElement('radio', 'if_exists', '', get_lang('UplRenameLong'), 'rename');
 
-//close the java script and avoid the footer up
-$form -> addElement('html','</div>');
+// Close the java script and avoid the footer up
+$form -> addElement('html', '</div>');
 
-//button send document
-$form->addElement('style_submit_button', 'submitDocument', get_lang('SendDocument'),'class="upload"');
-$form->add_real_progress_bar('DocumentUpload','user_upload');
+// Button send document
+$form->addElement('style_submit_button', 'submitDocument', get_lang('SendDocument'), 'class="upload"');
+$form->add_real_progress_bar('DocumentUpload', 'user_upload');
 
-$defaults = array('index_document'=>'checked="checked"');
+$defaults = array('index_document' => 'checked="checked"');
 
 $form->setDefaults($defaults);
 
-
 $form->display();
-
 ?>
 
 <!-- end upload form -->
 
 <?php
-// footer
+// Footer
 Display::display_footer();
-?>