Răsfoiți Sursa

Removing fileUpload.lib and fileManager.lib calls lib already loaded with composer. fileManage.lib.php renamed to fileManager.lib.php

Julio Montoya 12 ani în urmă
părinte
comite
23f364d2cf
100 a modificat fișierele cu 28119 adăugiri și 20231 ștergeri
  1. 557 483
      main/admin/calendar.lib.php
  2. 552 515
      main/admin/configure_homepage.php
  3. 83 69
      main/admin/group_add.php
  4. 62 51
      main/admin/group_edit.php
  5. 367 144
      main/admin/settings.lib.php
  6. 210 135
      main/admin/settings.php
  7. 220 135
      main/admin/user_add.php
  8. 220 157
      main/admin/user_edit.php
  9. 267 102
      main/announcements/announcements.php
  10. 446 334
      main/auth/profile.php
  11. 375 103
      main/calendar/agenda.inc.php
  12. 83 24
      main/calendar/agenda.php
  13. 198 141
      main/chat/chat_chat.php
  14. 340 242
      main/chat/chat_message.php
  15. 245 194
      main/conference/api.php
  16. 67 67
      main/conference/audiopost.php
  17. 11 13
      main/course_info/download.php
  18. 468 103
      main/coursecopy/classes/CourseRestorer.class.php
  19. 63 41
      main/coursecopy/copy_course.php
  20. 327 280
      main/coursecopy/copy_course_session.php
  21. 48 39
      main/coursecopy/create_backup.php
  22. 173 112
      main/coursecopy/import_backup.php
  23. 85 38
      main/create_course/add_course.php
  24. 645 435
      main/document/create_audio.php
  25. 394 256
      main/document/create_document.php
  26. 440 90
      main/document/document.inc.php
  27. 425 162
      main/document/document.php
  28. 445 231
      main/document/document_lite.php
  29. 434 303
      main/document/edit_document.php
  30. 139 89
      main/document/save_pixlr.php
  31. 489 417
      main/dropbox/dropbox_functions.inc.php
  32. 192 168
      main/dropbox/dropbox_submit.php
  33. 35 41
      main/exercice/GC.php
  34. 107 99
      main/exercice/Hpdownload.php
  35. 128 72
      main/exercice/admin.php
  36. 638 456
      main/exercice/exercice.php
  37. 430 109
      main/exercice/exercise.class.php
  38. 286 170
      main/exercice/exercise_report.php
  39. 579 527
      main/exercice/export/exercise_import.inc.php
  40. 40 35
      main/exercice/export/exercise_import.php
  41. 54 49
      main/exercice/feedback.php
  42. 64 35
      main/exercice/hotpotatoes.php
  43. 151 109
      main/exercice/hotpotatoes_exercise_report.php
  44. 43 36
      main/exercice/qti2.php
  45. 667 583
      main/exercice/question.class.php
  46. 10 11
      main/exercice/savescores.php
  47. 45 38
      main/exercice/showinframes.php
  48. 64 30
      main/exercice/upload_exercise.php
  49. 345 153
      main/forum/forumfunction.inc.php
  50. 406 348
      main/gradebook/gradebook_view_result.php
  51. 24 22
      main/gradebook/user_info.php
  52. 228 163
      main/inc/global.inc.php
  53. 224 62
      main/inc/lib/announcements.inc.php
  54. 637 546
      main/inc/lib/blog.lib.php
  55. 313 212
      main/inc/lib/document.lib.php
  56. 293 312
      main/inc/lib/fckeditor/editor/filemanager/connectors/php/commands.php
  57. 255 239
      main/inc/lib/fckeditor/editor/filemanager/connectors/php/io.php
  58. 934 868
      main/inc/lib/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php
  59. 76 44
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_create_folder.php
  60. 161 22
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_paste.php
  61. 100 72
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_upload.php
  62. 558 559
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/class.upload.php
  63. 102 63
      main/inc/lib/fckeditor/repository.php
  64. 0 661
      main/inc/lib/fileManage.lib.php
  65. 2127 0
      main/inc/lib/fileManager.lib.php
  66. 5 1498
      main/inc/lib/fileUpload.lib.php
  67. 19 13
      main/inc/lib/file_store.class.php
  68. 488 411
      main/inc/lib/groupmanager.lib.php
  69. 62 45
      main/inc/lib/jpegcam/webcam_receiver.php
  70. 560 442
      main/inc/lib/message.lib.php
  71. 482 412
      main/inc/lib/nanogong.lib.php
  72. 50 38
      main/inc/lib/nanogong/receiver.php
  73. 60 35
      main/inc/lib/search/xapian/XapianIndexer.class.php
  74. 135 139
      main/inc/lib/security.lib.php
  75. 30 31
      main/inc/lib/svg-edit/extensions/fileopen.php
  76. 129 80
      main/inc/lib/svg-edit/extensions/filesave.php
  77. 57 40
      main/inc/lib/wami-recorder/record_document.php
  78. 648 525
      main/install/index.php
  79. 345 186
      main/install/install.lib.php
  80. 56 54
      main/install/update-files-1.6.x-1.8.0.inc.php
  81. 499 403
      main/metadata/importmanifest.php
  82. 92 69
      main/mySpace/user_import.php
  83. 321 152
      main/newscorm/aicc.class.php
  84. 335 219
      main/newscorm/learnpath.class.php
  85. 224 93
      main/newscorm/learnpathItem.class.php
  86. 321 179
      main/newscorm/learnpath_functions.inc.php
  87. 155 128
      main/newscorm/lp_admin_view.php
  88. 45 35
      main/newscorm/openoffice_document.class.php
  89. 121 34
      main/newscorm/openoffice_presentation.class.php
  90. 113 48
      main/newscorm/openoffice_text.class.php
  91. 100 45
      main/newscorm/openoffice_text_document.class.php
  92. 452 181
      main/newscorm/resourcelinker.inc.php
  93. 323 209
      main/newscorm/resourcelinker.php
  94. 292 131
      main/newscorm/scorm.class.php
  95. 1708 1328
      main/resourcelinker/resourcelinker.inc.php
  96. 480 477
      main/resourcelinker/resourcelinker.php
  97. 11 11
      main/social/friends.php
  98. 56 43
      main/social/group_edit.php
  99. 107 26
      main/survey/create_new_survey.php
  100. 44 52
      main/upload/index.php

Fișier diff suprimat deoarece este prea mare
+ 557 - 483
main/admin/calendar.lib.php


Fișier diff suprimat deoarece este prea mare
+ 552 - 515
main/admin/configure_homepage.php


+ 83 - 69
main/admin/group_add.php

@@ -1,18 +1,16 @@
 <?php
 /* For licensing terms, see /dokeos_license.txt */
 /**
-*	@package chamilo.admin
-*/
+ * @package chamilo.admin
+ */
 
 // Language files that should be included
-$language_file = array('admin', 'registration','userInfo');
+$language_file = array('admin', 'registration', 'userInfo');
 
 $cidReset = true;
 
 // Including necessary libraries.
 require '../inc/global.inc.php';
-$libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileUpload.lib.php';
 
 // Section for the tabs
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -35,10 +33,10 @@ function text_longitud(){
 
 // Database table definitions
 if (!empty($_GET['message'])) {
-	$message = urldecode($_GET['message']);
+    $message = urldecode($_GET['message']);
 }
 
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $tool_name = get_lang('AddGroups');
 
 // Create the form
@@ -46,25 +44,35 @@ $form = new FormValidator('group_add');
 $form->addElement('header', $tool_name);
 
 // name
-$form->addElement('text', 'name', get_lang('Name'), array('size'=>60, 'maxlength'=>120));
+$form->addElement('text', 'name', get_lang('Name'), array('size' => 60, 'maxlength' => 120));
 $form->applyFilter('name', 'html_filter');
 $form->applyFilter('name', 'trim');
 $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
 
 // Description
-$form->addElement('textarea', 'description', get_lang('Description'), array('rows'=>3, 'cols'=>58, 'onKeyDown' => "text_longitud()", 'onKeyUp' => "text_longitud()"));
+$form->addElement(
+    'textarea',
+    'description',
+    get_lang('Description'),
+    array('rows' => 3, 'cols' => 58, 'onKeyDown' => "text_longitud()", 'onKeyUp' => "text_longitud()")
+);
 $form->applyFilter('description', 'html_filter');
 $form->applyFilter('description', 'trim');
 
 // url
-$form->addElement('text', 'url', get_lang('URL'), array('size'=>35));
+$form->addElement('text', 'url', get_lang('URL'), array('size' => 35));
 $form->applyFilter('url', 'html_filter');
 $form->applyFilter('url', 'trim');
 
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
-$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
+$allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
+$form->addRule(
+    'picture',
+    get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
+    'filetype',
+    $allowed_picture_types
+);
 
 //Group Parentship
 $groups = array();
@@ -76,8 +84,8 @@ $form->addElement('select', 'parent_group', get_lang('GroupParentship'), $groups
 
 // Status
 $status = array();
-$status[GROUP_PERMISSION_OPEN] 		= get_lang('Open');
-$status[GROUP_PERMISSION_CLOSED]	= get_lang('Closed');
+$status[GROUP_PERMISSION_OPEN] = get_lang('Open');
+$status[GROUP_PERMISSION_CLOSED] = get_lang('Closed');
 
 $form->addElement('select', 'visibility', get_lang('GroupPermissions'), $status);
 
@@ -90,70 +98,76 @@ $form->setDefaults($defaults);
 $form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
 
 // Validate form
-if( $form->validate()) {
-	$check = Security::check_token('post');
-	if ($check) {
-		$values = $form->exportValues();
-
-		$picture_element = $form->getElement('picture');
-		$picture 		= $picture_element->getValue();
-		$picture_uri 	= '';
-		$name 			= $values['name'];
-		$description	= $values['description'];
-		$url 			= $values['url'];
-		$status 		= intval($values['visibility']);
-		$picture 		= $_FILES['picture'];
+if ($form->validate()) {
+    $check = Security::check_token('post');
+    if ($check) {
+        $values = $form->exportValues();
+
+        $picture_element = $form->getElement('picture');
+        $picture = $picture_element->getValue();
+        $picture_uri = '';
+        $name = $values['name'];
+        $description = $values['description'];
+        $url = $values['url'];
+        $status = intval($values['visibility']);
+        $picture = $_FILES['picture'];
         $parent_group_id = intval($values['parent_group']);
 
-		$group_id = GroupPortalManager::add($name, $description, $url, $status);
-        GroupPortalManager::set_parent_group($group_id,$parent_group_id);
-
-		if (!empty($picture['name'])) {
-			$picture_uri = GroupPortalManager::update_group_picture($group_id, $_FILES['picture']['name'], $_FILES['picture']['tmp_name']);
-			GroupPortalManager::update($group_id, $name, $description, $url,$status, $picture_uri);
-		}
-
-		//@todo send emails
-
-/*		if (!empty($email) && $send_mail) {
-			$recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
-			$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
-
-			$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-			$email_admin = api_get_setting('emailAdministrator');
-
-			if ($_configuration['multiple_access_urls']) {
-				$access_url_id = api_get_current_access_url_id();
-				if ($access_url_id != -1) {
-					$url = api_get_access_url($access_url_id);
-					$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
-				}
-			}
-			else {
-				$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
-			}
-			api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
-		}*/
-
-		Security::clear_token();
-		$tok = Security::get_token();
-		header('Location: group_list.php?action=show_message&message='.urlencode(get_lang('GroupAdded')).'&sec_token='.$tok);
+        $group_id = GroupPortalManager::add($name, $description, $url, $status);
+        GroupPortalManager::set_parent_group($group_id, $parent_group_id);
+
+        if (!empty($picture['name'])) {
+            $picture_uri = GroupPortalManager::update_group_picture(
+                $group_id,
+                $_FILES['picture']['name'],
+                $_FILES['picture']['tmp_name']
+            );
+            GroupPortalManager::update($group_id, $name, $description, $url, $status, $picture_uri);
+        }
+
+        //@todo send emails
+
+        /*		if (!empty($email) && $send_mail) {
+                    $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
+                    $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
+
+                    $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+                    $email_admin = api_get_setting('emailAdministrator');
+
+                    if ($_configuration['multiple_access_urls']) {
+                        $access_url_id = api_get_current_access_url_id();
+                        if ($access_url_id != -1) {
+                            $url = api_get_access_url($access_url_id);
+                            $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
+                        }
+                    }
+                    else {
+                        $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
+                    }
+                    api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
+                }*/
+
+        Security::clear_token();
+        $tok = Security::get_token();
+        header(
+            'Location: group_list.php?action=show_message&message='.urlencode(get_lang('GroupAdded')).'&sec_token='.$tok
+        );
         exit ();
-	}
+    }
 } else {
-	if (isset($_POST['submit'])) {
-		Security::clear_token();
-	}
-	$token = Security::get_token();
-	$form->addElement('hidden', 'sec_token');
-	$form->setConstants(array('sec_token' => $token));
+    if (isset($_POST['submit'])) {
+        Security::clear_token();
+    }
+    $token = Security::get_token();
+    $form->addElement('hidden', 'sec_token');
+    $form->setConstants(array('sec_token' => $token));
 }
 
 // Display form
 Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
-if(!empty($message)){
-	Display::display_normal_message(stripslashes($message));
+if (!empty($message)) {
+    Display::display_normal_message(stripslashes($message));
 }
 $form->display();
 

+ 62 - 51
main/admin/group_edit.php

@@ -1,24 +1,20 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*	@package chamilo.admin
-
-*/
+ * @package chamilo.admin
+ */
 // Language files that should be included
-$language_file = array('admin','userInfo');
+$language_file = array('admin', 'userInfo');
 $cidReset = true;
 require_once '../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 
-$libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileUpload.lib.php';
-
 $group_id = isset($_GET['id']) ? intval($_GET['id']) : intval($_POST['id']);
 $tool_name = get_lang('GroupEdit');
 
-$interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => 'group_list.php','name' => get_lang('GroupList'));
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => 'group_list.php', 'name' => get_lang('GroupList'));
 
 $table_group = Database::get_main_table(TABLE_MAIN_GROUP);
 
@@ -38,8 +34,8 @@ function text_longitud(){
 $sql = "SELECT * FROM $table_group WHERE id = '".$group_id."'";
 $res = Database::query($sql);
 if (Database::num_rows($res) != 1) {
-	header('Location: group_list.php');
-	exit;
+    header('Location: group_list.php');
+    exit;
 }
 
 $group_data = Database::fetch_array($res, 'ASSOC');
@@ -50,26 +46,36 @@ $form->addElement('header', '', $tool_name);
 $form->addElement('hidden', 'id', $group_id);
 
 // name
-$form->addElement('text', 'name', get_lang('Name'), array('size'=>60, 'maxlength'=>120));
+$form->addElement('text', 'name', get_lang('Name'), array('size' => 60, 'maxlength' => 120));
 $form->applyFilter('name', 'html_filter');
 $form->applyFilter('name', 'trim');
 $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
 
 // Description
-$form->addElement('textarea', 'description', get_lang('Description'), array('rows'=>3, 'cols'=>58, 'onKeyDown' => "text_longitud()", 'onKeyUp' => "text_longitud()"));
+$form->addElement(
+    'textarea',
+    'description',
+    get_lang('Description'),
+    array('rows' => 3, 'cols' => 58, 'onKeyDown' => "text_longitud()", 'onKeyUp' => "text_longitud()")
+);
 $form->applyFilter('description', 'html_filter');
 $form->applyFilter('description', 'trim');
 
 // url
-$form->addElement('text', 'url', get_lang('URL'), array('size'=>35));
+$form->addElement('text', 'url', get_lang('URL'), array('size' => 35));
 $form->applyFilter('url', 'html_filter');
 $form->applyFilter('url', 'trim');
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
-$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
+$allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
+$form->addRule(
+    'picture',
+    get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
+    'filetype',
+    $allowed_picture_types
+);
 if (strlen($group_data['picture_uri']) > 0) {
-	$form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
+    $form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
 }
 
 //Group Parentship
@@ -82,8 +88,8 @@ $form->addElement('select', 'parent_group', get_lang('GroupParentship'), $groups
 
 // Status
 $status = array();
-$status[GROUP_PERMISSION_OPEN] 		= get_lang('Open');
-$status[GROUP_PERMISSION_CLOSED]	= get_lang('Closed');
+$status[GROUP_PERMISSION_OPEN] = get_lang('Open');
+$status[GROUP_PERMISSION_CLOSED] = get_lang('Closed');
 $form->addElement('select', 'visibility', get_lang('GroupPermissions'), $status, array());
 
 // Submit button
@@ -93,49 +99,54 @@ $form->addElement('style_submit_button', 'submit', get_lang('ModifyInformation')
 $form->setDefaults($group_data);
 
 // Validate form
-if ( $form->validate()) {
-	$group = $form->exportValues();
-
-	$picture_element = $form->getElement('picture');
-	$picture = $picture_element->getValue();
-
-	$picture_uri = $group_data['picture_uri'];
-	if ($group['delete_picture']) {
-		$picture_uri = GroupPortalManager::delete_group_picture($group_id);
-		}
-	elseif (!empty($picture['name'])) {
-		$picture_uri = GroupPortalManager::update_group_picture($group_id, $_FILES['picture']['name'], $_FILES['picture']['tmp_name']);
-	}
-
-	$name 			= $group['name'];
-	$description	= $group['description'];
-	$url 			= $group['url'];
-	$status 		= intval($group['visibility']);
-  $parent_group_id = intval($group['parent_group']);
-
-	GroupPortalManager::update($group_id, $name, $description, $url, $status, $picture_uri);
-  GroupPortalManager::set_parent_group($group_id,$parent_group_id);
-
-	$tok = Security::get_token();
-	header('Location: group_list.php?action=show_message&message='.urlencode(get_lang('GroupUpdated')).'&sec_token='.$tok);
-	exit();
+if ($form->validate()) {
+    $group = $form->exportValues();
+
+    $picture_element = $form->getElement('picture');
+    $picture = $picture_element->getValue();
+
+    $picture_uri = $group_data['picture_uri'];
+    if ($group['delete_picture']) {
+        $picture_uri = GroupPortalManager::delete_group_picture($group_id);
+    } elseif (!empty($picture['name'])) {
+        $picture_uri = GroupPortalManager::update_group_picture(
+            $group_id,
+            $_FILES['picture']['name'],
+            $_FILES['picture']['tmp_name']
+        );
+    }
+
+    $name = $group['name'];
+    $description = $group['description'];
+    $url = $group['url'];
+    $status = intval($group['visibility']);
+    $parent_group_id = intval($group['parent_group']);
+
+    GroupPortalManager::update($group_id, $name, $description, $url, $status, $picture_uri);
+    GroupPortalManager::set_parent_group($group_id, $parent_group_id);
+
+    $tok = Security::get_token();
+    header(
+        'Location: group_list.php?action=show_message&message='.urlencode(get_lang('GroupUpdated')).'&sec_token='.$tok
+    );
+    exit();
 }
 
 Display::display_header($tool_name);
 
 // Group picture
-$image_path = GroupPortalManager::get_group_picture_path_by_id($group_id,'web');
+$image_path = GroupPortalManager::get_group_picture_path_by_id($group_id, 'web');
 $image_dir = $image_path['dir'];
 $image = $image_path['file'];
 $image_file = ($image != '' ? $image_dir.$image : api_get_path(WEB_CODE_PATH).'img/unknown_group.jpg');
 $image_size = api_getimagesize($image_file);
 
 $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
-	.'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
-	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
+    .'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
+    .'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
 
 if ($image_size['width'] > 300) { //limit display width to 300px
-	$img_attributes .= 'width="300" ';
+    $img_attributes .= 'width="300" ';
 }
 
 // get the path,width and height from original picture
@@ -146,9 +157,9 @@ $big_image_height = $big_image_size['height'];
 $url_big_image = $big_image.'?rnd='.time();
 
 if ($image == '') {
-	echo '<img '.$img_attributes.' />';
+    echo '<img '.$img_attributes.' />';
 } else {
-	echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
+    echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
 }
 
 // Display form

Fișier diff suprimat deoarece este prea mare
+ 367 - 144
main/admin/settings.lib.php


+ 210 - 135
main/admin/settings.php

@@ -15,10 +15,12 @@
 // Language files that need to be included.
 if (isset($_GET['category']) && $_GET['category'] == 'Templates') {
     $language_file = array('admin', 'document');
-} else if(isset($_GET['category']) && $_GET['category'] == 'Gradebook') {
-    $language_file = array('admin', 'gradebook');
 } else {
-    $language_file = array('admin', 'document');
+    if (isset($_GET['category']) && $_GET['category'] == 'Gradebook') {
+        $language_file = array('admin', 'gradebook');
+    } else {
+        $language_file = array('admin', 'document');
+    }
 }
 $language_file[] = 'tracking';
 
@@ -27,7 +29,6 @@ $cidReset = true;
 
 // Including some necessary library files.
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once 'settings.lib.php';
 
 // Setting the section (for the tabs).
@@ -39,12 +40,17 @@ api_protect_admin_script();
 
 // Settings to avoid
 $settings_to_avoid = array(
-    'use_session_mode'                  => 'true',
-    'gradebook_enable'                  => 'false',
-    'example_material_course_creation'  => 'true' // ON by default - now we have this option when  we create a course
+    'use_session_mode' => 'true',
+    'gradebook_enable' => 'false',
+    'example_material_course_creation' => 'true' // ON by default - now we have this option when  we create a course
 );
 
-$convert_byte_to_mega_list = array('dropbox_max_filesize', 'message_max_upload_filesize', 'default_document_quotum', 'default_group_quotum');
+$convert_byte_to_mega_list = array(
+    'dropbox_max_filesize',
+    'message_max_upload_filesize',
+    'default_document_quotum',
+    'default_group_quotum'
+);
 
 if (isset($_POST['style'])) {
     Display::$preview_style = $_POST['style'];
@@ -66,16 +72,23 @@ if (isset($_GET['delete_watermark'])) {
     $watermark_deleted = PDF::delete_watermark();
 }
 
-if (isset($_GET['action']) &&  $_GET['action'] == 'delete_grading') {
-	$id = intval($_GET['id']);
-	api_delete_setting_option($id);
+if (isset($_GET['action']) && $_GET['action'] == 'delete_grading') {
+    $id = intval($_GET['id']);
+    api_delete_setting_option($id);
 }
 
-$form_search = new FormValidator('search_settings', 'get', api_get_self() , null, array('class'=>'well form-inline'));
+$form_search = new FormValidator('search_settings', 'get', api_get_self(), null, array('class' => 'well form-inline'));
 $form_search->addElement('text', 'search_field');
 $form_search->addElement('hidden', 'category', 'search_setting');
-$form_search->addElement('style_submit_button', 'submit_button', get_lang('Search'), 'value="submit_button", class="search"');
-$form_search->setDefaults(array('search_field' => (isset($_REQUEST['search_field'])?$_REQUEST['search_field']:null)));
+$form_search->addElement(
+    'style_submit_button',
+    'submit_button',
+    get_lang('Search'),
+    'value="submit_button", class="search"'
+);
+$form_search->setDefaults(
+    array('search_field' => (isset($_REQUEST['search_field']) ? $_REQUEST['search_field'] : null))
+);
 
 $form_search_html = $form_search->return_form();
 
@@ -83,7 +96,8 @@ $url_id = api_get_current_access_url_id();
 
 $settings = null;
 
-function get_settings($category = null) {
+function get_settings($category = null)
+{
     $url_id = api_get_current_access_url_id();
     $settings_by_access_list = array();
 
@@ -98,26 +112,31 @@ function get_settings($category = null) {
             $settings_by_access = api_get_settings($category, 'group', $url_id, 1);
 
             foreach ($settings_by_access as $row) {
-                if (empty($row['variable']))
+                if (empty($row['variable'])) {
                     $row['variable'] = 0;
-                if (empty($row['subkey']))
+                }
+                if (empty($row['subkey'])) {
                     $row['subkey'] = 0;
-                if (empty($row['category']))
+                }
+                if (empty($row['category'])) {
                     $row['category'] = 0;
+                }
 
                 // One more validation if is changeable.
-                if ($row['access_url_changeable'] == 1)
-                    $settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ]  = $row;
-                else
-                    $settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ]  = array();
+                if ($row['access_url_changeable'] == 1) {
+                    $settings_by_access_list[$row['variable']] [$row['subkey']] [$row['category']] = $row;
+                } else {
+                    $settings_by_access_list[$row['variable']] [$row['subkey']] [$row['category']] = array();
+                }
             }
         }
     }
-    if (isset($category) && $category== 'search_setting') {
+    if (isset($category) && $category == 'search_setting') {
         if (!empty($_REQUEST['search_field'])) {
             $settings = search_setting($_REQUEST['search_field']);
         }
     }
+
     return array('settings' => $settings, 'settings_by_access_list' => $settings_by_access_list);
 }
 
@@ -158,12 +177,12 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
                             $changeable = 1;
                         }
 
-                        $params = array('variable = ?' =>  array($key));
+                        $params = array('variable = ?' => array($key));
                         $data = api_get_settings_params($params);
 
                         if (!empty($data)) {
                             foreach ($data as $item) {
-                                $params = array('id' =>$item['id'], 'access_url_changeable' => $changeable);
+                                $params = array('id' => $item['id'], 'access_url_changeable' => $changeable);
                                 api_set_setting_simple($params);
                             }
                         }
@@ -179,21 +198,26 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         $pdf_export_watermark_path = $_FILES['pdf_export_watermark_path'];
 
         if (isset($pdf_export_watermark_path) && !empty($pdf_export_watermark_path['name'])) {
-            $pdf_export_watermark_path_result = PDF::upload_watermark($pdf_export_watermark_path['name'], $pdf_export_watermark_path['tmp_name']);
+            $pdf_export_watermark_path_result = PDF::upload_watermark(
+                $pdf_export_watermark_path['name'],
+                $pdf_export_watermark_path['tmp_name']
+            );
             if ($pdf_export_watermark_path_result) {
                 $message['confirmation'][] = get_lang('UplUploadSucceeded');
             } else {
-                $message['warning'][] = get_lang('UplUnableToSaveFile').' '.get_lang('Folder').': '.api_get_path(SYS_CODE_PATH).'default_course_document/images';
+                $message['warning'][] = get_lang('UplUnableToSaveFile').' '.get_lang('Folder').': '.api_get_path(
+                    SYS_CODE_PATH
+                ).'default_course_document/images';
             }
             unset($update_values['pdf_export_watermark_path']);
         }
 
         // Set true for allow_message_tool variable if social tool is actived
         foreach ($convert_byte_to_mega_list as $item) {
-			if (isset($values[$item])) {
-				$values[$item]        = round($values[$item]*1024*1024);
-			}
-		}
+            if (isset($values[$item])) {
+                $values[$item] = round($values[$item] * 1024 * 1024);
+            }
+        }
 
         if ($values['allow_social_tool'] == 'true') {
             $values['allow_message_tool'] = 'true';
@@ -222,10 +246,16 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
 
         foreach ($settings as $item) {
             $key = $item['variable'];
-            if (in_array($key, $settings_to_avoid)) { continue; }
-            if ($key == 'search_field' or $key == 'submit_fixed_in_bottom') { continue; }
+            if (in_array($key, $settings_to_avoid)) {
+                continue;
+            }
+            if ($key == 'search_field' or $key == 'submit_fixed_in_bottom') {
+                continue;
+            }
             $key = Database::escape_string($key);
-            $sql = "UPDATE $table_settings_current SET selected_value = 'false' WHERE variable = '".$key."' AND access_url = ".intval($url_id)."  AND type IN ('checkbox', 'radio') ";
+            $sql = "UPDATE $table_settings_current SET selected_value = 'false' WHERE variable = '".$key."' AND access_url = ".intval(
+                $url_id
+            )."  AND type IN ('checkbox', 'radio') ";
             $res = Database::query($sql);
         }
 
@@ -237,82 +267,115 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         $keys = array();
 
         foreach ($values as $key => $value) {
-            if (in_array($key, $settings_to_avoid)) { continue; }
+            if (in_array($key, $settings_to_avoid)) {
+                continue;
+            }
             // Avoid form elements which have nothing to do with settings
-            if ($key == 'search_field' or $key == 'submit_fixed_in_bottom') { continue; }
+            if ($key == 'search_field' or $key == 'submit_fixed_in_bottom') {
+                continue;
+            }
 
             // Treat gradebook values in separate function.
             //if (strpos($key, 'gradebook_score_display_custom_values') === false) {
-                if (!is_array($value)) {
-                    $old_value = api_get_setting($key);
-                    switch ($key) {
-                    	case 'header_extra_content':
-                    		file_put_contents(api_get_path(SYS_PATH).api_get_home_path().'/header_extra_content.txt', $value);
-                    		$value = api_get_home_path().'/header_extra_content.txt';
-                    		break;
-                    	case 'footer_extra_content':
-                    		file_put_contents(api_get_path(SYS_PATH).api_get_home_path().'/footer_extra_content.txt', $value);
-                    		$value = api_get_home_path().'/footer_extra_content.txt';
-                    		break;
-                        // URL validation for some settings.
-                        case 'InstitutionUrl':
-                        case 'course_validation_terms_and_conditions_url':
-                            $value = trim(Security::remove_XSS($value));
-                            if ($value != '') {
-                                // Here we accept absolute URLs only.
-                                if (strpos($value, '://') === false) {
-                                    $value = 'http://'.$value;
-                                }
-                                if (!api_valid_url($value, true)) {
-                                    // If the new (non-empty) URL value is invalid, then the old URL value stays.
-                                    $value = $old_value;
-                                }
+            if (!is_array($value)) {
+                $old_value = api_get_setting($key);
+                switch ($key) {
+                    case 'header_extra_content':
+                        file_put_contents(
+                            api_get_path(SYS_PATH).api_get_home_path().'/header_extra_content.txt',
+                            $value
+                        );
+                        $value = api_get_home_path().'/header_extra_content.txt';
+                        break;
+                    case 'footer_extra_content':
+                        file_put_contents(
+                            api_get_path(SYS_PATH).api_get_home_path().'/footer_extra_content.txt',
+                            $value
+                        );
+                        $value = api_get_home_path().'/footer_extra_content.txt';
+                        break;
+                    // URL validation for some settings.
+                    case 'InstitutionUrl':
+                    case 'course_validation_terms_and_conditions_url':
+                        $value = trim(Security::remove_XSS($value));
+                        if ($value != '') {
+                            // Here we accept absolute URLs only.
+                            if (strpos($value, '://') === false) {
+                                $value = 'http://'.$value;
                             }
-                            // If the new URL value is empty, then it will be stored (i.e. the setting will be deleted).
-                            break;
-
-                        // Validation against e-mail address for some settings.
-                        case 'emailAdministrator':
-                            $value = trim(Security::remove_XSS($value));
-                            if ($value != '' && !api_valid_email($value)) {
-                                // If the new (non-empty) e-mail address is invalid, then the old e-mail address stays.
-                                // If the new e-mail address is empty, then it will be stored (i.e. the setting will be deleted).
+                            if (!api_valid_url($value, true)) {
+                                // If the new (non-empty) URL value is invalid, then the old URL value stays.
                                 $value = $old_value;
                             }
-                            break;
-                    }
-                    if ($old_value != $value) $keys[] = $key;
-                    $result = api_set_setting($key, $value, null, null, $url_id);
-                } else {
-                    $sql = "SELECT subkey FROM $table_settings_current WHERE variable = '$key'";
-                    $res = Database::query($sql);
-                    while ($row_subkeys = Database::fetch_array($res)) {
-                        // If subkey is changed:
-                        if ((isset($value[$row_subkeys['subkey']]) && api_get_setting($key, $row_subkeys['subkey']) == 'false') ||
-                            (!isset($value[$row_subkeys['subkey']]) && api_get_setting($key, $row_subkeys['subkey']) == 'true')) {
-                            $keys[] = $key;
-                            break;
                         }
+                        // If the new URL value is empty, then it will be stored (i.e. the setting will be deleted).
+                        break;
+
+                    // Validation against e-mail address for some settings.
+                    case 'emailAdministrator':
+                        $value = trim(Security::remove_XSS($value));
+                        if ($value != '' && !api_valid_email($value)) {
+                            // If the new (non-empty) e-mail address is invalid, then the old e-mail address stays.
+                            // If the new e-mail address is empty, then it will be stored (i.e. the setting will be deleted).
+                            $value = $old_value;
+                        }
+                        break;
+                }
+                if ($old_value != $value) {
+                    $keys[] = $key;
+                }
+                $result = api_set_setting($key, $value, null, null, $url_id);
+            } else {
+                $sql = "SELECT subkey FROM $table_settings_current WHERE variable = '$key'";
+                $res = Database::query($sql);
+                while ($row_subkeys = Database::fetch_array($res)) {
+                    // If subkey is changed:
+                    if ((isset($value[$row_subkeys['subkey']]) && api_get_setting(
+                        $key,
+                        $row_subkeys['subkey']
+                    ) == 'false') ||
+                        (!isset($value[$row_subkeys['subkey']]) && api_get_setting(
+                            $key,
+                            $row_subkeys['subkey']
+                        ) == 'true')
+                    ) {
+                        $keys[] = $key;
+                        break;
                     }
-                    foreach ($value as $subkey => $subvalue) {
-                        $result = api_set_setting($key, 'true', $subkey, null, $url_id);
-                    }
-
                 }
+                foreach ($value as $subkey => $subvalue) {
+                    $result = api_set_setting($key, 'true', $subkey, null, $url_id);
+                }
+
+            }
         }
 
         // Add event configuration settings category to the system log.
         $user_id = api_get_user_id();
         $category = $_GET['category'];
-        event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
+        event_system(
+            LOG_CONFIGURATION_SETTINGS_CHANGE,
+            LOG_CONFIGURATION_SETTINGS_CATEGORY,
+            $category,
+            api_get_utc_datetime(),
+            $user_id
+        );
 
         api_set_setting_last_update();
 
         // Add event configuration settings variable to the system log.
         if (is_array($keys) && count($keys) > 0) {
             foreach ($keys as $variable) {
-                if (in_array($key, $settings_to_avoid)) { continue; }
-                event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, api_get_utc_datetime(), $user_id);
+                if (in_array($key, $settings_to_avoid)) {
+                    continue;
+                }
+                event_system(
+                    LOG_CONFIGURATION_SETTINGS_CHANGE,
+                    LOG_CONFIGURATION_SETTINGS_VARIABLE,
+                    $variable,
+                    api_get_utc_datetime(),
+                    $user_id
+                );
             }
         }
     }
@@ -350,30 +413,30 @@ $htmlHeadXtra[] = '<script>
 Display :: display_header($tool_name);
 
 // The action images.
-$action_images['platform']      = 'platform.png';
-$action_images['course']        = 'course.png';
-$action_images['session']       = 'session.png';
-$action_images['tools']         = 'tools.png';
-$action_images['user']          = 'user.png';
-$action_images['gradebook']     = 'gradebook.png';
-$action_images['ldap']          = 'ldap.png';
-$action_images['cas'] 	        = 'user_access.png';
-$action_images['security']      = 'security.png';
-$action_images['languages']     = 'languages.png';
-$action_images['tuning']        = 'tuning.png';
-$action_images['templates']     = 'template.png';
-$action_images['search']        = 'search.png';
-$action_images['editor']        = 'html_editor.png';
-$action_images['timezones']     = 'timezone.png';
-$action_images['extra']     	= 'wizard.png';
-$action_images['tracking']     	= 'statistics.png';
-$action_images['gradebook']     = 'gradebook.png';
-$action_images['search']        = 'search.png';
-$action_images['stylesheets']   = 'stylesheets.png';
-$action_images['templates']     = 'template.png';
-$action_images['plugins']       = 'plugins.png';
-$action_images['shibboleth']    = 'shibboleth.png';
-$action_images['facebook']      = 'facebook.png';
+$action_images['platform'] = 'platform.png';
+$action_images['course'] = 'course.png';
+$action_images['session'] = 'session.png';
+$action_images['tools'] = 'tools.png';
+$action_images['user'] = 'user.png';
+$action_images['gradebook'] = 'gradebook.png';
+$action_images['ldap'] = 'ldap.png';
+$action_images['cas'] = 'user_access.png';
+$action_images['security'] = 'security.png';
+$action_images['languages'] = 'languages.png';
+$action_images['tuning'] = 'tuning.png';
+$action_images['templates'] = 'template.png';
+$action_images['search'] = 'search.png';
+$action_images['editor'] = 'html_editor.png';
+$action_images['timezones'] = 'timezone.png';
+$action_images['extra'] = 'wizard.png';
+$action_images['tracking'] = 'statistics.png';
+$action_images['gradebook'] = 'gradebook.png';
+$action_images['search'] = 'search.png';
+$action_images['stylesheets'] = 'stylesheets.png';
+$action_images['templates'] = 'template.png';
+$action_images['plugins'] = 'plugins.png';
+$action_images['shibboleth'] = 'shibboleth.png';
+$action_images['facebook'] = 'facebook.png';
 
 $action_array = array();
 $resultcategories = array();
@@ -403,7 +466,12 @@ $resultcategories[] = array('category' => 'Facebook');
 foreach ($resultcategories as $row) {
     $url = array();
     $url['url'] = api_get_self()."?category=".$row['category'];
-    $url['content'] = Display::return_icon($action_images[strtolower($row['category'])], api_ucfirst(get_lang($row['category'])),'',ICON_SIZE_MEDIUM);
+    $url['content'] = Display::return_icon(
+        $action_images[strtolower($row['category'])],
+        api_ucfirst(get_lang($row['category'])),
+        '',
+        ICON_SIZE_MEDIUM
+    );
     if (strtolower($row['category']) == strtolower($_GET['category'])) {
         $url['active'] = true;
     }
@@ -425,8 +493,8 @@ if (isset($form) && $form->validate()) {
 
     Display::display_confirmation_message(get_lang('SettingsStored'));
     if (is_array($message)) {
-        foreach($message as $type => $content) {
-            foreach($content as $msg) {
+        foreach ($message as $type => $content) {
+            foreach ($content as $msg) {
                 echo Display::return_message($msg, $type);
             }
         }
@@ -447,7 +515,13 @@ if (!empty($_GET['category'])) {
                     // add event to system log
                     $user_id = api_get_user_id();
                     $category = $_GET['category'];
-                    event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
+                    event_system(
+                        LOG_CONFIGURATION_SETTINGS_CHANGE,
+                        LOG_CONFIGURATION_SETTINGS_CATEGORY,
+                        $category,
+                        api_get_utc_datetime(),
+                        $user_id
+                    );
                     Display :: display_confirmation_message(get_lang('DashboardPluginsHaveBeenUpdatedSucesslly'));
                 }
             }
@@ -457,23 +531,23 @@ if (!empty($_GET['category'])) {
                 });
                 </script>';
             echo '<div id="tabs">';
-                echo '<ul>';
-                echo '<li><a href="#tabs-1">'.get_lang('Plugins').'</a></li>';
-                echo '<li><a href="#tabs-2">'.get_lang('DashboardPlugins').'</a></li>';
-                echo '<li><a href="#tabs-3">'.get_lang('ConfigureExtensions').'</a></li>';
-                echo '</ul>';
-
-                echo '<div id="tabs-1">';
-                handle_plugins();
-                echo '</div>';
-
-                echo '<div id="tabs-2">';
-                DashboardManager::handle_dashboard_plugins();
-                echo '</div>';
-
-                echo '<div id="tabs-3">';
-                handle_extensions();
-                echo '</div>';
+            echo '<ul>';
+            echo '<li><a href="#tabs-1">'.get_lang('Plugins').'</a></li>';
+            echo '<li><a href="#tabs-2">'.get_lang('DashboardPlugins').'</a></li>';
+            echo '<li><a href="#tabs-3">'.get_lang('ConfigureExtensions').'</a></li>';
+            echo '</ul>';
+
+            echo '<div id="tabs-1">';
+            handle_plugins();
+            echo '</div>';
+
+            echo '<div id="tabs-2">';
+            DashboardManager::handle_dashboard_plugins();
+            echo '</div>';
+
+            echo '<div id="tabs-3">';
+            handle_extensions();
+            echo '</div>';
             echo '</div>';
             break;
         case 'Stylesheets':
@@ -493,8 +567,9 @@ if (!empty($_GET['category'])) {
             }
             break;
         default:
-            if (isset($form))
+            if (isset($form)) {
                 $form->display();
+            }
     }
 }
 

+ 220 - 135
main/admin/user_add.php

@@ -1,16 +1,14 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*	@package chamilo.admin
-*/
+ * @package chamilo.admin
+ */
 
 // Language files that should be included
 $language_file = array('admin', 'registration');
 $cidReset = true;
 // Including necessary libraries.
 require_once '../inc/global.inc.php';
-$libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileUpload.lib.php';
 
 // Section for the tabs
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -22,8 +20,12 @@ $is_platform_admin = api_is_platform_admin() ? 1 : 0;
 
 $message = null;
 
-$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
-$htmlHeadXtra[] = '<link href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
+$htmlHeadXtra[] = '<script src="'.api_get_path(
+    WEB_LIBRARY_PATH
+).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
+$htmlHeadXtra[] = '<link href="'.api_get_path(
+    WEB_LIBRARY_PATH
+).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
 $htmlHeadXtra[] = '
 <script>
 <!--
@@ -65,38 +67,38 @@ function display_drh_list(){
 </script>';
 
 if (!empty($_GET['message'])) {
-	$message = urldecode($_GET['message']);
+    $message = urldecode($_GET['message']);
 }
 
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ("url" => 'user_list.php', "name" => get_lang('UserList'));
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array("url" => 'user_list.php', "name" => get_lang('UserList'));
 $tool_name = get_lang('AddUsers');
 
 // Create the form
 $form = new FormValidator('user_add');
 $form->addElement('header', '', $tool_name);
 if (api_is_western_name_order()) {
-	// Firstname
-	$form->addElement('text', 'firstname', get_lang('FirstName'));
-	$form->applyFilter('firstname', 'html_filter');
-	$form->applyFilter('firstname', 'trim');
-	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
-	// Lastname
-	$form->addElement('text', 'lastname', get_lang('LastName'));
-	$form->applyFilter('lastname', 'html_filter');
-	$form->applyFilter('lastname', 'trim');
-	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+    // Firstname
+    $form->addElement('text', 'firstname', get_lang('FirstName'));
+    $form->applyFilter('firstname', 'html_filter');
+    $form->applyFilter('firstname', 'trim');
+    $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+    // Lastname
+    $form->addElement('text', 'lastname', get_lang('LastName'));
+    $form->applyFilter('lastname', 'html_filter');
+    $form->applyFilter('lastname', 'trim');
+    $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
 } else {
-	// Lastname
-	$form->addElement('text', 'lastname', get_lang('LastName'));
-	$form->applyFilter('lastname', 'html_filter');
-	$form->applyFilter('lastname', 'trim');
-	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
-	// Firstname
-	$form->addElement('text', 'firstname', get_lang('FirstName'));
-	$form->applyFilter('firstname', 'html_filter');
-	$form->applyFilter('firstname', 'trim');
-	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+    // Lastname
+    $form->addElement('text', 'lastname', get_lang('LastName'));
+    $form->applyFilter('lastname', 'html_filter');
+    $form->applyFilter('lastname', 'trim');
+    $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+    // Firstname
+    $form->addElement('text', 'firstname', get_lang('FirstName'));
+    $form->applyFilter('firstname', 'html_filter');
+    $form->applyFilter('firstname', 'trim');
+    $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 }
 // Official code
 $form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => '40'));
@@ -110,7 +112,12 @@ if (api_get_setting('registration', 'email') == 'true') {
 }
 
 if (api_get_setting('login_is_email') == 'true') {
-    $form->addRule('email', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
+    $form->addRule(
+        'email',
+        sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH),
+        'maxlength',
+        USERNAME_MAX_LENGTH
+    );
     $form->addRule('email', get_lang('UserTaken'), 'username_available');
 }
 
@@ -118,15 +125,25 @@ if (api_get_setting('login_is_email') == 'true') {
 $form->addElement('text', 'phone', get_lang('PhoneNumber'));
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
-$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
+$allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
 
-$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
+$form->addRule(
+    'picture',
+    get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
+    'filetype',
+    $allowed_picture_types
+);
 
 // Username
 if (api_get_setting('login_is_email') != 'true') {
     $form->addElement('text', 'username', get_lang('LoginName'), array('maxlength' => USERNAME_MAX_LENGTH));
     $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
-    $form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
+    $form->addRule(
+        'username',
+        sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH),
+        'maxlength',
+        USERNAME_MAX_LENGTH
+    );
     $form->addRule('username', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
     $form->addRule('username', get_lang('UserTaken'), 'username_available');
 }
@@ -136,26 +153,37 @@ $group = array();
 $auth_sources = 0; //make available wider as we need it in case of form reset (see below)
 $nb_ext_auth_source_added = 0;
 if (count($extAuthSource) > 0) {
-	$auth_sources = array();
-	foreach($extAuthSource as $key => $info) {
-	    // @todo : make uniform external authentification configuration (ex : cas and external_login ldap)
-	    // Special case for CAS. CAS is activated from Chamilo > Administration > Configuration > CAS
-	    // extAuthSource always on for CAS even if not activated
-	    // same action for file user_edit.php
-	    if (($key == CAS_AUTH_SOURCE && api_get_setting('cas_activate') === 'true') || ($key != CAS_AUTH_SOURCE)) {
-		    $auth_sources[$key] = $key;
-    		$nb_ext_auth_source_added++;
-		}
-	}
-	if ($nb_ext_auth_source_added > 0) {
-    	$group[] = $form->createElement('radio', 'password_auto', null, get_lang('ExternalAuthentication').' ', 2);
-    	$group[] = $form->createElement('select', 'auth_source', null, $auth_sources);
-    	$group[] = $form->createElement('static', '', '', '<br />');
+    $auth_sources = array();
+    foreach ($extAuthSource as $key => $info) {
+        // @todo : make uniform external authentification configuration (ex : cas and external_login ldap)
+        // Special case for CAS. CAS is activated from Chamilo > Administration > Configuration > CAS
+        // extAuthSource always on for CAS even if not activated
+        // same action for file user_edit.php
+        if (($key == CAS_AUTH_SOURCE && api_get_setting('cas_activate') === 'true') || ($key != CAS_AUTH_SOURCE)) {
+            $auth_sources[$key] = $key;
+            $nb_ext_auth_source_added++;
+        }
+    }
+    if ($nb_ext_auth_source_added > 0) {
+        $group[] = $form->createElement('radio', 'password_auto', null, get_lang('ExternalAuthentication').' ', 2);
+        $group[] = $form->createElement('select', 'auth_source', null, $auth_sources);
+        $group[] = $form->createElement('static', '', '', '<br />');
     }
 }
-$group[] = $form->createElement('radio', 'password_auto', get_lang('Password'), get_lang('AutoGeneratePassword').'<br />', 1);
+$group[] = $form->createElement(
+    'radio',
+    'password_auto',
+    get_lang('Password'),
+    get_lang('AutoGeneratePassword').'<br />',
+    1
+);
 $group[] = $form->createElement('radio', 'password_auto', 'id="radio_user_password"', null, 0);
-$group[] = $form->createElement('password', 'password', null, array('onkeydown' => 'javascript: password_switch_radio_button();'));
+$group[] = $form->createElement(
+    'password',
+    'password',
+    null,
+    array('onkeydown' => 'javascript: password_switch_radio_button();')
+);
 $form->addGroup($group, 'password', get_lang('Password'), '');
 
 // Status
@@ -165,18 +193,24 @@ $status[STUDENT] = get_lang('Learner');
 $status[DRH] = get_lang('Drh');
 $status[SESSIONADMIN] = get_lang('SessionsAdmin');
 
-$form->addElement('select', 'status', get_lang('Profile'), $status, array('id' => 'status_select', 'class'=>'chzn-select', 'onchange' => 'javascript: display_drh_list();'));
+$form->addElement(
+    'select',
+    'status',
+    get_lang('Profile'),
+    $status,
+    array('id' => 'status_select', 'class' => 'chzn-select', 'onchange' => 'javascript: display_drh_list();')
+);
 
 //drh list (display only if student)
-$display = isset($_POST['status']) && $_POST['status'] == STUDENT  || !isset($_POST['status']) ? 'block' : 'none';
+$display = isset($_POST['status']) && $_POST['status'] == STUDENT || !isset($_POST['status']) ? 'block' : 'none';
 
 //@todo remove the drh list here. This code is unused
 $form->addElement('html', '<div id="drh_list" style="display:'.$display.';">');
 
 if (isset($drh_list) && is_array($drh_list)) {
-	foreach ($drh_list as $drh) {
-		$drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']);
-	}
+    foreach ($drh_list as $drh) {
+        $drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']);
+    }
 }
 $form->addElement('html', '</div>');
 
@@ -200,9 +234,14 @@ $group[] = $form->createElement('radio', 'send_mail', null, get_lang('No'), 0);
 $form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;');
 // Expiration Date
 $form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
-$group = array ();
+$group = array();
 $group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-$group[] = $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
+$group[] = $form->createElement(
+    'datepicker',
+    'expiration_date',
+    null,
+    array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();')
+);
 $form->addGroup($group, 'max_member_group', null, '', false);
 // Active account or inactive account
 $form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
@@ -214,7 +253,7 @@ $return_params = ExtraField::set_extra_fields_in_form($form, $extra_data, 'user_
 $jquery_ready_content = $return_params['jquery_ready_content'];
 
 // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function
-$htmlHeadXtra[] ='<script>
+$htmlHeadXtra[] = '<script>
 $(document).ready(function(){
 	'.$jquery_ready_content.'
 });
@@ -237,97 +276,143 @@ $defaults = array_merge($defaults, $extra_data);
 $form->setDefaults($defaults);
 
 // Submit button
-$html_results_enabled[] = $form-> createElement ('style_submit_button', 'submit_plus', get_lang('Add').'+', 'class="add"');
-$html_results_enabled[] = $form-> createElement ('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
+$html_results_enabled[] = $form->createElement(
+    'style_submit_button',
+    'submit_plus',
+    get_lang('Add').'+',
+    'class="add"'
+);
+$html_results_enabled[] = $form->createElement('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
 $form->addGroup($html_results_enabled);
 
 // Validate form
-if( $form->validate()) {
-	$check = Security::check_token('post');
-	if ($check) {
-		$user = $form->exportValues();
-		$lastname       = $user['lastname'];
-		$firstname      = $user['firstname'];
-		$official_code  = $user['official_code'];
-		$email          = $user['email'];
-		$phone          = $user['phone'];
-		$username       = $user['username'];
-		$status         = intval($user['status']);
-		$language       = $user['language'];
-		$picture        = $_FILES['picture'];
-		$platform_admin = intval($user['admin']['platform_admin']);
-		$send_mail      = intval($user['mail']['send_mail']);
-		$hr_dept_id     = intval($user['hr_dept_id']);
-
-		if (count($extAuthSource) > 0 && $user['password']['password_auto'] == '2') {
-			$auth_source = $user['password']['auth_source'];
-			$password = 'PLACEHOLDER';
-		} else {
-			$auth_source = PLATFORM_AUTH_SOURCE;
-			$password = $user['password']['password_auto'] == '1' ? api_generate_password() : $user['password']['password'];
-		}
+if ($form->validate()) {
+    $check = Security::check_token('post');
+    if ($check) {
+        $user = $form->exportValues();
+        $lastname = $user['lastname'];
+        $firstname = $user['firstname'];
+        $official_code = $user['official_code'];
+        $email = $user['email'];
+        $phone = $user['phone'];
+        $username = $user['username'];
+        $status = intval($user['status']);
+        $language = $user['language'];
+        $picture = $_FILES['picture'];
+        $platform_admin = intval($user['admin']['platform_admin']);
+        $send_mail = intval($user['mail']['send_mail']);
+        $hr_dept_id = intval($user['hr_dept_id']);
+
+        if (count($extAuthSource) > 0 && $user['password']['password_auto'] == '2') {
+            $auth_source = $user['password']['auth_source'];
+            $password = 'PLACEHOLDER';
+        } else {
+            $auth_source = PLATFORM_AUTH_SOURCE;
+            $password = $user['password']['password_auto'] == '1' ? api_generate_password(
+            ) : $user['password']['password'];
+        }
 
-		if ($user['radio_expiration_date'] == '1') {
-			$expiration_date = $user['expiration_date'];
-		} else {
-			$expiration_date = '0000-00-00 00:00:00';
-		}
+        if ($user['radio_expiration_date'] == '1') {
+            $expiration_date = $user['expiration_date'];
+        } else {
+            $expiration_date = '0000-00-00 00:00:00';
+        }
 
-		$active = intval($user['active']);
+        $active = intval($user['active']);
 
         if (api_get_setting('login_is_email') == 'true') {
             $username = $email;
         }
 
-		$user_id = UserManager::create_user($firstname, $lastname, $status, $email, $username, $password, $official_code, $language, $phone, null, $auth_source, $expiration_date, $active, $hr_dept_id, null, null, $send_mail);
-
-		Security::clear_token();
-		$tok = Security::get_token();
-		if ($user_id === false) {
-			//If any error ocurred during user creation, print it (api_failureList
-			// stores values as separate words, so rework it
-			$message = '';
-			$message_bits = explode(' ',api_get_last_failure());
-			foreach ($message_bits as $bit) {
-				$message .= ucfirst($bit);
-			}
-		} else {
- 			if (!empty($picture['name'])) {
-				$picture_uri = UserManager::update_user_picture($user_id, $_FILES['picture']['name'], $_FILES['picture']['tmp_name']);
-				UserManager::update_user($user_id, $firstname, $lastname, $username, $password, $auth_source, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, null, $hr_dept_id, null, $language);
-			}
-
-			foreach ($user as $key => $value) {
-				if (substr($key, 0, 6) == 'extra_') { //an extra field
-					UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
-				}
-			}
-			if ($platform_admin) {
+        $user_id = UserManager::create_user(
+            $firstname,
+            $lastname,
+            $status,
+            $email,
+            $username,
+            $password,
+            $official_code,
+            $language,
+            $phone,
+            null,
+            $auth_source,
+            $expiration_date,
+            $active,
+            $hr_dept_id,
+            null,
+            null,
+            $send_mail
+        );
+
+        Security::clear_token();
+        $tok = Security::get_token();
+        if ($user_id === false) {
+            //If any error ocurred during user creation, print it (api_failureList
+            // stores values as separate words, so rework it
+            $message = '';
+            $message_bits = explode(' ', api_get_last_failure());
+            foreach ($message_bits as $bit) {
+                $message .= ucfirst($bit);
+            }
+        } else {
+            if (!empty($picture['name'])) {
+                $picture_uri = UserManager::update_user_picture(
+                    $user_id,
+                    $_FILES['picture']['name'],
+                    $_FILES['picture']['tmp_name']
+                );
+                UserManager::update_user(
+                    $user_id,
+                    $firstname,
+                    $lastname,
+                    $username,
+                    $password,
+                    $auth_source,
+                    $email,
+                    $status,
+                    $official_code,
+                    $phone,
+                    $picture_uri,
+                    $expiration_date,
+                    $active,
+                    null,
+                    $hr_dept_id,
+                    null,
+                    $language
+                );
+            }
+
+            foreach ($user as $key => $value) {
+                if (substr($key, 0, 6) == 'extra_') { //an extra field
+                    UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
+                }
+            }
+            if ($platform_admin) {
                 UserManager::add_user_as_admin($user_id);
-			}
-			$message = get_lang('UserAdded');
-		}
-		if (isset($user['submit_plus'])) {
-			//we want to add more. Prepare report message and redirect to the same page (to clean the form)
-			header('Location: user_add.php?message='.urlencode($message).'&sec_token='.$tok);
-			exit ();
-		} else {
-			$tok = Security::get_token();
-			header('Location: user_list.php?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
-			exit ();
-		}
-	}
+            }
+            $message = get_lang('UserAdded');
+        }
+        if (isset($user['submit_plus'])) {
+            //we want to add more. Prepare report message and redirect to the same page (to clean the form)
+            header('Location: user_add.php?message='.urlencode($message).'&sec_token='.$tok);
+            exit ();
+        } else {
+            $tok = Security::get_token();
+            header('Location: user_list.php?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
+            exit ();
+        }
+    }
 } else {
-	if (isset($_POST['submit'])) {
-		Security::clear_token();
-	}
-	$token = Security::get_token();
-	$form->addElement('hidden', 'sec_token');
-	$form->setConstants(array('sec_token' => $token));
+    if (isset($_POST['submit'])) {
+        Security::clear_token();
+    }
+    $token = Security::get_token();
+    $form->addElement('hidden', 'sec_token');
+    $form->setConstants(array('sec_token' => $token));
 }
 
-if (!empty($message)){
-	$message = Display::return_message(stripslashes($message));
+if (!empty($message)) {
+    $message = Display::return_message(stripslashes($message));
 }
 $content = $form->return_form();
 

+ 220 - 157
main/admin/user_edit.php

@@ -1,8 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*	@package chamilo.admin
-*/
+ * @package chamilo.admin
+ */
 
 // Language files that should be included
 $language_file = array('admin', 'registration');
@@ -21,8 +21,12 @@ api_protect_super_admin($user_id, null, true);
 
 $is_platform_admin = api_is_platform_admin() ? 1 : 0;
 
-$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
-$htmlHeadXtra[] = '<link  href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
+$htmlHeadXtra[] = '<script src="'.api_get_path(
+    WEB_LIBRARY_PATH
+).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
+$htmlHeadXtra[] = '<link  href="'.api_get_path(
+    WEB_LIBRARY_PATH
+).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
 $htmlHeadXtra[] = '
 <script>
 
@@ -67,22 +71,19 @@ function show_image(image,width,height) {
 //-->
 </script>';
 
-$libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileUpload.lib.php';
-
 $noPHP_SELF = true;
 $tool_name = get_lang('ModifyUserInfo');
 
-$interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => "user_list.php","name" => get_lang('UserList'));
+$interbreadcrumb[] = array('url' => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => "user_list.php", "name" => get_lang('UserList'));
 
 $table_user = Database::get_main_table(TABLE_MAIN_USER);
 $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
 $sql = "SELECT u.*, a.user_id AS is_admin FROM $table_user u LEFT JOIN $table_admin a ON a.user_id = u.user_id WHERE u.user_id = '".$user_id."'";
 $res = Database::query($sql);
 if (Database::num_rows($res) != 1) {
-	header('Location: user_list.php');
-	exit;
+    header('Location: user_list.php');
+    exit;
 }
 
 $user_data = Database::fetch_array($res, 'ASSOC');
@@ -92,7 +93,11 @@ $user_data['old_password'] = $user_data['password'];
 //Convert the registration date of the user
 
 //@todo remove the date_default_timezone_get() see UserManager::create_user function
-$user_data['registration_date'] = api_get_local_time($user_data['registration_date'], null, date_default_timezone_get());
+$user_data['registration_date'] = api_get_local_time(
+    $user_data['registration_date'],
+    null,
+    date_default_timezone_get()
+);
 unset($user_data['password']);
 $extra_data = UserManager :: get_extra_user_data($user_id, true);
 $user_data = array_merge($user_data, $extra_data);
@@ -103,27 +108,27 @@ $form->addElement('header', '', $tool_name);
 $form->addElement('hidden', 'user_id', $user_id);
 
 if (api_is_western_name_order()) {
-	// Firstname
-	$form->addElement('text', 'firstname', get_lang('FirstName'));
-	$form->applyFilter('firstname', 'html_filter');
-	$form->applyFilter('firstname', 'trim');
-	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
-	// Lastname
-	$form->addElement('text', 'lastname', get_lang('LastName'));
-	$form->applyFilter('lastname', 'html_filter');
-	$form->applyFilter('lastname', 'trim');
-	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+    // Firstname
+    $form->addElement('text', 'firstname', get_lang('FirstName'));
+    $form->applyFilter('firstname', 'html_filter');
+    $form->applyFilter('firstname', 'trim');
+    $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+    // Lastname
+    $form->addElement('text', 'lastname', get_lang('LastName'));
+    $form->applyFilter('lastname', 'html_filter');
+    $form->applyFilter('lastname', 'trim');
+    $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
 } else {
-	// Lastname
-	$form->addElement('text', 'lastname', get_lang('LastName'));
-	$form->applyFilter('lastname', 'html_filter');
-	$form->applyFilter('lastname', 'trim');
-	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
-	// Firstname
-	$form->addElement('text', 'firstname', get_lang('FirstName'));
-	$form->applyFilter('firstname', 'html_filter');
-	$form->applyFilter('firstname', 'trim');
-	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+    // Lastname
+    $form->addElement('text', 'lastname', get_lang('LastName'));
+    $form->applyFilter('lastname', 'html_filter');
+    $form->applyFilter('lastname', 'trim');
+    $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+    // Firstname
+    $form->addElement('text', 'firstname', get_lang('FirstName'));
+    $form->applyFilter('firstname', 'html_filter');
+    $form->applyFilter('firstname', 'trim');
+    $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 }
 
 // Official code
@@ -139,13 +144,18 @@ if (api_get_setting('registration', 'email') == 'true') {
 }
 
 if (api_get_setting('login_is_email') == 'true') {
-    $form->addRule('email', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
+    $form->addRule(
+        'email',
+        sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH),
+        'maxlength',
+        USERNAME_MAX_LENGTH
+    );
     $form->addRule('email', get_lang('UserTaken'), 'username_available', $user_data['username']);
 }
 
 // OpenID
 if (api_get_setting('openid_authentication') == 'true') {
-	$form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => '40'));
+    $form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => '40'));
 }
 
 // Phone
@@ -153,10 +163,15 @@ $form->addElement('text', 'phone', get_lang('PhoneNumber'));
 
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
-$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
+$allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
+$form->addRule(
+    'picture',
+    get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
+    'filetype',
+    $allowed_picture_types
+);
 if (strlen($user_data['picture_uri']) > 0) {
-	$form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
+    $form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
 }
 
 // Username
@@ -164,7 +179,12 @@ if (strlen($user_data['picture_uri']) > 0) {
 if (api_get_setting('login_is_email') != 'true') {
     $form->addElement('text', 'username', get_lang('LoginName'), array('maxlength' => USERNAME_MAX_LENGTH));
     $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
-    $form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
+    $form->addRule(
+        'username',
+        sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH),
+        'maxlength',
+        USERNAME_MAX_LENGTH
+    );
     $form->addRule('username', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
     $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
 }
@@ -173,39 +193,50 @@ if (api_get_setting('login_is_email') != 'true') {
 $form->addElement('radio', 'reset_password', get_lang('Password'), get_lang('DontResetPassword'), 0);
 $nb_ext_auth_source_added = 0;
 if (count($extAuthSource) > 0) {
-	$auth_sources = array();
-	foreach($extAuthSource as $key => $info) {
-	    // @todo : make uniform external authentification configuration (ex : cas and external_login ldap)
-	    // Special case for CAS. CAS is activated from Chamilo > Administration > Configuration > CAS
-	    // extAuthSource always on for CAS even if not activated
-	    // same action for file user_add.php
-	    if (($key == CAS_AUTH_SOURCE && api_get_setting('cas_activate') === 'true') || ($key != CAS_AUTH_SOURCE)) {
-    		$auth_sources[$key] = $key;
-    		$nb_ext_auth_source_added++;
-	    }
-	}
-	if ($nb_ext_auth_source_added > 0) {
-	    // @todo check the radio button for external authentification and select the external authentification in the menu
-	    $group[] =$form->createElement('radio', 'reset_password', null, get_lang('ExternalAuthentication').' ', 3);
-	    $group[] =$form->createElement('select', 'auth_source', null, $auth_sources);
-	    $group[] =$form->createElement('static', '', '', '<br />');
-	    $form->addGroup($group, 'password', null, '', false);
-	}
+    $auth_sources = array();
+    foreach ($extAuthSource as $key => $info) {
+        // @todo : make uniform external authentification configuration (ex : cas and external_login ldap)
+        // Special case for CAS. CAS is activated from Chamilo > Administration > Configuration > CAS
+        // extAuthSource always on for CAS even if not activated
+        // same action for file user_add.php
+        if (($key == CAS_AUTH_SOURCE && api_get_setting('cas_activate') === 'true') || ($key != CAS_AUTH_SOURCE)) {
+            $auth_sources[$key] = $key;
+            $nb_ext_auth_source_added++;
+        }
+    }
+    if ($nb_ext_auth_source_added > 0) {
+        // @todo check the radio button for external authentification and select the external authentification in the menu
+        $group[] = $form->createElement('radio', 'reset_password', null, get_lang('ExternalAuthentication').' ', 3);
+        $group[] = $form->createElement('select', 'auth_source', null, $auth_sources);
+        $group[] = $form->createElement('static', '', '', '<br />');
+        $form->addGroup($group, 'password', null, '', false);
+    }
 }
 $form->addElement('radio', 'reset_password', null, get_lang('AutoGeneratePassword'), 1);
 $group = array();
-$group[] =$form->createElement('radio', 'reset_password', null, null, 2);
-$group[] =$form->createElement('password', 'password', null, array('onkeydown' => 'javascript: password_switch_radio_button();'));
+$group[] = $form->createElement('radio', 'reset_password', null, null, 2);
+$group[] = $form->createElement(
+    'password',
+    'password',
+    null,
+    array('onkeydown' => 'javascript: password_switch_radio_button();')
+);
 $form->addGroup($group, 'password', null, '', false);
 
 // Status
 $status = array();
-$status[COURSEMANAGER] 	= get_lang('Teacher');
-$status[STUDENT] 		= get_lang('Learner');
-$status[DRH] 			= get_lang('Drh');
-$status[SESSIONADMIN] 	= get_lang('SessionsAdmin');
-
-$form->addElement('select', 'status', get_lang('Profile'), $status, array('id' => 'status_select', 'onchange' => 'javascript: display_drh_list();','class'=>'chzn-select'));
+$status[COURSEMANAGER] = get_lang('Teacher');
+$status[STUDENT] = get_lang('Learner');
+$status[DRH] = get_lang('Drh');
+$status[SESSIONADMIN] = get_lang('SessionsAdmin');
+
+$form->addElement(
+    'select',
+    'status',
+    get_lang('Profile'),
+    $status,
+    array('id' => 'status_select', 'onchange' => 'javascript: display_drh_list();', 'class' => 'chzn-select')
+);
 
 $display = isset($user_data['status']) && ($user_data['status'] == STUDENT || (isset($_POST['status']) && $_POST['status'] == STUDENT)) ? 'block' : 'none';
 
@@ -228,15 +259,15 @@ $form->addElement('html', '</div>');
 
 // Platform admin
 if (api_is_platform_admin()) {
-	$group = array();
-	$group[] =$form->createElement('radio', 'platform_admin', null, get_lang('Yes'), 1);
-	$group[] =$form->createElement('radio', 'platform_admin', null, get_lang('No'), 0);
+    $group = array();
+    $group[] = $form->createElement('radio', 'platform_admin', null, get_lang('Yes'), 1);
+    $group[] = $form->createElement('radio', 'platform_admin', null, get_lang('No'), 0);
 
-	$user_data['status'] == 1 ? $display = 'block':$display = 'none';
+    $user_data['status'] == 1 ? $display = 'block' : $display = 'none';
 
-	$form->addElement('html', '<div id="id_platform_admin" style="display:'.$display.'">');
-	$form->addGroup($group, 'admin', get_lang('PlatformAdmin'), null, false);
-	$form->addElement('html', '</div>');
+    $form->addElement('html', '<div id="id_platform_admin" style="display:'.$display.'">');
+    $form->addGroup($group, 'admin', get_lang('PlatformAdmin'), null, false);
+    $form->addElement('html', '</div>');
 }
 
 //Language
@@ -244,24 +275,29 @@ $form->addElement('select_language', 'language', get_lang('Language'));
 
 // Send email
 $group = array();
-$group[] =$form->createElement('radio', 'send_mail', null, get_lang('Yes'), 1);
-$group[] =$form->createElement('radio', 'send_mail', null, get_lang('No'), 0);
+$group[] = $form->createElement('radio', 'send_mail', null, get_lang('Yes'), 1);
+$group[] = $form->createElement('radio', 'send_mail', null, get_lang('No'), 0);
 $form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;', false);
 
 // Registration Date
 $form->addElement('static', 'registration_date', get_lang('RegistrationDate'), $user_data['registration_date']);
 
 if (!$user_data['platform_admin']) {
-	// Expiration Date
-	$form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
-	$group = array ();
-	$group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-	$group[] = $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
-	$form->addGroup($group, 'max_member_group', null, '', false);
-
-	// Active account or inactive account
-	$form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
-	$form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
+    // Expiration Date
+    $form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
+    $group = array();
+    $group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
+    $group[] = $form->createElement(
+        'datepicker',
+        'expiration_date',
+        null,
+        array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();')
+    );
+    $form->addGroup($group, 'max_member_group', null, '', false);
+
+    // Active account or inactive account
+    $form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
+    $form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 }
 
 
@@ -270,7 +306,7 @@ $return_params = ExtraField::set_extra_fields_in_form($form, $extra_data, 'user_
 $jquery_ready_content = $return_params['jquery_ready_content'];
 
 // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function
-$htmlHeadXtra[] ='<script>
+$htmlHeadXtra[] = '<script>
 $(document).ready(function(){
 	'.$jquery_ready_content.'
 });
@@ -285,18 +321,18 @@ $user_data['reset_password'] = 0;
 $expiration_date = $user_data['expiration_date'];
 
 if ($expiration_date == '0000-00-00 00:00:00') {
-	$user_data['radio_expiration_date'] = 0;
-	$user_data['expiration_date'] = array();
-	$user_data['expiration_date']['d'] = date('d');
-	$user_data['expiration_date']['F'] = date('m');
-	$user_data['expiration_date']['Y'] = date('Y');
+    $user_data['radio_expiration_date'] = 0;
+    $user_data['expiration_date'] = array();
+    $user_data['expiration_date']['d'] = date('d');
+    $user_data['expiration_date']['F'] = date('m');
+    $user_data['expiration_date']['Y'] = date('Y');
 } else {
-	$user_data['radio_expiration_date'] = 1;
+    $user_data['radio_expiration_date'] = 1;
 
-	$user_data['expiration_date'] = array();
-	$user_data['expiration_date']['d'] = substr($expiration_date, 8, 2);
-	$user_data['expiration_date']['F'] = substr($expiration_date, 5, 2);
-	$user_data['expiration_date']['Y'] = substr($expiration_date, 0, 4);
+    $user_data['expiration_date'] = array();
+    $user_data['expiration_date']['d'] = substr($expiration_date, 8, 2);
+    $user_data['expiration_date']['F'] = substr($expiration_date, 5, 2);
+    $user_data['expiration_date']['Y'] = substr($expiration_date, 0, 4);
 
     $user_data['expiration_date']['H'] = substr($expiration_date, 11, 2);
     $user_data['expiration_date']['i'] = substr($expiration_date, 14, 2);
@@ -307,44 +343,48 @@ $error_drh = false;
 // Validate form
 if ($form->validate()) {
 
-	$user = $form->getSubmitValues();
-	$is_user_subscribed_in_course = CourseManager::is_user_subscribed_in_course($user['user_id']);
-
-	if ($user['status'] == DRH && $is_user_subscribed_in_course) {
-		$error_drh = true;
-	} else {
-		$picture_element = $form->getElement('picture');
-		$picture = $picture_element->getValue();
-
-		$picture_uri = $user_data['picture_uri'];
-		if ($user['delete_picture']) {
-			$picture_uri = UserManager::delete_user_picture($user_id);
-		} elseif (!empty($picture['name'])) {
-			$picture_uri = UserManager::update_user_picture($user_id, $_FILES['picture']['name'], $_FILES['picture']['tmp_name']);
-		}
+    $user = $form->getSubmitValues();
+    $is_user_subscribed_in_course = CourseManager::is_user_subscribed_in_course($user['user_id']);
+
+    if ($user['status'] == DRH && $is_user_subscribed_in_course) {
+        $error_drh = true;
+    } else {
+        $picture_element = $form->getElement('picture');
+        $picture = $picture_element->getValue();
+
+        $picture_uri = $user_data['picture_uri'];
+        if ($user['delete_picture']) {
+            $picture_uri = UserManager::delete_user_picture($user_id);
+        } elseif (!empty($picture['name'])) {
+            $picture_uri = UserManager::update_user_picture(
+                $user_id,
+                $_FILES['picture']['name'],
+                $_FILES['picture']['tmp_name']
+            );
+        }
 
-		$lastname = $user['lastname'];
-		$firstname = $user['firstname'];
+        $lastname = $user['lastname'];
+        $firstname = $user['firstname'];
         $password = $user['password'];
         $auth_source = $user['auth_source'];
 
-		$official_code = $user['official_code'];
-		$email = $user['email'];
-		$phone = $user['phone'];
-		$username = $user['username'];
-		$status = intval($user['status']);
-		$platform_admin = intval($user['platform_admin']);
-		$send_mail = intval($user['send_mail']);
-		$reset_password = intval($user['reset_password']);
-		$hr_dept_id = intval($user['hr_dept_id']);
-		$language = $user['language'];
-		if ($user['radio_expiration_date'] == '1' && !$user_data['platform_admin']) {
+        $official_code = $user['official_code'];
+        $email = $user['email'];
+        $phone = $user['phone'];
+        $username = $user['username'];
+        $status = intval($user['status']);
+        $platform_admin = intval($user['platform_admin']);
+        $send_mail = intval($user['send_mail']);
+        $reset_password = intval($user['reset_password']);
+        $hr_dept_id = intval($user['hr_dept_id']);
+        $language = $user['language'];
+        if ($user['radio_expiration_date'] == '1' && !$user_data['platform_admin']) {
             $expiration_date = return_datetime_from_array($user['expiration_date']);
-		} else {
-			$expiration_date = '0000-00-00 00:00:00';
-		}
+        } else {
+            $expiration_date = '0000-00-00 00:00:00';
+        }
 
-		$active = $user_data['platform_admin'] ? 1 : intval($user['active']);
+        $active = $user_data['platform_admin'] ? 1 : intval($user['active']);
 
         //If the user is set to admin the status will be overwrite by COURSEMANAGER = 1
         if ($platform_admin == 1) {
@@ -354,62 +394,85 @@ if ($form->validate()) {
         if (api_get_setting('login_is_email') == 'true') {
             $username = $email;
         }
-		UserManager::update_user($user_id, $firstname, $lastname, $username, $password, $auth_source, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, null, $hr_dept_id, null, $language, null, $send_mail, $reset_password);
-
-		if (api_get_setting('openid_authentication') == 'true' && !empty($user['openid'])) {
-			$up = UserManager::update_openid($user_id,$user['openid']);
-		}
-		if ($user_id != $_SESSION['_uid']) {
-			if ($platform_admin == 1) {
+        UserManager::update_user(
+            $user_id,
+            $firstname,
+            $lastname,
+            $username,
+            $password,
+            $auth_source,
+            $email,
+            $status,
+            $official_code,
+            $phone,
+            $picture_uri,
+            $expiration_date,
+            $active,
+            null,
+            $hr_dept_id,
+            null,
+            $language,
+            null,
+            $send_mail,
+            $reset_password
+        );
+
+        if (api_get_setting('openid_authentication') == 'true' && !empty($user['openid'])) {
+            $up = UserManager::update_openid($user_id, $user['openid']);
+        }
+        if ($user_id != $_SESSION['_uid']) {
+            if ($platform_admin == 1) {
                 UserManager::add_user_as_admin($user_id);
-			} else {
+            } else {
                 UserManager::remove_user_admin($user_id);
-			}
-		}
+            }
+        }
 
-		foreach ($user as $key => $value) {
-			if (substr($key, 0, 6) == 'extra_') {
+        foreach ($user as $key => $value) {
+            if (substr($key, 0, 6) == 'extra_') {
                 //an extra field
                 //@todo remove this as well as in the profile.php ad put it in a function
                 if (is_array($value) && isset($value['Y']) && isset($value['F']) && isset($value['d'])) {
                     if (isset($value['H']) && isset($value['i'])) {
                         // extra field date time
-                        $time = mktime($value['H'],$value['i'],0,$value['F'],$value['d'],$value['Y']);
-                        $value = date('Y-m-d H:i:s',$time);
+                        $time = mktime($value['H'], $value['i'], 0, $value['F'], $value['d'], $value['Y']);
+                        $value = date('Y-m-d H:i:s', $time);
                     } else {
                         // extra field date
-                        $time = mktime(0,0,0,$value['F'],$value['d'],$value['Y']);
-                        $value = date('Y-m-d',$time);
+                        $time = mktime(0, 0, 0, $value['F'], $value['d'], $value['Y']);
+                        $value = date('Y-m-d', $time);
                     }
                 }
-				UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
-			}
-		}
-		$tok = Security::get_token();
-		header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserUpdated')).'&sec_token='.$tok);
-		exit();
-	}
+                UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
+            }
+        }
+        $tok = Security::get_token();
+        header(
+            'Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserUpdated')).'&sec_token='.$tok
+        );
+        exit();
+    }
 }
 
 $message = null;
 if ($error_drh) {
-	$err_msg = get_lang('StatusCanNotBeChangedToHumanResourcesManager');
-	$message = Display::return_message($err_msg, 'error');
+    $err_msg = get_lang('StatusCanNotBeChangedToHumanResourcesManager');
+    $message = Display::return_message($err_msg, 'error');
 }
 
 // USER PICTURE
-$image_path = UserManager::get_user_picture_path_by_id($user_id,'web');
+$image_path = UserManager::get_user_picture_path_by_id($user_id, 'web');
 $image_dir = $image_path['dir'];
 $image = $image_path['file'];
 $image_file = ($image != '' ? $image_dir.$image : api_get_path(WEB_CODE_PATH).'img/unknown.jpg');
 $image_size = api_getimagesize($image_file);
 
 $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
-	.'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
-	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
+    .'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
+    .'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
 
 if ($image_size['width'] > 300) { //limit display width to 300px
-	$img_attributes .= 'width="300" ';
+    $img_attributes .= 'width="300" ';
 }
 
 // get the path,width and height from original picture
@@ -421,9 +484,9 @@ $url_big_image = $big_image.'?rnd='.time();
 
 $content = null;
 if ($image == '') {
-	$content .= '<img '.$img_attributes.' />';
+    $content .= '<img '.$img_attributes.' />';
 } else {
-	$content .= '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
+    $content .= '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
 }
 
 // Display form

+ 267 - 102
main/announcements/announcements.php

@@ -7,8 +7,8 @@
  * @author Julio Montoya <gugli100@gmail.com>, MORE code cleaning 2011
  *
  * @abstract The task of the internship was to integrate the 'send messages to specific users' with the
- * 			 Announcements tool and also add the resource linker here. The database also needed refactoring
- * 			 as there was no title field (the title was merged into the content field)
+ *              Announcements tool and also add the resource linker here. The database also needed refactoring
+ *              as there was no title field (the title was merged into the content field)
  * @package chamilo.announcements
  * @todo make AWACS out of the configuration settings
  * @todo this file is 1300+ lines without any functions -> needs to be split into
@@ -54,9 +54,6 @@ $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
 
 /* 	Libraries	 */
 
-$lib = api_get_path(LIBRARY_PATH); //avoid useless function calls
-require_once $lib.'fileUpload.lib.php';
-
 $course_id = api_get_course_int_id();
 
 /* 	Tracking	 */
@@ -74,7 +71,12 @@ if (!empty($_POST['To'])) {
     }
     $display_form = true;
 
-    $form_elements = array('emailTitle' => $safe_emailTitle, 'newContent' => $safe_newContent, 'id' => $_POST['id'], 'emailoption' => $_POST['email_ann']);
+    $form_elements = array(
+        'emailTitle' => $safe_emailTitle,
+        'newContent' => $safe_newContent,
+        'id' => $_POST['id'],
+        'emailoption' => $_POST['email_ann']
+    );
     $_SESSION['formelements'] = $form_elements;
 
     $form_elements = $_SESSION['formelements'];
@@ -148,7 +150,10 @@ $group_id = api_get_group_id();
 if (!empty($group_id)) {
     $group_properties = GroupManager :: get_group_properties($group_id);
     $interbreadcrumb[] = array("url" => "../group/group.php", "name" => get_lang('Groups'));
-    $interbreadcrumb[] = array("url" => "../group/group_space.php?gidReq=".$group_id, "name" => get_lang('GroupSpace').' '.$group_properties['name']);
+    $interbreadcrumb[] = array(
+        "url" => "../group/group_space.php?gidReq=".$group_id,
+        "name" => get_lang('GroupSpace').' '.$group_properties['name']
+    );
 }
 
 $announcement_id = isset($_GET['id']) ? intval($_GET['id']) : null;
@@ -159,7 +164,7 @@ if (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath') {
     Display::display_header($nameTools, get_lang('Announcements'));
 }
 
-if (AnnouncementManager::user_can_edit_announcement()){
+if (AnnouncementManager::user_can_edit_announcement()) {
     /*
       Change visibility of announcement
      */
@@ -242,7 +247,11 @@ if (AnnouncementManager::user_can_edit_announcement()){
             $rs = Database::query($sql);
             $myrow = Database::fetch_array($rs);
             $last_id = $id;
-            $edit_attachment = AnnouncementManager::edit_announcement_attachment_file($last_id, $_FILES['user_upload'], $file_comment);
+            $edit_attachment = AnnouncementManager::edit_announcement_attachment_file(
+                $last_id,
+                $_FILES['user_upload'],
+                $file_comment
+            );
 
             if ($myrow) {
                 $announcement_to_modify = $myrow['id'];
@@ -304,8 +313,12 @@ if (AnnouncementManager::user_can_edit_announcement()){
             if ($thisAnnouncementOrderFound) {
                 $nextAnnouncementId = $announcementId;
                 $nextAnnouncementOrder = $announcementOrder;
-                Database::query("UPDATE $tbl_announcement SET display_order = '$nextAnnouncementOrder'  WHERE c_id = $course_id AND id =  '$thisAnnouncementId'");
-                Database::query("UPDATE $tbl_announcement  SET display_order = '$thisAnnouncementOrder' WHERE c_id = $course_id AND id =  '$nextAnnouncementId.'");
+                Database::query(
+                    "UPDATE $tbl_announcement SET display_order = '$nextAnnouncementOrder'  WHERE c_id = $course_id AND id =  '$thisAnnouncementId'"
+                );
+                Database::query(
+                    "UPDATE $tbl_announcement  SET display_order = '$thisAnnouncementOrder' WHERE c_id = $course_id AND id =  '$nextAnnouncementId.'"
+                );
                 break;
             }
             // STEP 1 : FIND THE ORDER OF THE ANNOUNCEMENT
@@ -336,54 +349,76 @@ if (AnnouncementManager::user_can_edit_announcement()){
     if ($submitAnnouncement && empty($emailTitle)) {
         $error_message = get_lang('TitleIsRequired');
         $content_to_modify = $newContent;
-    } else if ($submitAnnouncement) {
-        $selected_form = isset($_POST['selectedform']) ? $_POST['selectedform'] : null;
-
-        if (isset($id) && $id) {
-            // there is an Id => the announcement already exists => update mode
-            if ($ctok == $_POST['sec_token']) {
-                $file_comment = $_POST['file_comment'];
-                $file = $_FILES['user_upload'];
-                AnnouncementManager::edit_announcement($id, $emailTitle, $newContent, $selected_form, $file, $file_comment);
-
-                /* 		MAIL FUNCTION	 */
-                if ($_POST['email_ann'] && empty($_POST['onlyThoseMails'])) {
-                    AnnouncementManager::send_email($id);
+    } else {
+        if ($submitAnnouncement) {
+            $selected_form = isset($_POST['selectedform']) ? $_POST['selectedform'] : null;
+
+            if (isset($id) && $id) {
+                // there is an Id => the announcement already exists => update mode
+                if ($ctok == $_POST['sec_token']) {
+                    $file_comment = $_POST['file_comment'];
+                    $file = $_FILES['user_upload'];
+                    AnnouncementManager::edit_announcement(
+                        $id,
+                        $emailTitle,
+                        $newContent,
+                        $selected_form,
+                        $file,
+                        $file_comment
+                    );
+
+                    /* 		MAIL FUNCTION	 */
+                    if ($_POST['email_ann'] && empty($_POST['onlyThoseMails'])) {
+                        AnnouncementManager::send_email($id);
+                    }
+                    $message = get_lang('AnnouncementModified');
                 }
-                $message = get_lang('AnnouncementModified');
-            }
-        } else {
-            //insert mode
-            if ($ctok == $_POST['sec_token']) {
-                $file = $_FILES['user_upload'];
-                $file_comment = $_POST['file_comment'];
+            } else {
+                //insert mode
+                if ($ctok == $_POST['sec_token']) {
+                    $file = $_FILES['user_upload'];
+                    $file_comment = $_POST['file_comment'];
+
+                    if (!empty($group_id)) {
+                        $insert_id = AnnouncementManager::add_group_announcement(
+                            $safe_emailTitle,
+                            $safe_newContent,
+                            array('GROUP:'.$group_id),
+                            $selected_form,
+                            $file,
+                            $file_comment
+                        );
+                    } else {
+                        $insert_id = AnnouncementManager::add_announcement(
+                            $safe_emailTitle,
+                            $safe_newContent,
+                            $selected_form,
+                            $file,
+                            $file_comment
+                        );
+                    }
+                    //store_resources($_SESSION['source_type'],$insert_id);
+                    $_SESSION['select_groupusers'] = "hide";
+                    $message = get_lang('AnnouncementAdded');
 
-                if (!empty($group_id)) {
-                    $insert_id = AnnouncementManager::add_group_announcement($safe_emailTitle, $safe_newContent, array('GROUP:'.$group_id), $selected_form, $file, $file_comment);
-                } else {
-                    $insert_id = AnnouncementManager::add_announcement($safe_emailTitle, $safe_newContent, $selected_form, $file, $file_comment);
-                }
-                //store_resources($_SESSION['source_type'],$insert_id);
-                $_SESSION['select_groupusers'] = "hide";
-                $message = get_lang('AnnouncementAdded');
+                    /* 		MAIL FUNCTION	 */
+                    if (isset($_POST['email_ann']) && $_POST['email_ann'] && empty($_POST['onlyThoseMails'])) {
+                        AnnouncementManager::send_email($insert_id);
+                    }
+                } // end condition token
+            } // isset
+            // UNSET VARIABLES
+            unset($form_elements);
+            $_SESSION['formelements'] = null;
 
-                /* 		MAIL FUNCTION	 */
-                if (isset($_POST['email_ann']) && $_POST['email_ann'] && empty($_POST['onlyThoseMails'])) {
-                    AnnouncementManager::send_email($insert_id);
-                }
-            } // end condition token
-        } // isset
-        // UNSET VARIABLES
-        unset($form_elements);
-        $_SESSION['formelements'] = null;
-
-        $newContent = null;
-        $emailTitle = null;
-
-        unset($emailTitle);
-        unset($newContent);
-        unset($content_to_modify);
-        unset($title_to_modify);
+            $newContent = null;
+            $emailTitle = null;
+
+            unset($emailTitle);
+            unset($newContent);
+            unset($content_to_modify);
+            unset($title_to_modify);
+        }
     } // if $submit Announcement
 }
 
@@ -428,7 +463,8 @@ if (api_is_allowed_to_edit(false, true)) {
 
         if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
             if (api_get_group_id() == 0) {
-                $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR ( ip.to_user_id='".api_get_user_id()."'".
+                $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id(
+                )."' OR ( ip.to_user_id='".api_get_user_id()."'".
                     "OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))) ";
             } else {
                 $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."'
@@ -447,7 +483,7 @@ if (api_is_allowed_to_edit(false, true)) {
 
         // the user is member of several groups => display personal announcements AND his group announcements AND the general announcements
         if (is_array($group_memberships) && count($group_memberships) > 0) {
-           $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
+            $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
                 FROM $tbl_announcement announcement, $tbl_item_property ip
                 WHERE
                     announcement.c_id = $course_id AND
@@ -466,7 +502,8 @@ if (api_is_allowed_to_edit(false, true)) {
             if ($_user['user_id']) {
 
                 if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
-                    $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR ( ip.to_user_id='".$_user['user_id']."' OR ip.to_group_id='0')) ";
+                    $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id(
+                    )."' OR ( ip.to_user_id='".$_user['user_id']."' OR ip.to_group_id='0')) ";
                 } else {
                     $cond_user_id = " AND ( ip.to_user_id='".$_user['user_id']."' OR ip.to_group_id='0') ";
                 }
@@ -521,30 +558,59 @@ $show_actions = false;
 if (AnnouncementManager::user_can_edit_announcement()) {
     echo '<div class="actions">';
     if (isset($_GET['action']) && in_array($_GET['action'], array('add', 'modify', 'view'))) {
-        echo "<a href='".api_get_self()."?".api_get_cidreq()."&origin=".(empty($_GET['origin']) ? '' : $_GET['origin'])."'>".Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM)."</a>";
+        echo "<a href='".api_get_self()."?".api_get_cidreq(
+        )."&origin=".(empty($_GET['origin']) ? '' : $_GET['origin'])."'>".Display::return_icon(
+            'back.png',
+            get_lang('Back'),
+            '',
+            ICON_SIZE_MEDIUM
+        )."</a>";
     } else {
-        echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=add&origin=".(empty($_GET['origin']) ? '' : $_GET['origin'])."'>".Display::return_icon('new_announce.png', get_lang('AddAnnouncement'), '', ICON_SIZE_MEDIUM)."</a>";
+        echo "<a href='".api_get_self()."?".api_get_cidreq(
+        )."&action=add&origin=".(empty($_GET['origin']) ? '' : $_GET['origin'])."'>".Display::return_icon(
+            'new_announce.png',
+            get_lang('AddAnnouncement'),
+            '',
+            ICON_SIZE_MEDIUM
+        )."</a>";
     }
     $show_actions = true;
 } else {
     if (isset($_GET['action']) && in_array($_GET['action'], array('view'))) {
         echo '<div class="actions">';
-        echo "<a href='".api_get_self()."?".api_get_cidreq()."&origin=".(empty($_GET['origin']) ? '' : $_GET['origin'])."'>".Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM)."</a>";
+        echo "<a href='".api_get_self()."?".api_get_cidreq(
+        )."&origin=".(empty($_GET['origin']) ? '' : $_GET['origin'])."'>".Display::return_icon(
+            'back.png',
+            get_lang('Back'),
+            '',
+            ICON_SIZE_MEDIUM
+        )."</a>";
         echo '</div>';
     }
 }
 
 if (api_is_allowed_to_edit() && $announcement_number > 1) {
     if ($group_id == 0) {
-        if (!$show_actions)
+        if (!$show_actions) {
             echo '<div class="actions">';
-        if (!isset($_GET['action']) OR !in_array($_GET['action'], array('add', 'modify', 'view')))
-            echo "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=delete_all\" onclick=\"javascript:if(!confirm('".get_lang("ConfirmYourChoice")."')) return false;\">".Display::return_icon('delete_announce.png', get_lang('AnnouncementDeleteAll'), '', ICON_SIZE_MEDIUM)."</a>";
+        }
+        if (!isset($_GET['action']) OR !in_array($_GET['action'], array('add', 'modify', 'view'))) {
+            echo "<a href=\"".api_get_self()."?".api_get_cidreq(
+            )."&action=delete_all\" onclick=\"javascript:if(!confirm('".get_lang(
+                "ConfirmYourChoice"
+            )."')) return false;\">".Display::return_icon(
+                'delete_announce.png',
+                get_lang('AnnouncementDeleteAll'),
+                '',
+                ICON_SIZE_MEDIUM
+            )."</a>";
+        }
     }
 }
 
-if ($show_actions)
+if ($show_actions) {
     echo '</div>';
+}
 
 //	ANNOUNCEMENTS LIST
 
@@ -571,7 +637,8 @@ if ($display_form) {
     // DISPLAY ADD ANNOUNCEMENT COMMAND
     //echo '<form method="post" name="f1" enctype = "multipart/form-data" action="'.api_get_self().'?publish_survey='.Security::remove_XSS($surveyid).'&id='.Security::remove_XSS($_GET['id']).'&db_name='.$db_name.'&cidReq='.Security::remove_XSS($_GET['cidReq']).'" style="margin:0px;">';
     $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
-    echo '<form class="form-horizontal" method="post" name="f1" enctype = "multipart/form-data" action="'.api_get_self().'?id='.$id.'&'.api_get_cidreq().'" style="margin:0px;">';
+    echo '<form class="form-horizontal" method="post" name="f1" enctype = "multipart/form-data" action="'.api_get_self(
+    ).'?id='.$id.'&'.api_get_cidreq().'" style="margin:0px;">';
     if (empty($_GET['id'])) {
         $form_name = get_lang('AddAnnouncement');
     } else {
@@ -585,7 +652,12 @@ if ($display_form) {
     if (empty($group_id)) {
         echo '<div class="control-group">
                 <label class="control-label">'.
-        Display::return_icon('group.png', get_lang('ModifyRecipientList'), array('align' => 'absmiddle'), ICON_SIZE_SMALL).'<a href="#" onclick="toggle_sendto();">'.get_lang('SentTo').'</a>
+            Display::return_icon(
+                'group.png',
+                get_lang('ModifyRecipientList'),
+                array('align' => 'absmiddle'),
+                ICON_SIZE_SMALL
+            ).'<a href="#" onclick="toggle_sendto();">'.get_lang('SentTo').'</a>
 					</label>
 					<div class="controls">';
         if (isset($_GET['id']) && is_array($to)) {
@@ -611,7 +683,11 @@ if ($display_form) {
             // setting the variables for the form elements: the title of the email
             $title_to_modify = sprintf(get_lang('RemindInactiveLearnersMailSubject'), api_get_setting('siteName'));
             // setting the variables for the form elements: the message of the email
-            $content_to_modify = sprintf(get_lang('RemindInactiveLearnersMailContent'), api_get_setting('siteName'), $since);
+            $content_to_modify = sprintf(
+                get_lang('RemindInactiveLearnersMailContent'),
+                api_get_setting('siteName'),
+                $since
+            );
             // when we want to remind the users who have never been active then we have a different subject and content for the announcement
             if ($_GET['since'] == 'never') {
                 $title_to_modify = sprintf(get_lang('RemindInactiveLearnersMailSubject'), api_get_setting('siteName'));
@@ -624,14 +700,17 @@ if ($display_form) {
         echo '		</div>
 					</div>';
 
-        if (!isset($announcement_to_modify))
+        if (!isset($announcement_to_modify)) {
             $announcement_to_modify = '';
+        }
 
         ($email_ann == '1') ? $checked = 'checked' : $checked = '';
         echo '	<div class="control-group">
                     <div class="controls">
                         <label class="checkbox" for="email_ann">
-                            <input id="email_ann" class="checkbox" type="checkbox" value="1" name="email_ann" checked> '.get_lang('EmailOption').'</label>
+                            <input id="email_ann" class="checkbox" type="checkbox" value="1" name="email_ann" checked> '.get_lang(
+            'EmailOption'
+        ).'</label>
                     </div>
                 </div>';
     } else {
@@ -643,7 +722,10 @@ if ($display_form) {
         echo '<div class="control-group">
               <div class="controls">
               <input class="checkbox" type="checkbox" value="1" name="email_ann" '.$checked.'>
-              '.get_lang('EmailOption').': <span id="recipient_overview">'.Display::label(get_lang('MyGroup'), 'success').'</span>
+              '.get_lang('EmailOption').': <span id="recipient_overview">'.Display::label(
+            get_lang('MyGroup'),
+            'success'
+        ).'</span>
               <a href="#" onclick="toggle_sendto();">'.get_lang('ModifyRecipientList').'</a>';
         AnnouncementManager::show_to_form_group($group_id, $to);
         echo '</div></div>';
@@ -656,19 +738,24 @@ if ($display_form) {
 					<span class="form_required">*</span> '.get_lang('EmailTitle').'
 				</label>
 				<div class="controls">
-					<input type="text" id="emailTitle" name="emailTitle" value="'.Security::remove_XSS($title_to_modify).'" class="span4">
+					<input type="text" id="emailTitle" name="emailTitle" value="'.Security::remove_XSS(
+        $title_to_modify
+    ).'" class="span4">
 				</div>
 			</div>';
 
     unset($title_to_modify);
     $title_to_modify = null;
 
-    if (!isset($announcement_to_modify))
+    if (!isset($announcement_to_modify)) {
         $announcement_to_modify = "";
-    if (!isset($content_to_modify))
+    }
+    if (!isset($content_to_modify)) {
         $content_to_modify = "";
-    if (!isset($title_to_modify))
+    }
+    if (!isset($title_to_modify)) {
         $title_to_modify = "";
+    }
 
     echo '<input type="hidden" name="id" value="'.$announcement_to_modify.'" />';
 
@@ -686,7 +773,10 @@ if ($display_form) {
 
     echo '<div class="row"><div class="formw">';
 
-    echo Display::display_normal_message(get_lang('Tags').' <br /><br />'.implode('<br />', AnnouncementManager::get_tags()), false);
+    echo Display::display_normal_message(
+        get_lang('Tags').' <br /><br />'.implode('<br />', AnnouncementManager::get_tags()),
+        false
+    );
 
     echo $oFCKeditor->CreateHtml();
     echo '</div></div>';
@@ -694,7 +784,9 @@ if ($display_form) {
     //File attachment
     echo '	<div class="control-group">
 				<div class="controls">
-				    <a href="javascript://" onclick="return plus_attachment();"><span id="plus"><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AddAnAttachment').'</span></a>
+				    <a href="javascript://" onclick="return plus_attachment();"><span id="plus"><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang(
+        'AddAnAttachment'
+    ).'</span></a>
 				    <br />
 					<table id="options" style="display: none;">
 					<tr>
@@ -719,16 +811,27 @@ if ($display_form) {
     if (empty($group_id)) {
         echo '<input type="hidden" name="submitAnnouncement" value="OK">';
         echo '<input type="hidden" name="sec_token" value="'.$stok.'" />';
-        echo '<button class="btn save" type="button"  value="'.'  '.get_lang('Send').'  '.'" onclick="selectAll(this.form.elements[3],true)" >'.get_lang('ButtonPublishAnnouncement').'</button><br /><br />';
+        echo '<button class="btn save" type="button"  value="'.'  '.get_lang(
+            'Send'
+        ).'  '.'" onclick="selectAll(this.form.elements[3],true)" >'.get_lang(
+            'ButtonPublishAnnouncement'
+        ).'</button><br /><br />';
     } else {
         echo '<input type="hidden" name="submitAnnouncement" value="OK">';
         echo '<input type="hidden" name="sec_token" value="'.$stok.'" />';
-        echo '<button class="btn save" type="button"  value="'.'  '.get_lang('Send').'  '.'" onclick="selectAll(this.form.elements[4],true)" >'.get_lang('ButtonPublishAnnouncement').'</button><br /><br />';
+        echo '<button class="btn save" type="button"  value="'.'  '.get_lang(
+            'Send'
+        ).'  '.'" onclick="selectAll(this.form.elements[4],true)" >'.get_lang(
+            'ButtonPublishAnnouncement'
+        ).'</button><br /><br />';
     }
     echo '</div></div>';
     echo '</form><br />';
 
-    if ((isset($_GET['action']) && isset($_GET['id']) && is_array($to)) || isset($_GET['remindallinactives']) || isset($_GET['remind_inactive'])) {
+    if ((isset($_GET['action']) && isset($_GET['id']) && is_array(
+        $to
+    )) || isset($_GET['remindallinactives']) || isset($_GET['remind_inactive'])
+    ) {
         echo '<script>toggle_sendto();</script>';
     }
 } // displayform
@@ -744,7 +847,10 @@ if ($display_announcement_list) {
 
     $group_memberships = GroupManager::get_group_ids($course_id, api_get_user_id());
 
-    if (api_is_allowed_to_edit(false, true) OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
+    if (api_is_allowed_to_edit(false, true) OR (api_get_course_setting(
+        'allow_user_edit_announcement'
+    ) && !api_is_anonymous())
+    ) {
         // A.1. you are a course admin with a USER filter
         // => see only the messages of this specific user + the messages of the group (s)he is member of.
         if (!empty($_SESSION['user'])) {
@@ -827,7 +933,8 @@ if ($display_announcement_list) {
             if (AnnouncementManager::user_can_edit_announcement()) {
                 if (api_get_group_id() == 0) {
                     //No group
-                    $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR ( ip.to_user_id='".$_user['user_id']."'".
+                    $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id(
+                    )."' OR ( ip.to_user_id='".$_user['user_id']."'".
                         " OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))) ";
                 } else {
                     $cond_user_id = " AND (
@@ -837,7 +944,10 @@ if ($display_announcement_list) {
                 }
             } else {
                 if (api_get_group_id() == 0) {
-                    $cond_user_id = " AND (ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) ";
+                    $cond_user_id = " AND (ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(
+                        ", ",
+                        $group_memberships
+                    ).")) ";
                 } else {
                     $cond_user_id = " AND (
                             (ip.to_user_id = $user_id AND ip.to_group_id = ".api_get_group_id().") OR
@@ -863,7 +973,8 @@ if ($display_announcement_list) {
         } else {
             if ($_user['user_id']) {
                 if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
-                    $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR (ip.to_user_id='".$_user['user_id']."' OR ip.to_group_id='0')) ";
+                    $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id(
+                    )."' OR (ip.to_user_id='".$_user['user_id']."' OR ip.to_group_id='0')) ";
                 } else {
                     $cond_user_id = " AND (ip.to_user_id='".$_user['user_id']."' OR ip.to_group_id='0') ";
                 }
@@ -908,14 +1019,22 @@ if ($display_announcement_list) {
 
     // DISPLAY: NO ITEMS
 
-    if (!isset($_GET['action']) || !in_array($_GET['action'], array('add', 'modify', 'view')))
+    if (!isset($_GET['action']) || !in_array($_GET['action'], array('add', 'modify', 'view'))) {
         if ($num_rows == 0) {
-            if ((api_is_allowed_to_edit(false, true) OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) and (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath')) {
+            if ((api_is_allowed_to_edit(false, true) OR (api_get_course_setting(
+                'allow_user_edit_announcement'
+            ) && !api_is_anonymous())) and (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath')
+            ) {
                 echo '<div id="no-data-view">';
                 echo '<h2>'.get_lang('Announcements').'</h2>';
                 echo Display::return_icon('valves.png', '', array(), 64);
                 echo '<div class="controls">';
-                echo Display::url(get_lang('AddAnnouncement'), api_get_self()."?".api_get_cidreq()."&action=add&origin=".(empty($_GET['origin']) ? '' : $_GET['origin']), array('class' => 'btn'));
+                echo Display::url(
+                    get_lang('AddAnnouncement'),
+                    api_get_self()."?".api_get_cidreq(
+                    )."&action=add&origin=".(empty($_GET['origin']) ? '' : $_GET['origin']),
+                    array('class' => 'btn')
+                );
                 echo '</div>';
                 echo '</div>';
             } else {
@@ -929,8 +1048,12 @@ if ($display_announcement_list) {
             $ths = Display::tag('th', get_lang('Title'));
             $ths .= Display::tag('th', get_lang('By'));
             $ths .= Display::tag('th', get_lang('LastUpdateDate'));
-            if (api_is_allowed_to_edit(false, true) OR (api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id']))
-                OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
+            if (api_is_allowed_to_edit(false, true) OR (api_is_course_coach() && api_is_element_in_the_session(
+                TOOL_ANNOUNCEMENT,
+                $myrow['id']
+            ))
+                OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
+            ) {
                 $ths .= Display::tag('th', get_lang('Modify'));
             }
 
@@ -947,7 +1070,12 @@ if ($display_announcement_list) {
 
                     $title = $myrow['title'].$sent_to_icon;
 
-                    $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $myrow['id'], $session_id);
+                    $item_visibility = api_get_item_visibility(
+                        $_course,
+                        TOOL_ANNOUNCEMENT,
+                        $myrow['id'],
+                        $session_id
+                    );
                     $myrow['visibility'] = $item_visibility;
 
                     // the styles
@@ -973,16 +1101,33 @@ if ($display_announcement_list) {
 
                     $user_info = api_get_user_info($myrow['insert_user_id']);
                     $username = sprintf(get_lang("LoginX"), $user_info['username']);
-                    $username_span = Display::tag('span', api_get_person_name($user_info['firstName'], $user_info['lastName']), array('title' => $username));
+                    $username_span = Display::tag(
+                        'span',
+                        api_get_person_name($user_info['firstName'], $user_info['lastName']),
+                        array('title' => $username)
+                    );
                     echo Display::tag('td', $username_span);
-                    echo Display::tag('td', api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG));
+                    echo Display::tag(
+                        'td',
+                        api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG)
+                    );
 
                     // we can edit if : we are the teacher OR the element belongs to the session we are coaching OR the option to allow users to edit is on
                     $modify_icons = '';
-                    if (api_is_allowed_to_edit(false, true) OR (api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id']))
-                        OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
-
-                        $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$myrow['id']."\">".Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
+                    if (api_is_allowed_to_edit(false, true) OR (api_is_course_coach() && api_is_element_in_the_session(
+                        TOOL_ANNOUNCEMENT,
+                        $myrow['id']
+                    ))
+                        OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
+                    ) {
+
+                        $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq(
+                        )."&action=modify&id=".$myrow['id']."\">".Display::return_icon(
+                            'edit.png',
+                            get_lang('Edit'),
+                            '',
+                            ICON_SIZE_SMALL
+                        )."</a>";
                         if ($myrow['visibility'] == 1) {
                             $image_visibility = "visible";
                             $alt_visibility = get_lang('Hide');
@@ -990,22 +1135,41 @@ if ($display_announcement_list) {
                             $image_visibility = "invisible";
                             $alt_visibility = get_lang('Visible');
                         }
-                        $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&origin=".(!empty($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : '')."&action=showhide&id=".$myrow['id']."&sec_token=".$stok."\">".
-                            Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
+                        $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq(
+                        )."&origin=".(!empty($_GET['origin']) ? Security::remove_XSS(
+                            $_GET['origin']
+                        ) : '')."&action=showhide&id=".$myrow['id']."&sec_token=".$stok."\">".
+                            Display::return_icon(
+                                $image_visibility.'.png',
+                                $alt_visibility,
+                                '',
+                                ICON_SIZE_SMALL
+                            )."</a>";
 
                         // DISPLAY MOVE UP COMMAND only if it is not the top announcement
                         if ($iterator != 1) {
-                            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&up=".$myrow["id"]."&sec_token=".$stok."\">".Display::return_icon('up.gif', get_lang('Up'))."</a>";
+                            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq(
+                            )."&up=".$myrow["id"]."&sec_token=".$stok."\">".Display::return_icon(
+                                'up.gif',
+                                get_lang('Up')
+                            )."</a>";
                         } else {
                             $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
                         }
                         if ($iterator < $bottomAnnouncement) {
-                            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&down=".$myrow["id"]."&sec_token=".$stok."\">".Display::return_icon('down.gif', get_lang('Down'))."</a>";
+                            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq(
+                            )."&down=".$myrow["id"]."&sec_token=".$stok."\">".Display::return_icon(
+                                'down.gif',
+                                get_lang('Down')
+                            )."</a>";
                         } else {
                             $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
                         }
                         if (api_is_allowed_to_edit(false, true)) {
-                            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=delete&id=".$myrow['id']."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."')) return false;\">".
+                            $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq(
+                            )."&action=delete&id=".$myrow['id']."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
+                                api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)
+                            )."')) return false;\">".
                                 Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
                                 "</a>";
                         }
@@ -1018,6 +1182,7 @@ if ($display_announcement_list) {
             } // end while
             echo "</table>";
         }
+    }
 } // end: if ($displayAnnoucementList)
 
 if (isset($_GET['action']) && $_GET['action'] == 'view') {

+ 446 - 334
main/auth/profile.php

@@ -1,13 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-* This file displays the user's profile,
-* optionally it allows users to modify their profile as well.
-*
-* See inc/conf/profile.conf.php to modify settings
-*
-* @package chamilo.auth
-*/
+ * This file displays the user's profile,
+ * optionally it allows users to modify their profile as well.
+ *
+ * See inc/conf/profile.conf.php to modify settings
+ *
+ * @package chamilo.auth
+ */
 /**
  * Code
  */
@@ -30,7 +30,9 @@ if (!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user[
 }
 
 $htmlHeadXtra[] = '<script src="../inc/lib/javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
-$htmlHeadXtra[] = '<link href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
+$htmlHeadXtra[] = '<link href="'.api_get_path(
+    WEB_LIBRARY_PATH
+).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
 
 $htmlHeadXtra[] = '<script>
 function confirmation(name) {
@@ -72,19 +74,19 @@ function show_icon_edit(element_html) {
 
 //$interbreadcrumb[] = array('url' => '../auth/profile.php', 'name' => get_lang('ModifyProfile'));
 if (!empty ($_GET['coursePath'])) {
-	$course_url = api_get_path(WEB_COURSE_PATH).htmlentities(strip_tags($_GET['coursePath'])).'/index.php';
-	$interbreadcrumb[] = array('url' => $course_url, 'name' => Security::remove_XSS($_GET['courseCode']));
+    $course_url = api_get_path(WEB_COURSE_PATH).htmlentities(strip_tags($_GET['coursePath'])).'/index.php';
+    $interbreadcrumb[] = array('url' => $course_url, 'name' => Security::remove_XSS($_GET['courseCode']));
 }
 
 $warning_msg = '';
 if (!empty($_GET['fe'])) {
-	$warning_msg .= get_lang('UplUnableToSaveFileFilteredExtension');
-	$_GET['fe'] = null;
+    $warning_msg .= get_lang('UplUnableToSaveFileFilteredExtension');
+    $_GET['fe'] = null;
 }
 
 $jquery_ready_content = '';
 if (api_get_setting('allow_message_tool') == 'true') {
-	$jquery_ready_content = <<<EOF
+    $jquery_ready_content = <<<EOF
 			$(".message-content .message-delete").click(function(){
 				$(this).parents(".message-content").animate({ opacity: "hide" }, "slow");
 				$(".message-view").animate({ opacity: "show" }, "slow");
@@ -96,8 +98,6 @@ EOF;
 require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
 
 // Libraries
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-
 $tool_name = is_profile_editable() ? get_lang('ModifProfile') : get_lang('ViewProfile');
 $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
@@ -113,37 +113,46 @@ $value_array = $array_list_key[$id_temp_key];
 $user_data['api_key_generate'] = $value_array;
 
 if ($user_data !== false) {
-	if (is_null($user_data['language'])) {
-		$user_data['language'] = api_get_setting('platformLanguage');
-	}
+    if (is_null($user_data['language'])) {
+        $user_data['language'] = api_get_setting('platformLanguage');
+    }
 }
 
 /*
  * Initialize the form.
  */
-$form = new FormValidator('profile', 'post', api_get_self()."?".str_replace('&fe=1', '', $_SERVER['QUERY_STRING']), null, array('style' => 'width: 70%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
+$form = new FormValidator('profile', 'post', api_get_self()."?".str_replace(
+    '&fe=1',
+    '',
+    $_SERVER['QUERY_STRING']
+), null, array('style' => 'width: 70%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
 
 if (api_is_western_name_order()) {
-	//	FIRST NAME and LAST NAME
-	$form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
-	$form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
+    //	FIRST NAME and LAST NAME
+    $form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
+    $form->addElement('text', 'lastname', get_lang('LastName'), array('size' => 40));
 } else {
-	//	LAST NAME and FIRST NAME
-	$form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
-	$form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
+    //	LAST NAME and FIRST NAME
+    $form->addElement('text', 'lastname', get_lang('LastName'), array('size' => 40));
+    $form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
 }
 if (api_get_setting('profile', 'name') !== 'true') {
-	$form->freeze(array('lastname', 'firstname'));
+    $form->freeze(array('lastname', 'firstname'));
 }
 $form->applyFilter(array('lastname', 'firstname'), 'stripslashes');
 $form->applyFilter(array('lastname', 'firstname'), 'trim');
-$form->addRule('lastname' , get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 
 //	USERNAME
-$form->addElement('text', 'username', get_lang('UserName'), array('maxlength' => USERNAME_MAX_LENGTH, 'size' => USERNAME_MAX_LENGTH));
+$form->addElement(
+    'text',
+    'username',
+    get_lang('UserName'),
+    array('maxlength' => USERNAME_MAX_LENGTH, 'size' => USERNAME_MAX_LENGTH)
+);
 if (api_get_setting('profile', 'login') !== 'true') {
-	$form->freeze('username');
+    $form->freeze('username');
 }
 $form->applyFilter('username', 'stripslashes');
 $form->applyFilter('username', 'trim');
@@ -153,24 +162,28 @@ $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_da
 
 //	OFFICIAL CODE
 if (CONFVAL_ASK_FOR_OFFICIAL_CODE) {
-	$form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
-	if (api_get_setting('profile', 'officialcode') !== 'true') {
-		$form->freeze('official_code');
-	}
-	$form->applyFilter('official_code', 'stripslashes');
-	$form->applyFilter('official_code', 'trim');
-	if (api_get_setting('registration', 'officialcode') == 'true' && api_get_setting('profile', 'officialcode') == 'true') {
-		$form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
-	}
+    $form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
+    if (api_get_setting('profile', 'officialcode') !== 'true') {
+        $form->freeze('official_code');
+    }
+    $form->applyFilter('official_code', 'stripslashes');
+    $form->applyFilter('official_code', 'trim');
+    if (api_get_setting('registration', 'officialcode') == 'true' && api_get_setting(
+        'profile',
+        'officialcode'
+    ) == 'true'
+    ) {
+        $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
+    }
 }
 
 //	EMAIL
 $form->addElement('email', 'email', get_lang('Email'), array('size' => 40));
 if (api_get_setting('profile', 'email') !== 'true') {
-	$form->freeze('email');
+    $form->freeze('email');
 }
 
-if (api_get_setting('registration', 'email') == 'true' &&  api_get_setting('profile', 'email') == 'true') {
+if (api_get_setting('registration', 'email') == 'true' && api_get_setting('profile', 'email') == 'true') {
     $form->applyFilter('email', 'stripslashes');
     $form->applyFilter('email', 'trim');
     $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
@@ -179,20 +192,20 @@ if (api_get_setting('registration', 'email') == 'true' &&  api_get_setting('prof
 
 // OPENID URL
 if (is_profile_editable() && api_get_setting('openid_authentication') == 'true') {
-	$form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40));
-	if (api_get_setting('profile', 'openid') !== 'true') {
-		$form->freeze('openid');
-	}
-	$form->applyFilter('openid', 'trim');
-	//if (api_get_setting('registration', 'openid') == 'true') {
-	//	$form->addRule('openid', get_lang('ThisFieldIsRequired'), 'required');
-	//}
+    $form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40));
+    if (api_get_setting('profile', 'openid') !== 'true') {
+        $form->freeze('openid');
+    }
+    $form->applyFilter('openid', 'trim');
+    //if (api_get_setting('registration', 'openid') == 'true') {
+    //	$form->addRule('openid', get_lang('ThisFieldIsRequired'), 'required');
+    //}
 }
 
 //	PHONE
 $form->addElement('text', 'phone', get_lang('phone'), array('size' => 20));
 if (api_get_setting('profile', 'phone') !== 'true') {
-	$form->freeze('phone');
+    $form->freeze('phone');
 }
 $form->applyFilter('phone', 'stripslashes');
 $form->applyFilter('phone', 'trim');
@@ -203,19 +216,28 @@ $form->addRule('phone', get_lang('EmailWrong'), 'email');*/
 
 //	PICTURE
 if (is_profile_editable() && api_get_setting('profile', 'picture') == 'true') {
-	$form->addElement('file', 'picture', ($user_data['picture_uri'] != '' ? get_lang('UpdateImage') : get_lang('AddImage')));
-	$form->add_progress_bar();
-	if (!empty($user_data['picture_uri'])) {
-		$form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
-	}
-	$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-	$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
+    $form->addElement(
+        'file',
+        'picture',
+        ($user_data['picture_uri'] != '' ? get_lang('UpdateImage') : get_lang('AddImage'))
+    );
+    $form->add_progress_bar();
+    if (!empty($user_data['picture_uri'])) {
+        $form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
+    }
+    $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
+    $form->addRule(
+        'picture',
+        get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
+        'filetype',
+        $allowed_picture_types
+    );
 }
 
 //	LANGUAGE
 $form->addElement('select_language', 'language', get_lang('Language'));
 if (api_get_setting('profile', 'language') !== 'true') {
-	$form->freeze('language');
+    $form->freeze('language');
 }
 
 //THEME
@@ -228,39 +250,71 @@ if (is_profile_editable() && api_get_setting('user_selected_theme') == 'true') {
 }
 //	EXTENDED PROFILE  this make the page very slow!
 if (api_get_setting('extended_profile') == 'true') {
-	if (!isset($_GET['type']) || (isset($_GET['type']) && $_GET['type'] == 'extended')) {
-		$width_extended_profile = 500;
-		//$form->addElement('html', '<a href="javascript: void(0);" onclick="javascript: show_extend();"> show_extend_profile</a>');
-		//$form->addElement('static', null, '<em>'.get_lang('OptionalTextFields').'</em>');
-		//	MY COMPETENCES
-		$form->add_html_editor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
-		//	MY DIPLOMAS
-		$form->add_html_editor('diplomas', get_lang('MyDiplomas'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
-		//	WHAT I AM ABLE TO TEACH
-		$form->add_html_editor('teach', get_lang('MyTeach'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
-
-		//	MY PRODUCTIONS
-		$form->addElement('file', 'production', get_lang('MyProductions'));
-		if ($production_list = UserManager::build_production_list(api_get_user_id(), '', true)) {
-			$form->addElement('static', 'productions_list', null, $production_list);
-		}
-		//	MY PERSONAL OPEN AREA
-		$form->add_html_editor('openarea', get_lang('MyPersonalOpenArea'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '350'));
-		$form->applyFilter(array('competences', 'diplomas', 'teach', 'openarea'), 'stripslashes');
-		$form->applyFilter(array('competences', 'diplomas', 'teach'), 'trim'); // openarea is untrimmed for maximum openness
-	}
+    if (!isset($_GET['type']) || (isset($_GET['type']) && $_GET['type'] == 'extended')) {
+        $width_extended_profile = 500;
+        //$form->addElement('html', '<a href="javascript: void(0);" onclick="javascript: show_extend();"> show_extend_profile</a>');
+        //$form->addElement('static', null, '<em>'.get_lang('OptionalTextFields').'</em>');
+        //	MY COMPETENCES
+        $form->add_html_editor(
+            'competences',
+            get_lang('MyCompetences'),
+            false,
+            false,
+            array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')
+        );
+        //	MY DIPLOMAS
+        $form->add_html_editor(
+            'diplomas',
+            get_lang('MyDiplomas'),
+            false,
+            false,
+            array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')
+        );
+        //	WHAT I AM ABLE TO TEACH
+        $form->add_html_editor(
+            'teach',
+            get_lang('MyTeach'),
+            false,
+            false,
+            array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')
+        );
+
+        //	MY PRODUCTIONS
+        $form->addElement('file', 'production', get_lang('MyProductions'));
+        if ($production_list = UserManager::build_production_list(api_get_user_id(), '', true)) {
+            $form->addElement('static', 'productions_list', null, $production_list);
+        }
+        //	MY PERSONAL OPEN AREA
+        $form->add_html_editor(
+            'openarea',
+            get_lang('MyPersonalOpenArea'),
+            false,
+            false,
+            array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '350')
+        );
+        $form->applyFilter(array('competences', 'diplomas', 'teach', 'openarea'), 'stripslashes');
+        $form->applyFilter(
+            array('competences', 'diplomas', 'teach'),
+            'trim'
+        ); // openarea is untrimmed for maximum openness
+    }
 }
 
 //	PASSWORD, if auth_source is platform
 if (is_platform_authentication() && is_profile_editable() && api_get_setting('profile', 'password') == 'true') {
-	$form->addElement('password', 'password0', array(get_lang('Pass'), get_lang('Enter2passToChange')), array('size' => 40));
-	$form->addElement('password', 'password1', get_lang('NewPass'), array('size' => 40));
-	$form->addElement('password', 'password2', get_lang('Confirmation'), array('size' => 40));
-	//	user must enter identical password twice so we can prevent some user errors
-	$form->addRule(array('password1', 'password2'), get_lang('PassTwo'), 'compare');
-	if (CHECK_PASS_EASY_TO_FIND) {
-		$form->addRule('password1', get_lang('CurrentPasswordEmptyOrIncorrect'), 'callback', 'api_check_password');
-	}
+    $form->addElement(
+        'password',
+        'password0',
+        array(get_lang('Pass'), get_lang('Enter2passToChange')),
+        array('size' => 40)
+    );
+    $form->addElement('password', 'password1', get_lang('NewPass'), array('size' => 40));
+    $form->addElement('password', 'password2', get_lang('Confirmation'), array('size' => 40));
+    //	user must enter identical password twice so we can prevent some user errors
+    $form->addRule(array('password1', 'password2'), get_lang('PassTwo'), 'compare');
+    if (CHECK_PASS_EASY_TO_FIND) {
+        $form->addRule('password1', get_lang('CurrentPasswordEmptyOrIncorrect'), 'callback', 'api_check_password');
+    }
 }
 
 // EXTRA FIELDS
@@ -269,23 +323,33 @@ $return_params = ExtraField::set_extra_fields_in_form($form, $extra_data, 'profi
 $jquery_ready_content = $return_params['jquery_ready_content'];
 
 // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function
-$htmlHeadXtra[] ='<script>
+$htmlHeadXtra[] = '<script>
 $(document).ready(function(){
 	'.$jquery_ready_content.'
 });
 </script>';
 
 if (api_get_setting('profile', 'apikeys') == 'true') {
-	$form->addElement('html', '<div id="div_api_key">');
-	$form->addElement('text', 'api_key_generate', get_lang('MyApiKey'), array('size' => 40, 'id' => 'id_api_key_generate'));
-	$form->addElement('html', '</div>');
-	$form->addElement('button', 'generate_api_key', get_lang('GenerateApiKey'), array('id' => 'id_generate_api_key', 'onclick' => 'generate_open_id_form()')); //generate_open_id_form()
+    $form->addElement('html', '<div id="div_api_key">');
+    $form->addElement(
+        'text',
+        'api_key_generate',
+        get_lang('MyApiKey'),
+        array('size' => 40, 'id' => 'id_api_key_generate')
+    );
+    $form->addElement('html', '</div>');
+    $form->addElement(
+        'button',
+        'generate_api_key',
+        get_lang('GenerateApiKey'),
+        array('id' => 'id_generate_api_key', 'onclick' => 'generate_open_id_form()')
+    ); //generate_open_id_form()
 }
 //	SUBMIT
 if (is_profile_editable()) {
-	$form->addElement('style_submit_button', 'apply_change', get_lang('SaveSettings'), 'class="save"');
+    $form->addElement('style_submit_button', 'apply_change', get_lang('SaveSettings'), 'class="save"');
 } else {
-	$form->freeze();
+    $form->freeze();
 }
 
 $user_data = array_merge($user_data, $extra_data);
@@ -299,18 +363,21 @@ $form->setDefaults($user_data);
  *
  * @return  boolean if auth_source is platform
  */
-function is_platform_authentication() {
+function is_platform_authentication()
+{
     $tab_user_info = api_get_user_info();
+
     return $tab_user_info['auth_source'] == PLATFORM_AUTH_SOURCE;
 }
 
 /**
  * Can a user edit his/her profile?
  *
- * @return	boolean	Editability of the profile
+ * @return    boolean    Editability of the profile
  */
-function is_profile_editable() {
-	return $GLOBALS['profileIsEditable'];
+function is_profile_editable()
+{
+    return $GLOBALS['profileIsEditable'];
 }
 
 /*
@@ -320,108 +387,119 @@ function is_profile_editable() {
 /**
  * Upload a submitted user production.
  *
- * @param	$user_id	User id
- * @return	The filename of the new production or FALSE if the upload has failed
+ * @param    $user_id    User id
+ * @return    The filename of the new production or FALSE if the upload has failed
  */
-function upload_user_production($user_id) {
-	$image_path = UserManager::get_user_picture_path_by_id($user_id, 'system', true);
+function upload_user_production($user_id)
+{
+    $image_path = UserManager::get_user_picture_path_by_id($user_id, 'system', true);
 
-	$production_repository = $image_path['dir'].$user_id.'/';
+    $production_repository = $image_path['dir'].$user_id.'/';
 
-	if (!file_exists($production_repository)) {
-		@mkdir($production_repository, api_get_permissions_for_new_directories(), true);
-	}
-	$filename = replace_dangerous_char($_FILES['production']['name']);
-	$filename = disable_dangerous_file($filename);
+    if (!file_exists($production_repository)) {
+        @mkdir($production_repository, api_get_permissions_for_new_directories(), true);
+    }
+    $filename = replace_dangerous_char($_FILES['production']['name']);
+    $filename = FileManager::disable_dangerous_file($filename);
 
-	if (filter_extension($filename)) {
-		if (@move_uploaded_file($_FILES['production']['tmp_name'], $production_repository.$filename)) {
-			return $filename;
-		}
-	}
-	return false; // this should be returned if anything went wrong with the upload
+    if (FileManager::filter_extension($filename)) {
+        if (@move_uploaded_file($_FILES['production']['tmp_name'], $production_repository.$filename)) {
+            return $filename;
+        }
+    }
+
+    return false; // this should be returned if anything went wrong with the upload
 }
 
 /**
  * Check current user's current password
- * @param	char	password
- * @return	bool true o false
+ * @param    char    password
+ * @return    bool true o false
  * @uses Gets user ID from global variable
  */
-function check_user_password($password){
-	global $_user;
-	$user_id = api_get_user_id();
-	if ($user_id != strval(intval($user_id)) || empty($password)) { return false; }
-	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
-	$password = api_get_encrypted_password($password);
-	$sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND password='".$password."'";
-	$result = Database::query($sql_password);
-	return Database::num_rows($result) != 0;
+function check_user_password($password)
+{
+    global $_user;
+    $user_id = api_get_user_id();
+    if ($user_id != strval(intval($user_id)) || empty($password)) {
+        return false;
+    }
+    $table_user = Database :: get_main_table(TABLE_MAIN_USER);
+    $password = api_get_encrypted_password($password);
+    $sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND password='".$password."'";
+    $result = Database::query($sql_password);
+
+    return Database::num_rows($result) != 0;
 }
+
 /**
  * Check current user's current password
- * @param	char	email
- * @return	bool true o false
+ * @param    char    email
+ * @return    bool true o false
  * @uses Gets user ID from global variable
  */
-function check_user_email($email) {
-	$user_id = api_get_user_id();
-	if ($user_id != strval(intval($user_id)) || empty($email)) { return false; }
-	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
+function check_user_email($email)
+{
+    $user_id = api_get_user_id();
+    if ($user_id != strval(intval($user_id)) || empty($email)) {
+        return false;
+    }
+    $table_user = Database :: get_main_table(TABLE_MAIN_USER);
     $email = Database::escape_string($email);
-	$sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND email='".$email."'";
-	$result = Database::query($sql_password);
-	return Database::num_rows($result) != 0;
+    $sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND email='".$email."'";
+    $result = Database::query($sql_password);
+
+    return Database::num_rows($result) != 0;
 }
 
 /*		MAIN CODE */
-$filtered_extension         = false;
-$update_success             = false;
-$upload_picture_success     = false;
-$upload_production_success  = false;
-$msg_fail_changue_email     = false;
-$msg_is_not_password        = false;
+$filtered_extension = false;
+$update_success = false;
+$upload_picture_success = false;
+$upload_production_success = false;
+$msg_fail_changue_email = false;
+$msg_is_not_password = false;
 
 if (is_platform_authentication()) {
     if (!empty($_SESSION['change_email'])) {
-    	$msg_fail_changue_email= ($_SESSION['change_email'] == 'success');
-    	unset($_SESSION['change_email']);
+        $msg_fail_changue_email = ($_SESSION['change_email'] == 'success');
+        unset($_SESSION['change_email']);
     } elseif (!empty($_SESSION['is_not_password'])) {
-    	$msg_is_not_password = ($_SESSION['is_not_password'] == 'success');
-    	unset($_SESSION['is_not_password']);
+        $msg_is_not_password = ($_SESSION['is_not_password'] == 'success');
+        unset($_SESSION['is_not_password']);
     } elseif (!empty($_SESSION['profile_update'])) {
-    	$update_success = ($_SESSION['profile_update'] == 'success');
-    	unset($_SESSION['profile_update']);
+        $update_success = ($_SESSION['profile_update'] == 'success');
+        unset($_SESSION['profile_update']);
     } elseif (!empty($_SESSION['image_uploaded'])) {
-    	$upload_picture_success = ($_SESSION['image_uploaded'] == 'success');
-    	unset($_SESSION['image_uploaded']);
+        $upload_picture_success = ($_SESSION['image_uploaded'] == 'success');
+        unset($_SESSION['image_uploaded']);
     } elseif (!empty($_SESSION['production_uploaded'])) {
-    	$upload_production_success = ($_SESSION['production_uploaded'] == 'success');
-    	unset($_SESSION['production_uploaded']);
+        $upload_production_success = ($_SESSION['production_uploaded'] == 'success');
+        unset($_SESSION['production_uploaded']);
     }
 }
 
 if ($form->validate()) {
 
-	$wrong_current_password = false;
+    $wrong_current_password = false;
 //	$user_data = $form->exportValues();
-	$user_data = $form->getSubmitValues();
-
-	// set password if a new one was provided
-	if (!empty($user_data['password0'])) {
-		if (check_user_password($user_data['password0'])) {
-			if (!empty($user_data['password1'])) {
-				$password = $user_data['password1'];
-			}
-		} else {
-			$wrong_current_password = true;
-			$_SESSION['is_not_password'] = 'success';
-		}
-	}
-	if (empty($user_data['password0']) && !empty($user_data['password1'])) {
-		$wrong_current_password = true;
-		$_SESSION['is_not_password'] = 'success';
-	}
+    $user_data = $form->getSubmitValues();
+
+    // set password if a new one was provided
+    if (!empty($user_data['password0'])) {
+        if (check_user_password($user_data['password0'])) {
+            if (!empty($user_data['password1'])) {
+                $password = $user_data['password1'];
+            }
+        } else {
+            $wrong_current_password = true;
+            $_SESSION['is_not_password'] = 'success';
+        }
+    }
+    if (empty($user_data['password0']) && !empty($user_data['password1'])) {
+        $wrong_current_password = true;
+        $_SESSION['is_not_password'] = 'success';
+    }
 
     $allow_users_to_change_email_with_no_password = true;
     if (is_platform_authentication() && api_get_setting('allow_users_to_change_email_with_no_password') == 'false') {
@@ -442,75 +520,83 @@ if ($form->validate()) {
                 $changeemail = $user_data['email'];
             }
 
-            if (!check_user_email($user_data['email']) && empty($user_data['password0'])){
+            if (!check_user_email($user_data['email']) && empty($user_data['password0'])) {
                 $_SESSION['change_email'] = 'success';
             }
         }
     }
 
 
-	// Upload picture if a new one is provided
-	if ($_FILES['picture']['size']) {
-		if ($new_picture = UserManager::update_user_picture(api_get_user_id(), $_FILES['picture']['name'], $_FILES['picture']['tmp_name'])) {
-			$user_data['picture_uri'] = $new_picture;
-			$_SESSION['image_uploaded'] = 'success';
-		}
-	} elseif (!empty($user_data['remove_picture'])) {
-	    // remove existing picture if asked
-		UserManager::delete_user_picture(api_get_user_id());
-		$user_data['picture_uri'] = '';
-	}
-
-	//Remove production
-	if (is_array($user_data['remove_production'])) {
-		foreach (array_keys($user_data['remove_production']) as $production) {
-			UserManager::remove_user_production(api_get_user_id(), urldecode($production));
-		}
-		if ($production_list = UserManager::build_production_list(api_get_user_id(), true, true)) {
-			$form->insertElementBefore($form->createElement('static', null, null, $production_list), 'productions_list');
-		}
-		$form->removeElement('productions_list');
-		$file_deleted = true;
-	}
-
-	// upload production if a new one is provided
-	if ($_FILES['production']['size']) {
-		$res = upload_user_production(api_get_user_id());
-		if (!$res) {
-			//it's a bit excessive to assume the extension is the reason why upload_user_production() returned false, but it's true in most cases
-			$filtered_extension = true;
-		} else {
-			$_SESSION['production_uploaded'] = 'success';
-		}
-	}
-
-	// remove values that shouldn't go in the database
-	unset($user_data['password0'],$user_data['password1'], $user_data['password2'], $user_data['MAX_FILE_SIZE'],
-	$user_data['remove_picture'], $user_data['apply_change'],$user_data['email'] );
-
-	// Following RFC2396 (http://www.faqs.org/rfcs/rfc2396.html), a URI uses ':' as a reserved character
-	// we can thus ensure the URL doesn't contain any scheme name by searching for ':' in the string
-	$my_user_openid = isset($user_data['openid']) ? $user_data['openid'] : '';
-	if (!preg_match('/^[^:]*:\/\/.*$/', $my_user_openid)) {
-		//ensure there is at least a http:// scheme in the URI provided
-		$user_data['openid'] = 'http://'.$my_user_openid;
-	}
-	$extras = array();
-
-	//Checking the user language
-	$languages = api_get_languages();
+    // Upload picture if a new one is provided
+    if ($_FILES['picture']['size']) {
+        if ($new_picture = UserManager::update_user_picture(
+            api_get_user_id(),
+            $_FILES['picture']['name'],
+            $_FILES['picture']['tmp_name']
+        )
+        ) {
+            $user_data['picture_uri'] = $new_picture;
+            $_SESSION['image_uploaded'] = 'success';
+        }
+    } elseif (!empty($user_data['remove_picture'])) {
+        // remove existing picture if asked
+        UserManager::delete_user_picture(api_get_user_id());
+        $user_data['picture_uri'] = '';
+    }
+
+    //Remove production
+    if (is_array($user_data['remove_production'])) {
+        foreach (array_keys($user_data['remove_production']) as $production) {
+            UserManager::remove_user_production(api_get_user_id(), urldecode($production));
+        }
+        if ($production_list = UserManager::build_production_list(api_get_user_id(), true, true)) {
+            $form->insertElementBefore(
+                $form->createElement('static', null, null, $production_list),
+                'productions_list'
+            );
+        }
+        $form->removeElement('productions_list');
+        $file_deleted = true;
+    }
+
+    // upload production if a new one is provided
+    if ($_FILES['production']['size']) {
+        $res = upload_user_production(api_get_user_id());
+        if (!$res) {
+            //it's a bit excessive to assume the extension is the reason why upload_user_production() returned false, but it's true in most cases
+            $filtered_extension = true;
+        } else {
+            $_SESSION['production_uploaded'] = 'success';
+        }
+    }
+
+    // remove values that shouldn't go in the database
+    unset($user_data['password0'], $user_data['password1'], $user_data['password2'], $user_data['MAX_FILE_SIZE'],
+    $user_data['remove_picture'], $user_data['apply_change'], $user_data['email']);
+
+    // Following RFC2396 (http://www.faqs.org/rfcs/rfc2396.html), a URI uses ':' as a reserved character
+    // we can thus ensure the URL doesn't contain any scheme name by searching for ':' in the string
+    $my_user_openid = isset($user_data['openid']) ? $user_data['openid'] : '';
+    if (!preg_match('/^[^:]*:\/\/.*$/', $my_user_openid)) {
+        //ensure there is at least a http:// scheme in the URI provided
+        $user_data['openid'] = 'http://'.$my_user_openid;
+    }
+    $extras = array();
+
+    //Checking the user language
+    $languages = api_get_languages();
     if (!in_array($user_data['language'], $languages['folder'])) {
         $user_data['language'] = api_get_setting('platformLanguage');
     }
 
-	//Only update values that are request by the "profile" setting
-	$profile_list = api_get_setting('profile');
-	//Adding missing variables
+    //Only update values that are request by the "profile" setting
+    $profile_list = api_get_setting('profile');
+    //Adding missing variables
 
-	$available_values_to_modify = array();
-	foreach($profile_list as $key => $status) {
-	    if ($status == 'true') {
-            switch($key) {
+    $available_values_to_modify = array();
+    foreach ($profile_list as $key => $status) {
+        if ($status == 'true') {
+            switch ($key) {
                 case 'login':
                     $available_values_to_modify[] = 'username';
                     break;
@@ -525,41 +611,44 @@ if ($form->validate()) {
                     $available_values_to_modify[] = $key;
                     break;
             }
-	    }
-	}
-
-	//Fixing missing variables
-    $available_values_to_modify = array_merge($available_values_to_modify, array('competences', 'diplomas', 'openarea', 'teach', 'openid'));
-
-	// build SQL query
-	$sql = "UPDATE $table_user SET";
-	unset($user_data['api_key_generate']);
-	foreach ($user_data as $key => $value) {
-		if (substr($key, 0, 6) == 'extra_') { //an extra field
-			$new_key = substr($key, 6);
-			// format array date to 'Y-m-d' or date time  to 'Y-m-d H:i:s'
-			if (is_array($value) && isset($value['Y']) && isset($value['F']) && isset($value['d'])) {
-				if (isset($value['H']) && isset($value['i'])) {
-					// extra field date time
-					$time = mktime($value['H'],$value['i'],0,$value['F'],$value['d'],$value['Y']);
-					$extras[$new_key] = date('Y-m-d H:i:s',$time);
-				} else {
-					// extra field date
-					$time = mktime(0,0,0,$value['F'],$value['d'],$value['Y']);
-					$extras[$new_key] = date('Y-m-d',$time);
-				}
-			} else {
-				$extras[$new_key] = $value;
-			}
-		} else {
-		    if (in_array($key, $available_values_to_modify)) {
+        }
+    }
+
+    //Fixing missing variables
+    $available_values_to_modify = array_merge(
+        $available_values_to_modify,
+        array('competences', 'diplomas', 'openarea', 'teach', 'openid')
+    );
+
+    // build SQL query
+    $sql = "UPDATE $table_user SET";
+    unset($user_data['api_key_generate']);
+    foreach ($user_data as $key => $value) {
+        if (substr($key, 0, 6) == 'extra_') { //an extra field
+            $new_key = substr($key, 6);
+            // format array date to 'Y-m-d' or date time  to 'Y-m-d H:i:s'
+            if (is_array($value) && isset($value['Y']) && isset($value['F']) && isset($value['d'])) {
+                if (isset($value['H']) && isset($value['i'])) {
+                    // extra field date time
+                    $time = mktime($value['H'], $value['i'], 0, $value['F'], $value['d'], $value['Y']);
+                    $extras[$new_key] = date('Y-m-d H:i:s', $time);
+                } else {
+                    // extra field date
+                    $time = mktime(0, 0, 0, $value['F'], $value['d'], $value['Y']);
+                    $extras[$new_key] = date('Y-m-d', $time);
+                }
+            } else {
+                $extras[$new_key] = $value;
+            }
+        } else {
+            if (in_array($key, $available_values_to_modify)) {
                 $sql .= " $key = '".Database::escape_string($value)."',";
-		    }
-		}
-	}
+            }
+        }
+    }
 
-	//change email
-	if ($allow_users_to_change_email_with_no_password) {
+    //change email
+    if ($allow_users_to_change_email_with_no_password) {
         if (isset($changeemail) && in_array('email', $available_values_to_modify)) {
             $sql .= " email = '".Database::escape_string($changeemail)."',";
         }
@@ -572,12 +661,16 @@ if ($form->validate()) {
         }
     } else {
         //normal behaviour
-        if(empty($changeemail) && isset($password)) {
+        if (empty($changeemail) && isset($password)) {
             $sql .= " email = y@u.com";
         }
         if (isset($changeemail) && !isset($password) && in_array('email', $available_values_to_modify)) {
             $sql .= " email = '".Database::escape_string($changeemail)."'";
-        } elseif (isset($password) && isset($changeemail) && in_array('email', $available_values_to_modify) && in_array('password', $available_values_to_modify)) {
+        } elseif (isset($password) && isset($changeemail) && in_array('email', $available_values_to_modify) && in_array(
+            'password',
+            $available_values_to_modify
+        )
+        ) {
             $sql .= " email = '".Database::escape_string($changeemail)."',";
             $password = api_get_encrypted_password($password);
             $sql .= " password = '".Database::escape_string($password)."'";
@@ -592,34 +685,37 @@ if ($form->validate()) {
     if (api_get_setting('profile', 'officialcode') == 'true' && isset($user_data['official_code'])) {
         $sql .= ", official_code = '".Database::escape_string($user_data['official_code'])."'";
     }
-	$sql .= " WHERE user_id  = '".api_get_user_id()."'";
-	Database::query($sql);
+    $sql .= " WHERE user_id  = '".api_get_user_id()."'";
+    Database::query($sql);
 
 
-	// User tag process
-	//1. Deleting all user tags
-	$list_extra_field_type_tag = UserManager::get_all_extra_field_by_type(ExtraField::FIELD_TYPE_TAG);
+    // User tag process
+    //1. Deleting all user tags
+    $list_extra_field_type_tag = UserManager::get_all_extra_field_by_type(ExtraField::FIELD_TYPE_TAG);
 
-	if (is_array($list_extra_field_type_tag) && count($list_extra_field_type_tag)>0) {
-		foreach ($list_extra_field_type_tag as $id) {
-			UserManager::delete_user_tags(api_get_user_id(), $id);
-		}
-	}
+    if (is_array($list_extra_field_type_tag) && count($list_extra_field_type_tag) > 0) {
+        foreach ($list_extra_field_type_tag as $id) {
+            UserManager::delete_user_tags(api_get_user_id(), $id);
+        }
+    }
 
-	//2. Update the extra fields and user tags if available
+    //2. Update the extra fields and user tags if available
 
-	if (is_array($extras) && count($extras)> 0) {
-		foreach ($extras as $key => $value) {
-			//3. Tags are process in the UserManager::update_extra_field_value by the UserManager::process_tags function
-			UserManager::update_extra_field_value(api_get_user_id(), $key, $value);
-		}
-	}
+    if (is_array($extras) && count($extras) > 0) {
+        foreach ($extras as $key => $value) {
+            //3. Tags are process in the UserManager::update_extra_field_value by the UserManager::process_tags function
+            UserManager::update_extra_field_value(api_get_user_id(), $key, $value);
+        }
+    }
 
     // re-init the system to take new settings into account
     $_SESSION['_user']['uidReset'] = true;
     $_SESSION['noredirection'] = true;
     $_SESSION['profile_update'] = 'success';
-    $url = api_get_self()."?{$_SERVER['QUERY_STRING']}".($filtered_extension && strpos($_SERVER['QUERY_STRING'], '&fe=1') === false ? '&fe=1' : '');
+    $url = api_get_self()."?{$_SERVER['QUERY_STRING']}".($filtered_extension && strpos(
+        $_SERVER['QUERY_STRING'],
+        '&fe=1'
+    ) === false ? '&fe=1' : '');
     header("Location: ".$url);
     exit;
 }
@@ -631,50 +727,66 @@ Display::display_header(get_lang('ModifyProfile'));
 
 if (api_get_setting('allow_social_tool') != 'true') {
 
-	if (api_get_setting('extended_profile') == 'true') {
-		echo '<div class="actions">';
+    if (api_get_setting('extended_profile') == 'true') {
+        echo '<div class="actions">';
 
-		if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
-			echo '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.Display::return_icon('shared_profile.png', get_lang('ViewSharedProfile')).'</a>';
-		}
-		if (api_get_setting('allow_message_tool') == 'true') {
-			echo '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.Display::return_icon('inbox.png', get_lang('Messages')).'</a>';
-		}
-		$show = isset($_GET['show']) ? '&amp;show='.Security::remove_XSS($_GET['show']) : '';
-
-		if (isset($_GET['type']) && $_GET['type'] == 'extended') {
-			echo '<a href="profile.php?type=reduced'.$show.'">'.Display::return_icon('edit.png', get_lang('EditNormalProfile'),'',16).'</a>';
-		} else {
-			echo '<a href="profile.php?type=extended'.$show.'">'.Display::return_icon('edit.png', get_lang('EditExtendProfile'),'',16).'</a>';
-		}
-		echo '</div>';
-	}
+        if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
+            echo '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.Display::return_icon(
+                'shared_profile.png',
+                get_lang('ViewSharedProfile')
+            ).'</a>';
+        }
+        if (api_get_setting('allow_message_tool') == 'true') {
+            echo '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.Display::return_icon(
+                'inbox.png',
+                get_lang('Messages')
+            ).'</a>';
+        }
+        $show = isset($_GET['show']) ? '&amp;show='.Security::remove_XSS($_GET['show']) : '';
+
+        if (isset($_GET['type']) && $_GET['type'] == 'extended') {
+            echo '<a href="profile.php?type=reduced'.$show.'">'.Display::return_icon(
+                'edit.png',
+                get_lang('EditNormalProfile'),
+                '',
+                16
+            ).'</a>';
+        } else {
+            echo '<a href="profile.php?type=extended'.$show.'">'.Display::return_icon(
+                'edit.png',
+                get_lang('EditExtendProfile'),
+                '',
+                16
+            ).'</a>';
+        }
+        echo '</div>';
+    }
 }
 
 if (!empty($file_deleted)) {
-	Display :: display_confirmation_message(get_lang('FileDeleted'), false);
+    Display :: display_confirmation_message(get_lang('FileDeleted'), false);
 } elseif (!empty($update_success)) {
-	$message = get_lang('ProfileReg');
+    $message = get_lang('ProfileReg');
 
-	if ($upload_picture_success) {
-		$message .= '<br /> '.get_lang('PictureUploaded');
-	}
+    if ($upload_picture_success) {
+        $message .= '<br /> '.get_lang('PictureUploaded');
+    }
 
-	if ($upload_production_success) {
-		$message.='<br />'.get_lang('ProductionUploaded');
-	}
-	Display :: display_confirmation_message($message, false);
+    if ($upload_production_success) {
+        $message .= '<br />'.get_lang('ProductionUploaded');
+    }
+    Display :: display_confirmation_message($message, false);
 }
 
 
-if (!empty($msg_fail_changue_email)){
-	$errormail=get_lang('ToChangeYourEmailMustTypeYourPassword');
-	Display :: display_error_message($errormail, false);
+if (!empty($msg_fail_changue_email)) {
+    $errormail = get_lang('ToChangeYourEmailMustTypeYourPassword');
+    Display :: display_error_message($errormail, false);
 }
 
-if (!empty($msg_is_not_password)){
-	$warning_msg = get_lang('CurrentPasswordEmptyOrIncorrect');
-	Display :: display_warning_message($warning_msg, false);
+if (!empty($msg_is_not_password)) {
+    $warning_msg = get_lang('CurrentPasswordEmptyOrIncorrect');
+    Display :: display_warning_message($warning_msg, false);
 }
 
 //User picture size is calculated from SYSTEM path
@@ -689,8 +801,8 @@ $image_dir = $image_path['dir'];
 $image = $image_path['file'];
 $image_file = $image_dir.$image;
 $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
-	.'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
-	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; margin-top:0px;padding:5px;" ';
+    .'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
+    .'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; margin-top:0px;padding:5px;" ';
 /*
 if ($image_size['width'] > 300) {
 	//limit display width to 300px
@@ -700,32 +812,32 @@ if ($image_size['width'] > 300) {
 // get the path,width and height from original picture
 $big_image = $image_dir.'big_'.$image;
 
-$big_image_size     = api_getimagesize($big_image);
-$big_image_width    = $big_image_size['width'];
-$big_image_height   = $big_image_size['height'];
-$url_big_image      = $big_image.'?rnd='.time();
+$big_image_size = api_getimagesize($big_image);
+$big_image_width = $big_image_size['width'];
+$big_image_height = $big_image_size['height'];
+$url_big_image = $big_image.'?rnd='.time();
 
 $show_delete_account_button = api_get_setting('platform_unsubscribe_allowed') == 'true' ? true : false;
 
 if (api_get_setting('allow_social_tool') == 'true') {
-	echo '<div class="row-fluid">';
-		echo '<div class="span3">';
-		echo SocialManager::show_social_menu('home', null, api_get_user_id(), false, $show_delete_account_button);
-		echo '</div>';
-		echo '<div class="span9">';
-        $form->display();
-	echo '</div>';
+    echo '<div class="row-fluid">';
+    echo '<div class="span3">';
+    echo SocialManager::show_social_menu('home', null, api_get_user_id(), false, $show_delete_account_button);
+    echo '</div>';
+    echo '<div class="span9">';
+    $form->display();
+    echo '</div>';
 } else {
-	// Style position:absolute has been removed for Opera-compatibility.
-	//echo '<div id="image-message-container" style="float:right;display:inline;position:absolute;padding:3px;width:250px;" >';
-	echo '<div id="image-message-container" style="float:right;display:inline;padding:3px;width:230px;" >';
-
-	if ($image == 'unknown.jpg') {
-		echo '<img '.$img_attributes.' />';
-	} else {
-		echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
-	}
-	echo '</div>';
-	$form->display();
+    // Style position:absolute has been removed for Opera-compatibility.
+    //echo '<div id="image-message-container" style="float:right;display:inline;position:absolute;padding:3px;width:250px;" >';
+    echo '<div id="image-message-container" style="float:right;display:inline;padding:3px;width:230px;" >';
+
+    if ($image == 'unknown.jpg') {
+        echo '<img '.$img_attributes.' />';
+    } else {
+        echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
+    }
+    echo '</div>';
+    $form->display();
 }
 Display :: display_footer();

Fișier diff suprimat deoarece este prea mare
+ 375 - 103
main/calendar/agenda.inc.php


+ 83 - 24
main/calendar/agenda.php

@@ -38,20 +38,37 @@ if (empty($action)) {
 /* 	Resource linker */
 $_SESSION['source_type'] = 'Agenda';
 require_once '../resourcelinker/resourcelinker.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 
 if (!empty($addresources)) {
     // When the "Add Resource" button is clicked we store all the form data into a session
-    $form_elements = array('day' => Security::remove_XSS($_POST['fday']), 'month' => Security::remove_XSS($_POST['fmonth']), 'year' => Security::remove_XSS($_POST['fyear']), 'hour' => Security::remove_XSS($_POST['fhour']), 'minutes' => Security::remove_XSS($_POST['fminute']),
-        'end_day' => Security::remove_XSS($_POST['end_fday']), 'end_month' => Security::remove_XSS($_POST['end_fmonth']), 'end_year' => Security::remove_XSS($_POST['end_fyear']), 'end_hours' => Security::remove_XSS($_POST['end_fhour']), 'end_minutes' => Security::remove_XSS($_POST['end_fminute']),
-        'title' => Security::remove_XSS(stripslashes($_POST['title'])), 'content' => Security::remove_XSS(stripslashes($_POST['content'])), 'id' => Security::remove_XSS($_POST['id']), 'action' => Security::remove_XSS($_POST['action']), 'to' => Security::remove_XSS($_POST['selectedform']));
+    $form_elements = array(
+        'day' => Security::remove_XSS($_POST['fday']),
+        'month' => Security::remove_XSS($_POST['fmonth']),
+        'year' => Security::remove_XSS($_POST['fyear']),
+        'hour' => Security::remove_XSS($_POST['fhour']),
+        'minutes' => Security::remove_XSS($_POST['fminute']),
+        'end_day' => Security::remove_XSS($_POST['end_fday']),
+        'end_month' => Security::remove_XSS($_POST['end_fmonth']),
+        'end_year' => Security::remove_XSS($_POST['end_fyear']),
+        'end_hours' => Security::remove_XSS($_POST['end_fhour']),
+        'end_minutes' => Security::remove_XSS($_POST['end_fminute']),
+        'title' => Security::remove_XSS(stripslashes($_POST['title'])),
+        'content' => Security::remove_XSS(stripslashes($_POST['content'])),
+        'id' => Security::remove_XSS($_POST['id']),
+        'action' => Security::remove_XSS($_POST['action']),
+        'to' => Security::remove_XSS($_POST['selectedform'])
+    );
     $_SESSION['formelements'] = $form_elements;
     // this is to correctly handle edits
     if ($id) {
         $action = "edit";
     }
     //print_r($form_elements);
-    header('Location: '.api_get_path(WEB_CODE_PATH)."resourcelinker/resourcelinker.php?source_id=1&action=$action&id=$id&originalresource=no");
+    header(
+        'Location: '.api_get_path(
+            WEB_CODE_PATH
+        )."resourcelinker/resourcelinker.php?source_id=1&action=$action&id=$id&originalresource=no"
+    );
     exit;
 }
 
@@ -85,8 +102,8 @@ if (!empty($_GET['sort']) and ($allow_individual_calendar_status == "show")) {
 
 // 4. filter user or group
 if (!empty($_GET['user']) or !empty($_GET['group'])) {
-    $_SESSION['user'] = (int) $_GET['user'];
-    $_SESSION['group'] = (int) $_GET['group'];
+    $_SESSION['user'] = (int)$_GET['user'];
+    $_SESSION['group'] = (int)$_GET['group'];
 }
 if ((!empty($_GET['user']) and $_GET['user'] == "none") or (!empty($_GET['group']) and $_GET['group'] == "none")) {
     Session::erase("user");
@@ -111,7 +128,10 @@ $nameTools = get_lang('Agenda'); // language variable in trad4all.inc.php
 if (!empty($group_id)) {
     $group_properties = GroupManager :: get_group_properties($group_id);
     $interbreadcrumb[] = array("url" => "../group/group.php", "name" => get_lang('Groups'));
-    $interbreadcrumb[] = array("url" => "../group/group_space.php?gidReq=".$group_id, "name" => get_lang('GroupSpace').' '.$group_properties['name']);
+    $interbreadcrumb[] = array(
+        "url" => "../group/group_space.php?gidReq=".$group_id,
+        "name" => get_lang('GroupSpace').' '.$group_properties['name']
+    );
     Display::display_header($nameTools, 'Agenda');
 } elseif (empty($origin) or $origin != 'learnpath') {
     Display::display_header($nameTools, 'Agenda');
@@ -145,7 +165,9 @@ $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_US
 
 /*   			ACCESS RIGHTS */
 // permission stuff - also used by loading from global in agenda.inc.php
-$is_allowed_to_edit = api_is_allowed_to_edit(false, true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous());
+$is_allowed_to_edit = api_is_allowed_to_edit(false, true) OR (api_get_course_setting(
+    'allow_user_edit_agenda'
+) && !api_is_anonymous());
 
 // Tool introduction
 Display::display_introduction_section(TOOL_CALENDAR_EVENT);
@@ -158,13 +180,13 @@ $select_month = '';
 $select_day = '';
 
 if (!empty($_GET['year'])) {
-    $select_year = (int) $_GET['year'];
+    $select_year = (int)$_GET['year'];
 }
 if (!empty($_GET['month'])) {
-    $select_month = (int) $_GET['month'];
+    $select_month = (int)$_GET['month'];
 }
 if (!empty($_GET['day'])) {
-    $select_day = (int) $_GET['day'];
+    $select_day = (int)$_GET['day'];
 }
 
 $today = getdate();
@@ -179,8 +201,15 @@ if (empty($select_month)) {
 echo '<div class="actions">';
 
 if (api_is_allowed_to_edit(false, true) OR
-    (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(false, true) OR
-    GroupManager::user_has_access(api_get_user_id(), $group_id,  GroupManager::GROUP_TOOL_CALENDAR) && GroupManager::is_tutor_of_group(api_get_user_id(), $group_id)
+    (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(
+        false,
+        true
+    ) OR
+    GroupManager::user_has_access(
+        api_get_user_id(),
+        $group_id,
+        GroupManager::GROUP_TOOL_CALENDAR
+    ) && GroupManager::is_tutor_of_group(api_get_user_id(), $group_id)
 ) {
     echo display_courseadmin_links();
 }
@@ -192,27 +221,50 @@ $event_id = isset($_GET['id']) ? $_GET['id'] : null;
 $course_info = api_get_course_info();
 
 if (api_is_allowed_to_edit(false, true) OR
-    (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(false, true)) OR
-     GroupManager::user_has_access(api_get_user_id(), $group_id,  GroupManager::GROUP_TOOL_CALENDAR) && GroupManager::is_tutor_of_group(api_get_user_id(), $group_id)
-    ) {
+    (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous() && api_is_allowed_to_session_edit(
+        false,
+        true
+    )) OR
+    GroupManager::user_has_access(
+        api_get_user_id(),
+        $group_id,
+        GroupManager::GROUP_TOOL_CALENDAR
+    ) && GroupManager::is_tutor_of_group(api_get_user_id(), $group_id)
+) {
     switch ($action) {
         case 'add':
             if (isset($_POST['submit_event']) && $_POST['submit_event']) {
-                $event_start = (int) $_POST['fyear'].'-'.(int) $_POST['fmonth'].'-'.(int) $_POST['fday'].' '.(int) $_POST['fhour'].':'.(int) $_POST['fminute'].':00';
-                $event_stop = (int) $_POST['end_fyear'].'-'.(int) $_POST['end_fmonth'].'-'.(int) $_POST['end_fday'].' '.(int) $_POST['end_fhour'].':'.(int) $_POST['end_fminute'].':00';
+                $event_start = (int)$_POST['fyear'].'-'.(int)$_POST['fmonth'].'-'.(int)$_POST['fday'].' '.(int)$_POST['fhour'].':'.(int)$_POST['fminute'].':00';
+                $event_stop = (int)$_POST['end_fyear'].'-'.(int)$_POST['end_fmonth'].'-'.(int)$_POST['end_fday'].' '.(int)$_POST['end_fhour'].':'.(int)$_POST['end_fminute'].':00';
                 $safe_title = Security::remove_XSS($_POST['title']);
                 $safe_file_comment = Security::remove_XSS($_POST['file_comment']);
 
                 if ($_POST['empty_end_date'] == 'on') {
                     $event_stop = '0000-00-00 00:00:00';
                 }
-                $id = agenda_add_item($course_info, $safe_title, $_POST['content'], $event_start, $event_stop, $_POST['selected_form'], false, $safe_file_comment);
+                $id = agenda_add_item(
+                    $course_info,
+                    $safe_title,
+                    $_POST['content'],
+                    $event_start,
+                    $event_stop,
+                    $_POST['selected_form'],
+                    false,
+                    $safe_file_comment
+                );
                 if (!empty($_POST['repeat'])) {
                     $end_y = intval($_POST['repeat_end_year']);
                     $end_m = intval($_POST['repeat_end_month']);
                     $end_d = intval($_POST['repeat_end_day']);
                     $end = mktime(23, 59, 59, $end_m, $end_d, $end_y);
-                    $res = agenda_add_repeat_item($course_info, $id, $_POST['repeat_type'], $end, $_POST['selected_form'], $safe_file_comment);
+                    $res = agenda_add_repeat_item(
+                        $course_info,
+                        $id,
+                        $_POST['repeat_type'],
+                        $end,
+                        $_POST['selected_form'],
+                        $safe_file_comment
+                    );
                 }
                 Display::display_confirmation_message(get_lang('AddSuccess'));
             } else {
@@ -225,7 +277,14 @@ if (api_is_allowed_to_edit(false, true) OR
                 // a coach can only delete an element belonging to his session
                 $ann_id = store_agenda_item_as_announcement($event_id);
                 $tool_group_link = (isset($_SESSION['toolgroup']) ? '&toolgroup='.$_SESSION['toolgroup'] : '');
-                Display::display_normal_message(get_lang('CopiedAsAnnouncement').'&nbsp;<a href="../announcements/announcements.php?id='.$ann_id.$tool_group_link.'">'.get_lang('NewAnnouncement').'</a>', false);
+                Display::display_normal_message(
+                    get_lang(
+                        'CopiedAsAnnouncement'
+                    ).'&nbsp;<a href="../announcements/announcements.php?id='.$ann_id.$tool_group_link.'">'.get_lang(
+                        'NewAnnouncement'
+                    ).'</a>',
+                    false
+                );
             }
             break;
         case 'importical':
@@ -267,7 +326,7 @@ if (api_is_allowed_to_edit(false, true) OR
             }
             break;
         case "delete":
-            if (!(api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $event_id) )) {
+            if (!(api_is_course_coach() && !api_is_element_in_the_session(TOOL_AGENDA, $event_id))) {
                 // a coach can only delete an element belonging to his session
                 delete_agenda_item($event_id);
                 $action = 'view';
@@ -283,7 +342,7 @@ if (api_is_allowed_to_edit(false, true) OR
                 display_one_agenda_item($_GET['agenda_id']);
             }
             break;
-        case "delete_attach":  //delete attachment file
+        case "delete_attach": //delete attachment file
             $id_attach = $_GET['id_attach'];
             if (!empty($id_attach)) {
                 delete_attachment_file($id_attach);

+ 198 - 141
main/chat/chat_chat.php

@@ -2,10 +2,10 @@
 /* For licensing terms, see /license.txt */
 
 /**
- *	Chat frame that shows the message list
+ *    Chat frame that shows the message list
  *
- *	@author Olivier Brouckaert
- *	@package chamilo.chat
+ * @author Olivier Brouckaert
+ * @package chamilo.chat
  */
 /**
  * Code
@@ -16,152 +16,209 @@ define('FRAME', 'chat');
 $language_file = array('chat');
 require_once '../inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
 
 $course = $_GET['cidReq'];
 $session_id = intval($_SESSION['id_session']);
-$group_id 	= intval($_SESSION['_gid']);
+$group_id = intval($_SESSION['_gid']);
 
 // if we have the session set up
 if (!empty($course)) {
-	$reset = (bool)$_GET['reset'];
-	$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-	$query = "SELECT username FROM $tbl_user WHERE user_id='".intval($_user['user_id'])."'";
-	$result = Database::query($query);
-
-	list($pseudo_user) = Database::fetch_row($result);
-
-	$isAllowed = !(empty($pseudo_user) || !$_cid);
-	$isMaster = (bool)$is_courseAdmin;
-
-	$date_now = date('Y-m-d');
-	$basepath_chat = '';
-	$document_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-	if (!empty($group_id)) {
-		$group_info = GroupManager :: get_group_properties($group_id);
-		$basepath_chat = $group_info['directory'].'/chat_files';
-	} else {
-		$basepath_chat = '/chat_files';
-	}
-	$chat_path = $document_path.$basepath_chat.'/';
-
-	$TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-	
-	$course_id = api_get_course_int_id();
-
-	if (!is_dir($chat_path)) {
-		if (is_file($chat_path)) {
-			@unlink($chat_path);
-		}
-
-		if (!api_is_anonymous()) {
-			@mkdir($chat_path, api_get_permissions_for_new_directories());
-			// Save chat files document for group into item property
-			if (!empty($group_id)) {
-				$doc_id = add_document($_course, $basepath_chat, 'folder', 0, 'chat_files');
-				$sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
+    $reset = (bool)$_GET['reset'];
+    $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+    $query = "SELECT username FROM $tbl_user WHERE user_id='".intval($_user['user_id'])."'";
+    $result = Database::query($query);
+
+    list($pseudo_user) = Database::fetch_row($result);
+
+    $isAllowed = !(empty($pseudo_user) || !$_cid);
+    $isMaster = (bool)$is_courseAdmin;
+
+    $date_now = date('Y-m-d');
+    $basepath_chat = '';
+    $document_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
+    if (!empty($group_id)) {
+        $group_info = GroupManager :: get_group_properties($group_id);
+        $basepath_chat = $group_info['directory'].'/chat_files';
+    } else {
+        $basepath_chat = '/chat_files';
+    }
+    $chat_path = $document_path.$basepath_chat.'/';
+
+    $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+    $course_id = api_get_course_int_id();
+
+    if (!is_dir($chat_path)) {
+        if (is_file($chat_path)) {
+            @unlink($chat_path);
+        }
+
+        if (!api_is_anonymous()) {
+            @mkdir($chat_path, api_get_permissions_for_new_directories());
+            // Save chat files document for group into item property
+            if (!empty($group_id)) {
+                $doc_id = FileManager::add_document($_course, $basepath_chat, 'folder', 0, 'chat_files');
+                $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
 						VALUES ($course_id, 'document',1,NOW(),NOW(),$doc_id,'FolderCreated',1,$group_id,NULL,0)";
-				Database::query($sql);
-			}
-		}
-	}
-
-	$filename_chat = '';
-	if (!empty($group_id)) {
-		$filename_chat = 'messages-'.$date_now.'_gid-'.$group_id.'.log.html';
-	} else if (!empty($session_id)) {
-		$filename_chat = 'messages-'.$date_now.'_sid-'.$session_id.'.log.html';
-	} else {
-		$filename_chat = 'messages-'.$date_now.'.log.html';
-	}
-	
-	if (!file_exists($chat_path.$filename_chat)) {
-		@fclose(fopen($chat_path.$filename_chat, 'w'));
-		if (!api_is_anonymous()) {
-			$doc_id = add_document($_course, $basepath_chat.'/'.$filename_chat, 'file', 0, $filename_chat);
-			api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $group_id, null, null, null, $session_id);
-			api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], $group_id, null, null, null, $session_id);
-			item_property_update_on_folder($_course, $basepath_chat, $_user['user_id']);
-		}
-	}
-
-	$basename_chat = '';
-	if (!empty($group_id)) {
-		$basename_chat = 'messages-'.$date_now.'_gid-'.$group_id;
-	} else if (!empty($session_id)) {
-		$basename_chat = 'messages-'.$date_now.'_sid-'.$session_id;
-	} else {
-		$basename_chat = 'messages-'.$date_now;
-	}
-
-	if ($reset && $isMaster) {
-
-		$i = 1;
-		while (file_exists($chat_path.$basename_chat.'-'.$i.'.log.html')) {
-			$i++;
-		}
-
-		@rename($chat_path.$basename_chat.'.log.html', $chat_path.$basename_chat.'-'.$i.'.log.html');
-
-		@fclose(fopen($chat_path.$basename_chat.'.log.html', 'w'));
-
-		$doc_id = add_document($_course, $basepath_chat.'/'.$basename_chat.'-'.$i.'.log.html', 'file', filesize($chat_path.$basename_chat.'-'.$i.'.log.html'), $basename_chat.'-'.$i.'.log.html');
-
-		api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $group_id, null, null, null, $session_id);
-		api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], $group_id, null, null, null, $session_id);
-		item_property_update_on_folder($_course,$basepath_chat, $_user['user_id']);
-
-		$doc_id = DocumentManager::get_document_id($_course, $basepath_chat.'/'.$basename_chat.'.log.html');
-
-		update_existing_document($_course, $doc_id, 0);
-	}
-	
-	$remove = 0;
-	$content = array();
-	if (file_exists($chat_path.$basename_chat.'.log.html')) {
-		$content = file($chat_path.$basename_chat.'.log.html');
-		$nbr_lines = sizeof($content);
-		$remove = $nbr_lines - 100;
-	}
-
-	if ($remove < 0) {
-		$remove = 0;
-	}
-
-	array_splice($content, 0, $remove);
-	require 'header_frame.inc.php';
-
-	if ($_GET['origin'] == 'whoisonline') {  //the caller
-		$content[0] = get_lang('CallSent').'<br />'.$content[0];
-	}
-	if ($_GET['origin'] == 'whoisonlinejoin') {   //the joiner (we have to delete the chat request to him when he joins the chat)
-		$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
-		$sql = "UPDATE $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' WHERE (user_id = ".$_user['user_id'].")";
-		$result = Database::query($sql);
-	}
-
-	echo '<div style="margin-left: 5px;">';
-	foreach ($content as & $this_line) {
-		echo strip_tags(api_html_entity_decode($this_line), '<br> <span> <b> <i> <img> <font>');
-	}
-	echo '</div>';
-
-	?>
-
-	<a name="bottom" style="text-decoration:none;">&nbsp;</a>
-
-	<?php
-	if ($isMaster || $is_courseCoach) {
-		$rand = mt_rand(1, 1000);
-		echo '<div style="margin-left: 5px;">';
-		echo '<a href="'.api_get_self().'?rand='.$rand.'&reset=1&cidReq='.$_GET['cidReq'].'#bottom" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang('ConfirmReset'), ENT_QUOTES)).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('ClearList')).' '.get_lang('ClearList').'</a>';
-		echo '</div>';
-	}
+                Database::query($sql);
+            }
+        }
+    }
+
+    $filename_chat = '';
+    if (!empty($group_id)) {
+        $filename_chat = 'messages-'.$date_now.'_gid-'.$group_id.'.log.html';
+    } else {
+        if (!empty($session_id)) {
+            $filename_chat = 'messages-'.$date_now.'_sid-'.$session_id.'.log.html';
+        } else {
+            $filename_chat = 'messages-'.$date_now.'.log.html';
+        }
+    }
+
+    if (!file_exists($chat_path.$filename_chat)) {
+        @fclose(fopen($chat_path.$filename_chat, 'w'));
+        if (!api_is_anonymous()) {
+            $doc_id = FileManager::add_document($_course, $basepath_chat.'/'.$filename_chat, 'file', 0, $filename_chat);
+            api_item_property_update(
+                $_course,
+                TOOL_DOCUMENT,
+                $doc_id,
+                'DocumentAdded',
+                $_user['user_id'],
+                $group_id,
+                null,
+                null,
+                null,
+                $session_id
+            );
+            api_item_property_update(
+                $_course,
+                TOOL_DOCUMENT,
+                $doc_id,
+                'invisible',
+                $_user['user_id'],
+                $group_id,
+                null,
+                null,
+                null,
+                $session_id
+            );
+            FileManager::item_property_update_on_folder($_course, $basepath_chat, $_user['user_id']);
+        }
+    }
+
+    $basename_chat = '';
+    if (!empty($group_id)) {
+        $basename_chat = 'messages-'.$date_now.'_gid-'.$group_id;
+    } else {
+        if (!empty($session_id)) {
+            $basename_chat = 'messages-'.$date_now.'_sid-'.$session_id;
+        } else {
+            $basename_chat = 'messages-'.$date_now;
+        }
+    }
+
+    if ($reset && $isMaster) {
+
+        $i = 1;
+        while (file_exists($chat_path.$basename_chat.'-'.$i.'.log.html')) {
+            $i++;
+        }
+
+        @rename($chat_path.$basename_chat.'.log.html', $chat_path.$basename_chat.'-'.$i.'.log.html');
+
+        @fclose(fopen($chat_path.$basename_chat.'.log.html', 'w'));
+
+        $doc_id = FileManager::add_document(
+            $_course,
+            $basepath_chat.'/'.$basename_chat.'-'.$i.'.log.html',
+            'file',
+            filesize($chat_path.$basename_chat.'-'.$i.'.log.html'),
+            $basename_chat.'-'.$i.'.log.html'
+        );
+
+        api_item_property_update(
+            $_course,
+            TOOL_DOCUMENT,
+            $doc_id,
+            'DocumentAdded',
+            $_user['user_id'],
+            $group_id,
+            null,
+            null,
+            null,
+            $session_id
+        );
+        api_item_property_update(
+            $_course,
+            TOOL_DOCUMENT,
+            $doc_id,
+            'invisible',
+            $_user['user_id'],
+            $group_id,
+            null,
+            null,
+            null,
+            $session_id
+        );
+        FileManager::item_property_update_on_folder($_course, $basepath_chat, $_user['user_id']);
+
+        $doc_id = DocumentManager::get_document_id($_course, $basepath_chat.'/'.$basename_chat.'.log.html');
+
+        FileManager::update_existing_document($_course, $doc_id, 0);
+    }
+
+    $remove = 0;
+    $content = array();
+    if (file_exists($chat_path.$basename_chat.'.log.html')) {
+        $content = file($chat_path.$basename_chat.'.log.html');
+        $nbr_lines = sizeof($content);
+        $remove = $nbr_lines - 100;
+    }
+
+    if ($remove < 0) {
+        $remove = 0;
+    }
+
+    array_splice($content, 0, $remove);
+    require 'header_frame.inc.php';
+
+    if ($_GET['origin'] == 'whoisonline') { //the caller
+        $content[0] = get_lang('CallSent').'<br />'.$content[0];
+    }
+    if ($_GET['origin'] == 'whoisonlinejoin') { //the joiner (we have to delete the chat request to him when he joins the chat)
+        $track_user_table = Database::get_main_table(TABLE_MAIN_USER);
+        $sql = "UPDATE $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' WHERE (user_id = ".$_user['user_id'].")";
+        $result = Database::query($sql);
+    }
+
+    echo '<div style="margin-left: 5px;">';
+    foreach ($content as & $this_line) {
+        echo strip_tags(api_html_entity_decode($this_line), '<br> <span> <b> <i> <img> <font>');
+    }
+    echo '</div>';
+
+    ?>
+
+<a name="bottom" style="text-decoration:none;">&nbsp;</a>
+
+<?php
+    if ($isMaster || $is_courseCoach) {
+        $rand = mt_rand(1, 1000);
+        echo '<div style="margin-left: 5px;">';
+        echo '<a href="'.api_get_self(
+        ).'?rand='.$rand.'&reset=1&cidReq='.$_GET['cidReq'].'#bottom" onclick="javascript: if(!confirm(\''.addslashes(
+            api_htmlentities(get_lang('ConfirmReset'), ENT_QUOTES)
+        ).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('ClearList')).' '.get_lang(
+            'ClearList'
+        ).'</a>';
+        echo '</div>';
+    }
 } else {
-	require 'header_frame.inc.php';
-	$message = get_lang('CloseOtherSession');
-	Display :: display_error_message($message);
+    require 'header_frame.inc.php';
+    $message = get_lang('CloseOtherSession');
+    Display :: display_error_message($message);
 }
 
 require 'footer_frame.inc.php';

+ 340 - 242
main/chat/chat_message.php

@@ -2,10 +2,10 @@
 /* For licensing terms, see /license.txt */
 
 /**
- *	Allows to type the messages that will be displayed on chat_chat.php
+ *    Allows to type the messages that will be displayed on chat_chat.php
  *
- *	@author Olivier Brouckaert
- *	@package chamilo.chat
+ * @author Olivier Brouckaert
+ * @package chamilo.chat
  */
 /**
  * Code
@@ -22,33 +22,33 @@ require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
 
 $course = api_get_course_id();
 $session_id = intval($_SESSION['id_session']);
-$group_id 	= intval($_SESSION['_gid']);
+$group_id = intval($_SESSION['_gid']);
 
 // Juan Carlos Raña inserted smileys and self-closing window.
 
 ?>
 <script type="text/javascript">
-function insert_smile(text) {
-	if (text.createTextRange) {
-		text.smile = document.selection.createRange().duplicate();
-	}
-}
-
-function insert(text) {
-	var chat = document.formMessage.message;
-	if (chat.createTextRange && chat.smile) {
-		var smile = chat.smile;
-		smile.text = smile.text.charAt(smile.text.length - 1) == ' ' ? text + ' ' : text;
-	}
-	else chat.value += text;
-	chat.focus(smile)
-}
-
-function close_chat_window() {
-	var chat_window = top.window.self;
-	chat_window.opener = top.window.self;
-	chat_window.top.close();
-}
+    function insert_smile(text) {
+        if (text.createTextRange) {
+            text.smile = document.selection.createRange().duplicate();
+        }
+    }
+
+    function insert(text) {
+        var chat = document.formMessage.message;
+        if (chat.createTextRange && chat.smile) {
+            var smile = chat.smile;
+            smile.text = smile.text.charAt(smile.text.length - 1) == ' ' ? text + ' ' : text;
+        }
+        else chat.value += text;
+        chat.focus(smile)
+    }
+
+    function close_chat_window() {
+        var chat_window = top.window.self;
+        chat_window.opener = top.window.self;
+        chat_window.top.close();
+    }
 </script>
 
 <?php
@@ -56,240 +56,338 @@ function close_chat_window() {
 // Mode open in a new window: close the window when there isn't an user login
 
 if (empty($_user['user_id'])) {
-	echo '<script languaje="javascript" type="text/javascript"> close_chat_window(); </script>';
+    echo '<script languaje="javascript" type="text/javascript"> close_chat_window(); </script>';
 } else {
-	api_protect_course_script();
+    api_protect_course_script();
 }
 
 // if we have the session set up
 if (!empty($course) && !empty($_user['user_id'])) {
-	require_once api_get_path(LIBRARY_PATH).'document.lib.php';
-	require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+    require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 
-	/*	Constants and variables */
+    /*	Constants and variables */
 
-	$tbl_user	= Database::get_main_table(TABLE_MAIN_USER);
-	$sent 		= $_REQUEST['sent'];
+    $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+    $sent = $_REQUEST['sent'];
 
-	/*	MAIN CODE */
+    /*	MAIN CODE */
 
-	$query = "SELECT lastname, firstname, username FROM $tbl_user WHERE user_id='".intval($_user['user_id'])."'";
-	$result = Database::query($query);
+    $query = "SELECT lastname, firstname, username FROM $tbl_user WHERE user_id='".intval($_user['user_id'])."'";
+    $result = Database::query($query);
 
-	list($pseudo_user) = Database::fetch_row($result);
+    list($pseudo_user) = Database::fetch_row($result);
 
-	$isAllowed = !(empty($pseudo_user) || !$_cid);
-	$isMaster = (bool)$is_courseAdmin;
+    $isAllowed = !(empty($pseudo_user) || !$_cid);
+    $isMaster = (bool)$is_courseAdmin;
 
-	$firstname = Database::result($result, 0, 'firstname');
-	$lastname  = Database::result($result, 0, 'lastname');
+    $firstname = Database::result($result, 0, 'firstname');
+    $lastname = Database::result($result, 0, 'lastname');
 
-	$date_now = date('Y-m-d');
+    $date_now = date('Y-m-d');
 
-	$basepath_chat = '';
-	$document_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-	if (!empty($group_id)) {
-		$group_info = GroupManager :: get_group_properties($group_id);
-		$basepath_chat = $group_info['directory'].'/chat_files';
-	} else {
-		$basepath_chat = '/chat_files';
-	}
-	$chat_path = $document_path.$basepath_chat.'/';
+    $basepath_chat = '';
+    $document_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
+    if (!empty($group_id)) {
+        $group_info = GroupManager :: get_group_properties($group_id);
+        $basepath_chat = $group_info['directory'].'/chat_files';
+    } else {
+        $basepath_chat = '/chat_files';
+    }
+    $chat_path = $document_path.$basepath_chat.'/';
 
-	$TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-	$course_id = api_get_course_int_id();
+    $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+    $course_id = api_get_course_int_id();
 
-	if (!is_dir($chat_path)) {
-		if (is_file($chat_path)) {
-			@unlink($chat_path);
-		}
-		if (!api_is_anonymous()) {
-			@mkdir($chat_path, api_get_permissions_for_new_directories());
-			// save chat files document for group into item property
-			if (!empty($group_id)) {
-				$doc_id = add_document($_course,$basepath_chat, 'folder', 0, 'chat_files');
-				$sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
+    if (!is_dir($chat_path)) {
+        if (is_file($chat_path)) {
+            @unlink($chat_path);
+        }
+        if (!api_is_anonymous()) {
+            @mkdir($chat_path, api_get_permissions_for_new_directories());
+            // save chat files document for group into item property
+            if (!empty($group_id)) {
+                $doc_id = FileManager::add_document($_course, $basepath_chat, 'folder', 0, 'chat_files');
+                $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
 						VALUES ($course_id, 'document',1,NOW(),NOW(),$doc_id,'FolderCreated',1,$group_id,NULL,0)";
-				Database::query($sql);
-			}
-		}
-	}
-
-	require 'header_frame.inc.php';
-	$chat_size = 0;
-
-	// Define emoticons
-	$emoticon_text1 = ':-)';
-	$emoticon_img1  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_smile.gif" alt="'.get_lang('Smile').'" title="'.get_lang('Smile').'" />';
-	$emoticon_text2 = ':-D';
-	$emoticon_img2  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_biggrin.gif" alt="'.get_lang('BigGrin').'" title="'.get_lang('BigGrin').'" />';
-	$emoticon_text3 = ';-)';
-	$emoticon_img3  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_wink.gif" alt="'.get_lang('Wink').'" title="'.get_lang('Wink').'" />';
-	$emoticon_text4 = ':-P';
-	$emoticon_img4  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_razz.gif" alt="'.get_lang('Avid').'" title="'.get_lang('Avid').'" />';
-	$emoticon_text5 = '8-)';
-	$emoticon_img5  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_cool.gif" alt="'.get_lang('Cool').'" title="'.get_lang('Cool').'" />';
-	$emoticon_text6 = ':-o)';
-	$emoticon_img6  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_surprised.gif" alt="'.get_lang('Surprised').'" title="'.get_lang('Surprised').'" />';
-	$emoticon_text7 = '=;';
-	$emoticon_img7  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_hand.gif" alt="'.get_lang('Hand').'" title="'.get_lang('Hand').'" />';
-	$emoticon_text8 = '=8-o';
-	$emoticon_img8  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_eek.gif" alt="'.get_lang('Amazing').'" title="'.get_lang('Amazing').'" />';
-	$emoticon_text9 = ':-|)';
-	$emoticon_img9  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_neutral.gif" alt="'.get_lang('Neutral').'" title="'.get_lang('Neutral').'" />';
-	$emoticon_text8 = ':-k';
-	$emoticon_img8  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_think.gif" alt="'.get_lang('Think').'" title="'.get_lang('Think').'" />';
-	$emoticon_text11 = ':-?';
-	$emoticon_img11  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_confused.gif" alt="'.get_lang('Confused').'" title="'.get_lang('Confused').'" />';
-	$emoticon_text12 = ':-8';
-	$emoticon_img12  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_redface.gif" alt="'.get_lang('Redface').'" title="'.get_lang('Redface').'" />';
-	$emoticon_text13 = ':- = ';
-	$emoticon_img13  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_shhh.gif" alt="'.get_lang('Silence').'" title="'.get_lang('Silence').'" />';
-	$emoticon_text14 = ':-#)';
-	$emoticon_img14  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_silenced.gif" alt="'.get_lang('Silenced').'" title="'.get_lang('Silenced').'" />';
-	$emoticon_text15 = ':-(';
-	$emoticon_img15  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_sad.gif" alt="'.get_lang('Sad').'" title="'.get_lang('Sad').'" />';
-	$emoticon_text16 = ':-[8';
-	$emoticon_img16  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_angry.gif" alt="'.get_lang('Angry').'" title="'.get_lang('Angry').'" />';
-	$emoticon_text17 = '--)';
-	$emoticon_img17  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_arrow.gif" alt="'.get_lang('Arrow').'" title="'.get_lang('Arrow').'" />';
-	$emoticon_text18 = ':!:';
-	$emoticon_img18  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_exclaim.gif" alt="'.get_lang('Exclamation').'" title="'.get_lang('Exclamation').'" />';
-	$emoticon_text19 = ':?:';
-	$emoticon_img19  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_question.gif" alt="'.get_lang('Question').'" title="'.get_lang('Question').'" />';
-	$emoticon_text20 = '0-';
-	$emoticon_img20  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_idea.gif" alt="'.get_lang('Idea').'" title="'.get_lang('Idea').'" />';
-  //
-	$emoticon_text201 = '*';
-	$emoticon_img201  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/waiting.gif" alt="'.get_lang('AskPermissionSpeak').'" title="'.get_lang('AskPermissionSpeak').'" />';
-	$emoticon_text202 = ':speak:';
-	$emoticon_img202  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_green_small.gif" alt="'.get_lang('GiveTheFloorTo').'" title="'.get_lang('GiveTheFloorTo').'" />';
-	$emoticon_text203 = ':pause:';
-	$emoticon_img203  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_yellow_small.gif" alt="'.get_lang('Pause').'" title="'.get_lang('Pause').'" />';
-	$emoticon_text204 = ':stop:';
-	$emoticon_img204  = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_red_small.gif" alt="'.get_lang('Stop').'" title="'.get_lang('Stop').'" />';
-
-	if ($sent) {
-		$message = trim(htmlspecialchars(stripslashes($_POST['message']), ENT_QUOTES, $charset));
-		$message = str_replace($emoticon_text1, $emoticon_img1, $message);
-		$message = str_replace($emoticon_text2, $emoticon_img2, $message);
-		$message = str_replace($emoticon_text3, $emoticon_img3, $message);
-		$message = str_replace($emoticon_text4, $emoticon_img4, $message);
-		$message = str_replace($emoticon_text5, $emoticon_img5, $message);
-		$message = str_replace($emoticon_text6, $emoticon_img6, $message);
-		$message = str_replace($emoticon_text7, $emoticon_img7, $message);
-		$message = str_replace($emoticon_text8, $emoticon_img8, $message);
-		$message = str_replace($emoticon_text9, $emoticon_img9, $message);
-		$message = str_replace($emoticon_text10, $emoticon_img10, $message);
-		$message = str_replace($emoticon_text11, $emoticon_img11, $message);
-		$message = str_replace($emoticon_text12, $emoticon_img12, $message);
-		$message = str_replace($emoticon_text13, $emoticon_img13, $message);
-		$message = str_replace($emoticon_text14, $emoticon_img14, $message);
-		$message = str_replace($emoticon_text15, $emoticon_img15, $message);
-		$message = str_replace($emoticon_text16, $emoticon_img16, $message);
-		$message = str_replace($emoticon_text17, $emoticon_img17, $message);
-		$message = str_replace($emoticon_text18, $emoticon_img18, $message);
- 		$message = str_replace($emoticon_text19, $emoticon_img19, $message);
-		$message = str_replace($emoticon_text20, $emoticon_img20, $message);
-		//
-		$message = str_replace($emoticon_text201, $emoticon_img201, $message);
-		$message = str_replace($emoticon_text202, $emoticon_img202, $message);
-		$message = str_replace($emoticon_text203, $emoticon_img203, $message);
-		$message = str_replace($emoticon_text204, $emoticon_img204, $message);
-
-		$timeNow = date('d/m/y H:i:s');
-
-		$basename_chat = '';
-		if (!empty($group_id)) {
-			$basename_chat = 'messages-'.$date_now.'_gid-'.$group_id;
-		} elseif (!empty($session_id)) {
-			$basename_chat = 'messages-'.$date_now.'_sid-'.$session_id;
-		} else {
-			$basename_chat = 'messages-'.$date_now;
-		}
-
-		if (!api_is_anonymous()) {
-			if (!empty($message)) {
-				$message = make_clickable($message);
-
-				if (!file_exists($chat_path.$basename_chat.'.log.html')) {
-					$doc_id = add_document($_course, $basepath_chat.'/'.$basename_chat.'.log.html', 'file', 0, $basename_chat.'.log.html');
-
-					api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $group_id, null, null, null, $session_id);
-					api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], $group_id, null, null, null, $session_id);
-					item_property_update_on_folder($_course, $basepath_chat, $_user['user_id']);
-				} else {
-					$doc_id = DocumentManager::get_document_id($_course, $basepath_chat.'/'.$basename_chat.'.log.html');
-				}
-
-				$fp = fopen($chat_path.$basename_chat.'.log.html', 'a');
-
-				if ($isMaster) {
-					$photo = '<img src="'.api_get_path(WEB_IMG_PATH).'teachers.gif" alt="'.get_lang('Teacher').'"  width="11" height="11" align="top"  title="'.get_lang('Teacher').'"  />';
-					fputs($fp, '<span style="color:#999; font-size: smaller;">['.$timeNow.']</span>'.$photo.' <span id="chat_login_name"><b>'.api_get_person_name($firstname, $lastname).'</b></span> : <i>'.$message.'</i><br />'."\n");
-				} else {
-					$photo = '<img src="'.api_get_path(WEB_IMG_PATH).'students.gif" alt="'.get_lang('Student').'"  width="11" height="11" align="top"  title="'.get_lang('Student').'"  />';
-					fputs($fp, '<span style="color:#999; font-size: smaller;">['.$timeNow.']</span>'.$photo.' <b>'.api_get_person_name($firstname, $lastname).'</b> : <i>'.$message.'</i><br />'."\n");
-				}
-
-				fclose($fp);
-
-				$chat_size = filesize($chat_path.$basename_chat.'.log.html');
-
-				update_existing_document($_course, $doc_id, $chat_size);
-				item_property_update_on_folder($_course, $basepath_chat, $_user['user_id']);
-			}
-		}
-	}
-	?>
-	<form name="formMessage" method="post" action="<?php echo api_get_self().'?'.api_get_cidreq(); ?>" onsubmit="javascript: if(document.formMessage.message.value == '') { alert('<?php echo addslashes(api_htmlentities(get_lang('TypeMessage'), ENT_QUOTES)); ?>'); document.formMessage.message.focus(); return false; }" autocomplete="off">
-	<input type="hidden" name="sent" value="1">
-	<table border="0" cellpadding="5" cellspacing="0" width="100%">
-	<tr>
-        <td width="320" valign="middle">
-		<?php $talkboxsize=(api_get_course_setting('allow_open_chat_window')) ? 'width: 350px; height: 35px' : 'width: 450px; height: 35px'; ?>
-        <textarea name="message" style=" <?php echo $talkboxsize; ?>" onkeydown="send_message(event);" onclick="javascript: insert_smile(this);"></textarea>
-        </td>
-        <td>
-            <button type="submit" value="<?php echo get_lang('Send'); ?>" class="background_submit"><?php echo get_lang('Send'); ?></button>
-        </td>
-	</tr>
-    <tr>
-        <td>
-        <?php
-		echo  "<a href=\"javascript:insert('".$emoticon_text1."')\">".$emoticon_img1."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text2."')\">".$emoticon_img2."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text3."')\">".$emoticon_img3."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text4."')\">".$emoticon_img4."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text5."')\">".$emoticon_img5."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text6."')\">".$emoticon_img6."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text7."')\">".$emoticon_img7."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text8."')\">".$emoticon_img8."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text9."')\">".$emoticon_img9."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text10."')\">".$emoticon_img10."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text11."')\">".$emoticon_img11."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text12."')\">".$emoticon_img12."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text13."')\">".$emoticon_img13."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text14."')\">".$emoticon_img14."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text15."')\">".$emoticon_img15."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text16."')\">".$emoticon_img16."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text17."')\">".$emoticon_img17."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text18."')\">".$emoticon_img18."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text19."')\">".$emoticon_img19."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text20."')\">".$emoticon_img20."</a>";
-		?>
-        </td>
-        <td>
-        <?php
-		echo  "<a href=\"javascript:insert('".$emoticon_text201."')\">".$emoticon_img201."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text202."')\">".$emoticon_img202."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text203."')\">".$emoticon_img203."</a>";
-		echo  "<a href=\"javascript:insert('".$emoticon_text204."')\">".$emoticon_img204."</a>";
-		?>
-        </td>
-    </tr>
-	</table>
-    </form>
+                Database::query($sql);
+            }
+        }
+    }
+
+    require 'header_frame.inc.php';
+    $chat_size = 0;
+
+    // Define emoticons
+    $emoticon_text1 = ':-)';
+    $emoticon_img1 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_smile.gif" alt="'.get_lang(
+        'Smile'
+    ).'" title="'.get_lang('Smile').'" />';
+    $emoticon_text2 = ':-D';
+    $emoticon_img2 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_biggrin.gif" alt="'.get_lang(
+        'BigGrin'
+    ).'" title="'.get_lang('BigGrin').'" />';
+    $emoticon_text3 = ';-)';
+    $emoticon_img3 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_wink.gif" alt="'.get_lang(
+        'Wink'
+    ).'" title="'.get_lang('Wink').'" />';
+    $emoticon_text4 = ':-P';
+    $emoticon_img4 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_razz.gif" alt="'.get_lang(
+        'Avid'
+    ).'" title="'.get_lang('Avid').'" />';
+    $emoticon_text5 = '8-)';
+    $emoticon_img5 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_cool.gif" alt="'.get_lang(
+        'Cool'
+    ).'" title="'.get_lang('Cool').'" />';
+    $emoticon_text6 = ':-o)';
+    $emoticon_img6 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_surprised.gif" alt="'.get_lang(
+        'Surprised'
+    ).'" title="'.get_lang('Surprised').'" />';
+    $emoticon_text7 = '=;';
+    $emoticon_img7 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_hand.gif" alt="'.get_lang(
+        'Hand'
+    ).'" title="'.get_lang('Hand').'" />';
+    $emoticon_text8 = '=8-o';
+    $emoticon_img8 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_eek.gif" alt="'.get_lang(
+        'Amazing'
+    ).'" title="'.get_lang('Amazing').'" />';
+    $emoticon_text9 = ':-|)';
+    $emoticon_img9 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_neutral.gif" alt="'.get_lang(
+        'Neutral'
+    ).'" title="'.get_lang('Neutral').'" />';
+    $emoticon_text8 = ':-k';
+    $emoticon_img8 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_think.gif" alt="'.get_lang(
+        'Think'
+    ).'" title="'.get_lang('Think').'" />';
+    $emoticon_text11 = ':-?';
+    $emoticon_img11 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_confused.gif" alt="'.get_lang(
+        'Confused'
+    ).'" title="'.get_lang('Confused').'" />';
+    $emoticon_text12 = ':-8';
+    $emoticon_img12 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_redface.gif" alt="'.get_lang(
+        'Redface'
+    ).'" title="'.get_lang('Redface').'" />';
+    $emoticon_text13 = ':- = ';
+    $emoticon_img13 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_shhh.gif" alt="'.get_lang(
+        'Silence'
+    ).'" title="'.get_lang('Silence').'" />';
+    $emoticon_text14 = ':-#)';
+    $emoticon_img14 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_silenced.gif" alt="'.get_lang(
+        'Silenced'
+    ).'" title="'.get_lang('Silenced').'" />';
+    $emoticon_text15 = ':-(';
+    $emoticon_img15 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_sad.gif" alt="'.get_lang(
+        'Sad'
+    ).'" title="'.get_lang('Sad').'" />';
+    $emoticon_text16 = ':-[8';
+    $emoticon_img16 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_angry.gif" alt="'.get_lang(
+        'Angry'
+    ).'" title="'.get_lang('Angry').'" />';
+    $emoticon_text17 = '--)';
+    $emoticon_img17 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_arrow.gif" alt="'.get_lang(
+        'Arrow'
+    ).'" title="'.get_lang('Arrow').'" />';
+    $emoticon_text18 = ':!:';
+    $emoticon_img18 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_exclaim.gif" alt="'.get_lang(
+        'Exclamation'
+    ).'" title="'.get_lang('Exclamation').'" />';
+    $emoticon_text19 = ':?:';
+    $emoticon_img19 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_question.gif" alt="'.get_lang(
+        'Question'
+    ).'" title="'.get_lang('Question').'" />';
+    $emoticon_text20 = '0-';
+    $emoticon_img20 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/icon_idea.gif" alt="'.get_lang(
+        'Idea'
+    ).'" title="'.get_lang('Idea').'" />';
+    //
+    $emoticon_text201 = '*';
+    $emoticon_img201 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/waiting.gif" alt="'.get_lang(
+        'AskPermissionSpeak'
+    ).'" title="'.get_lang('AskPermissionSpeak').'" />';
+    $emoticon_text202 = ':speak:';
+    $emoticon_img202 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_green_small.gif" alt="'.get_lang(
+        'GiveTheFloorTo'
+    ).'" title="'.get_lang('GiveTheFloorTo').'" />';
+    $emoticon_text203 = ':pause:';
+    $emoticon_img203 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_yellow_small.gif" alt="'.get_lang(
+        'Pause'
+    ).'" title="'.get_lang('Pause').'" />';
+    $emoticon_text204 = ':stop:';
+    $emoticon_img204 = '<img src="'.api_get_path(WEB_IMG_PATH).'smileys/flag_red_small.gif" alt="'.get_lang(
+        'Stop'
+    ).'" title="'.get_lang('Stop').'" />';
+
+    if ($sent) {
+        $message = trim(htmlspecialchars(stripslashes($_POST['message']), ENT_QUOTES, $charset));
+        $message = str_replace($emoticon_text1, $emoticon_img1, $message);
+        $message = str_replace($emoticon_text2, $emoticon_img2, $message);
+        $message = str_replace($emoticon_text3, $emoticon_img3, $message);
+        $message = str_replace($emoticon_text4, $emoticon_img4, $message);
+        $message = str_replace($emoticon_text5, $emoticon_img5, $message);
+        $message = str_replace($emoticon_text6, $emoticon_img6, $message);
+        $message = str_replace($emoticon_text7, $emoticon_img7, $message);
+        $message = str_replace($emoticon_text8, $emoticon_img8, $message);
+        $message = str_replace($emoticon_text9, $emoticon_img9, $message);
+        $message = str_replace($emoticon_text10, $emoticon_img10, $message);
+        $message = str_replace($emoticon_text11, $emoticon_img11, $message);
+        $message = str_replace($emoticon_text12, $emoticon_img12, $message);
+        $message = str_replace($emoticon_text13, $emoticon_img13, $message);
+        $message = str_replace($emoticon_text14, $emoticon_img14, $message);
+        $message = str_replace($emoticon_text15, $emoticon_img15, $message);
+        $message = str_replace($emoticon_text16, $emoticon_img16, $message);
+        $message = str_replace($emoticon_text17, $emoticon_img17, $message);
+        $message = str_replace($emoticon_text18, $emoticon_img18, $message);
+        $message = str_replace($emoticon_text19, $emoticon_img19, $message);
+        $message = str_replace($emoticon_text20, $emoticon_img20, $message);
+        //
+        $message = str_replace($emoticon_text201, $emoticon_img201, $message);
+        $message = str_replace($emoticon_text202, $emoticon_img202, $message);
+        $message = str_replace($emoticon_text203, $emoticon_img203, $message);
+        $message = str_replace($emoticon_text204, $emoticon_img204, $message);
+
+        $timeNow = date('d/m/y H:i:s');
+
+        $basename_chat = '';
+        if (!empty($group_id)) {
+            $basename_chat = 'messages-'.$date_now.'_gid-'.$group_id;
+        } elseif (!empty($session_id)) {
+            $basename_chat = 'messages-'.$date_now.'_sid-'.$session_id;
+        } else {
+            $basename_chat = 'messages-'.$date_now;
+        }
+
+        if (!api_is_anonymous()) {
+            if (!empty($message)) {
+                $message = make_clickable($message);
+
+                if (!file_exists($chat_path.$basename_chat.'.log.html')) {
+                    $doc_id = FileManager::add_document(
+                        $_course,
+                        $basepath_chat.'/'.$basename_chat.'.log.html',
+                        'file',
+                        0,
+                        $basename_chat.'.log.html'
+                    );
+
+                    api_item_property_update(
+                        $_course,
+                        TOOL_DOCUMENT,
+                        $doc_id,
+                        'DocumentAdded',
+                        $_user['user_id'],
+                        $group_id,
+                        null,
+                        null,
+                        null,
+                        $session_id
+                    );
+                    api_item_property_update(
+                        $_course,
+                        TOOL_DOCUMENT,
+                        $doc_id,
+                        'invisible',
+                        $_user['user_id'],
+                        $group_id,
+                        null,
+                        null,
+                        null,
+                        $session_id
+                    );
+                    FileManager::item_property_update_on_folder($_course, $basepath_chat, $_user['user_id']);
+                } else {
+                    $doc_id = DocumentManager::get_document_id($_course, $basepath_chat.'/'.$basename_chat.'.log.html');
+                }
+
+                $fp = fopen($chat_path.$basename_chat.'.log.html', 'a');
+
+                if ($isMaster) {
+                    $photo = '<img src="'.api_get_path(WEB_IMG_PATH).'teachers.gif" alt="'.get_lang(
+                        'Teacher'
+                    ).'"  width="11" height="11" align="top"  title="'.get_lang('Teacher').'"  />';
+                    fputs(
+                        $fp,
+                        '<span style="color:#999; font-size: smaller;">['.$timeNow.']</span>'.$photo.' <span id="chat_login_name"><b>'.api_get_person_name(
+                            $firstname,
+                            $lastname
+                        ).'</b></span> : <i>'.$message.'</i><br />'."\n"
+                    );
+                } else {
+                    $photo = '<img src="'.api_get_path(WEB_IMG_PATH).'students.gif" alt="'.get_lang(
+                        'Student'
+                    ).'"  width="11" height="11" align="top"  title="'.get_lang('Student').'"  />';
+                    fputs(
+                        $fp,
+                        '<span style="color:#999; font-size: smaller;">['.$timeNow.']</span>'.$photo.' <b>'.api_get_person_name(
+                            $firstname,
+                            $lastname
+                        ).'</b> : <i>'.$message.'</i><br />'."\n"
+                    );
+                }
+
+                fclose($fp);
+
+                $chat_size = filesize($chat_path.$basename_chat.'.log.html');
+
+                FileManager::update_existing_document($_course, $doc_id, $chat_size);
+                FileManager::item_property_update_on_folder($_course, $basepath_chat, $_user['user_id']);
+            }
+        }
+    }
+    ?>
+<form name="formMessage" method="post" action="<?php echo api_get_self().'?'.api_get_cidreq(); ?>"
+      onsubmit="javascript: if(document.formMessage.message.value == '') { alert('<?php echo addslashes(
+          api_htmlentities(get_lang('TypeMessage'), ENT_QUOTES)
+      ); ?>'); document.formMessage.message.focus(); return false; }" autocomplete="off">
+    <input type="hidden" name="sent" value="1">
+    <table border="0" cellpadding="5" cellspacing="0" width="100%">
+        <tr>
+            <td width="320" valign="middle">
+                <?php $talkboxsize = (api_get_course_setting(
+                'allow_open_chat_window'
+            )) ? 'width: 350px; height: 35px' : 'width: 450px; height: 35px'; ?>
+                <textarea name="message" style=" <?php echo $talkboxsize; ?>" onkeydown="send_message(event);"
+                          onclick="javascript: insert_smile(this);"></textarea>
+            </td>
+            <td>
+                <button type="submit" value="<?php echo get_lang('Send'); ?>"
+                        class="background_submit"><?php echo get_lang('Send'); ?></button>
+            </td>
+        </tr>
+        <tr>
+            <td>
+                <?php
+                echo  "<a href=\"javascript:insert('".$emoticon_text1."')\">".$emoticon_img1."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text2."')\">".$emoticon_img2."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text3."')\">".$emoticon_img3."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text4."')\">".$emoticon_img4."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text5."')\">".$emoticon_img5."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text6."')\">".$emoticon_img6."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text7."')\">".$emoticon_img7."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text8."')\">".$emoticon_img8."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text9."')\">".$emoticon_img9."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text10."')\">".$emoticon_img10."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text11."')\">".$emoticon_img11."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text12."')\">".$emoticon_img12."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text13."')\">".$emoticon_img13."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text14."')\">".$emoticon_img14."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text15."')\">".$emoticon_img15."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text16."')\">".$emoticon_img16."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text17."')\">".$emoticon_img17."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text18."')\">".$emoticon_img18."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text19."')\">".$emoticon_img19."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text20."')\">".$emoticon_img20."</a>";
+                ?>
+            </td>
+            <td>
+                <?php
+                echo  "<a href=\"javascript:insert('".$emoticon_text201."')\">".$emoticon_img201."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text202."')\">".$emoticon_img202."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text203."')\">".$emoticon_img203."</a>";
+                echo  "<a href=\"javascript:insert('".$emoticon_text204."')\">".$emoticon_img204."</a>";
+                ?>
+            </td>
+        </tr>
+    </table>
+</form>
 <?php
 }
 require 'footer_frame.inc.php';

+ 245 - 194
main/conference/api.php

@@ -5,29 +5,29 @@
 session_cache_limiter("none");
 
 /**
-*	This is an interface between Chamilo and Videoconference application
-*
+ *    This is an interface between Chamilo and Videoconference application
+ *
 
-*/
+ */
 /*==== DEBUG ====*/
-$debug=0;
+$debug = 0;
 /*==== CONSTANTS ==== */
 define('VIDEOCONF_UPLOAD_PATH', '/videoconf');
 $presentation_extension = array('.ppt', '.odp');
-$image_extension = array ('.png', '.jpg', '.gif', '.jpeg');
+$image_extension = array('.png', '.jpg', '.gif', '.jpeg');
 
-if ($debug>0)
-{
-	// dump the request
-	$v = array_keys(get_defined_vars());
-	error_log(var_export($v, true),3, '/tmp/log');
+if ($debug > 0) {
+    // dump the request
+    $v = array_keys(get_defined_vars());
+    error_log(var_export($v, true), 3, '/tmp/log');
 
-	foreach (array_keys(get_defined_vars()) as $k) {
-		if ($k == 'GLOBALS')
-			continue;
-		error_log($k, 3, '/tmp/log');
-		error_log(var_export($$k, true), 3, '/tmp/log');
-	}
+    foreach (array_keys(get_defined_vars()) as $k) {
+        if ($k == 'GLOBALS') {
+            continue;
+        }
+        error_log($k, 3, '/tmp/log');
+        error_log(var_export($$k, true), 3, '/tmp/log');
+    }
 
 }
 
@@ -43,33 +43,33 @@ if ($_SERVER['HTTP_USER_AGENT'] == 'Shockwave Flash') {
 /*==== INCLUDE ====*/
 require_once '../inc/global.inc.php';
 api_block_anonymous_users();
-require_once (api_get_path(LIBRARY_PATH)."course.lib.php");
 require_once (api_get_path(LIBRARY_PATH)."document.lib.php");
-require_once (api_get_path(LIBRARY_PATH)."fileUpload.lib.php");
+
 require_once ("../newscorm/learnpath.class.php");
 require_once ("../newscorm/openoffice_presentation.class.php");
 
 /*==== Variables initialisation ====*/
 $action = $_REQUEST["action"]; //safe as only used in if()'s
-$seek = array('/','%2F','..');
-$destroy = array('','','');
-$cidReq = str_replace($seek,$destroy,$_REQUEST["cidReq"]);
+$seek = array('/', '%2F', '..');
+$destroy = array('', '', '');
+$cidReq = str_replace($seek, $destroy, $_REQUEST["cidReq"]);
 $cidReq = Security::remove_XSS($cidReq);
 
 $user_id = api_get_user_id();
 $coursePath = api_get_path(SYS_COURSE_PATH).$cidReq.'/document';
 $_course = CourseManager::get_course_information($cidReq);
 $_course['path'] = $_course['directory'];
-// FIXME: add_document needs this to work
+// FIXME: FileManager::add_document needs this to work
 $_course['dbName'] = $_course['db_name'];
 
 // FIXME: check if CourseManager::get_user_in_course_status return !=
 //	COURSEMANAGER when the code is not valid
-if ($debug>0) error_log($coursePath, 0);
+if ($debug > 0) {
+    error_log($coursePath, 0);
+}
 
-if ($action == "uploadgui")
-{
-	echo '<form enctype="multipart/form-data" action="api.php" method="POST">
+if ($action == "uploadgui") {
+    echo '<form enctype="multipart/form-data" action="api.php" method="POST">
 	<input type="hidden" name="MAX_FILE_SIZE" value="100000000" />
 	<input type="hidden" name="action" value="upload" />
 	<input type="hidden" name="cidReq" value="'.$cidReq.'" />
@@ -79,173 +79,224 @@ if ($action == "uploadgui")
 	<input type="submit" value="'.get_lang('UploadFile').'"  />
 	</form>
 	';
-	die();
-}
-else if ($action == "upload")
-{
-	if ($debug >0) error_log("upload".$_FILES['Filedata']);
-	/*==== PERMISSION ====*/
-	$permissions = CourseManager::get_user_in_course_status($user_id, $cidReq);
-	if ($permissions != COURSEMANAGER)
-	{
-		if ($debug >0) error_log("Upload from videoconf not allowed !!!",0);
-		die('Not allowed'); // this user is not allowed to add upload documents
-	}
-	/*==== UPLOAD ====*/
-	$destPath = $coursePath.VIDEOCONF_UPLOAD_PATH;
-
-	/*==== creation of /videoconf ====*/
-	if (!is_dir($destPath))
-	{
-		$result = create_unexisting_directory($_course,$user_id, api_get_session_id(), 0,NULL,$coursePath,VIDEOCONF_UPLOAD_PATH);
-		if (!$result)
-		{
-			if ($debug>0) error_log("Can't create ".$destPath." folder",0);
-		}
-	}
-
-	/*==== file upload ====*/
-	$newPath = $_FILES['Filedata']['name'];
-	if($debug>0) error_log($newPath);
-
-	/*==== extension extraction ====*/
-	$file_name = (strrpos($newPath,'.')>0 ? substr($newPath, 0, strrpos($newPath,'.')) : $newPath);
- 	$file_extension = (strrpos($newPath,'.')>0 ? substr($newPath, strrpos($newPath,'.'),10) : '');
-	if($debug>0) error_log(strrpos($newPath,'.'));
-	if($debug>0) error_log($file_extension);
-
-	/*==== conversion if needed ====*/
-	if (!in_array(strtolower($file_extension), $image_extension))
-	{
-		if($debug>0) error_log("converting: ".$file_extension);
-		$take_slide_name = false;
-		$o_ppt = new OpenofficePresentation($take_slide_name);
-		$o_ppt -> set_slide_size(640,480);
-		$o_ppt -> convert_document($_FILES['Filedata'],'add_docs_to_visio');
-	}
-
-	echo '<html><body><script language="javascript">setTimeout(1000,window.close());</script></body></html>';
-}
-else if ($action == "service")
-{
-	/*==== List files ====*/
-	if ($debug>0) error_log("sending file list",0);
-	$subaction = $_REQUEST["subaction"];
-	$is_manager = (CourseManager::get_user_in_course_status($user_id, $cidReq) == COURSEMANAGER);
-	if ($subaction == "list")
-	{
-		// FIXME: check security around $_REQUEST["cwd"]
-		$cwd = $_REQUEST["cwd"];
-
-
-		// treat /..
-		$nParent = 0; // the number of /.. into the url
-		while (substr($cwd, -3, 3) == "/..")
-		{
-			// go to parent directory
-			$cwd= substr($cwd, 0, -3);
-			if (strlen($cwd) == 0) $cwd="/";
-			$nParent++;
-		}
-		for (;$nParent >0; $nParent--){
-			$cwd = (strrpos($cwd,'/')>-1 ? substr($cwd, 0, strrpos($cwd,'/')) : $cwd);
-		}
-
-		if (strlen($cwd) == 0) $cwd="/";
-
-		if (Security::check_abs_path($cwd,api_get_path(SYS_PATH)))
-			die();
-
-		// check if user can delete files. He must be manager and be inside /videoconf
-		$is_below_videoconf_dir = (substr($cwd,0,strlen(VIDEOCONF_UPLOAD_PATH)) == VIDEOCONF_UPLOAD_PATH);
-		if($debug>0) error_log('Current working directory: '.$cwd);
-		if($debug>0) error_log('Videoconf upload path: '.VIDEOCONF_UPLOAD_PATH);
-		/* $canDelete = ($canDelete && $isBellowVideoConfUploadPath);
-		*/
-		$can_delete = ($is_manager && $is_below_videoconf_dir);
-
-		// get files list
-		$files = DocumentManager::get_all_document_data($_course, $cwd, 0, NULL, false);
-		printf("<dokeosobject><fileListMeta></fileListMeta><fileList>");
-		printf("<folders>");
-
-		// title filter
-		if (is_array($files)) foreach (array_keys($files) as $k)
-		{
-			// converting to UTF-8
-			$files[$k]['title'] = api_convert_encoding(
-						api_strlen($files[$k]['title']) > 32 ?
-							api_substr($files[$k]['title'],0, 32)."..." :
-							$files[$k]['title'],
-						'utf-8',api_get_system_encoding());
-			// removing '<', '>' and '_'
-			$files[$k]['title'] = str_replace(array('<','>','_'),' ', $files[$k]['title']);
-		}
-
-		if(is_array($files))
-		{
-
-			foreach($files as $i)
-			{
-				if ($i["filetype"] == "folder")
-					printf('<folder><path>%s</path><title>%s</title><canDelete>%s</canDelete></folder>', $i['path'],$i['title'],($can_delete?'true':'false'));
-			}
-		}
-		printf("</folders><files>");
-		if(is_array($files))
-		{
-			foreach($files as $i) {
-	  			$extension = (strrpos($i['path'],'.')>0 ? substr($i['path'], strrpos($i['path'],'.'),10) : '');
-				if ($i["filetype"] == "file" && in_array(strtolower($extension), $image_extension))
-					printf('<file><path>%s</path><title>%s</title><canDelete>%s</canDelete></file>', $i['path'],$i['title'],($can_delete?'true':'false'));
-			}
-		}
-		printf("</files><ppts>");
-		printf("</ppts>");
-		printf("</fileList></dokeosobject>");
-	}
-	else if ($subaction == "delete")
-	{
-		/*==== PERMISSION ====*/
-		$permissions = CourseManager::get_user_in_course_status($user_id, $cidReq);
-		if ($permissions != COURSEMANAGER)
-		{
-			if ($debug > 0) error_log("Upload from videoconf not allowed !!!",0);
-			die(); // this user is not allowed to add upload documents
-		}
-		/*==== DELETE ====*/
-		$path = str_replace('../','',$_REQUEST["path"]);
-		if ((substr($path,0,strlen(VIDEOCONF_UPLOAD_PATH)) != VIDEOCONF_UPLOAD_PATH))
-		{
-			if ($debug >0 ) error_log("Delete from videoconf for "+$path+" NOT ALLOWED",0);
-			die();
-		}
-		DocumentManager::delete_document($_course, $path, $coursePath);
-		echo "<result>OK</result>"; // We have to return something to OpenLaszlo
-	}
-} else if ($action == "download") {
-	/*==== DOWNLOAD ====*/
-	//check if the document is in the database
-	if(!DocumentManager::get_document_id($_course,$_REQUEST['file'])) {
-		//file not found!
-		if ($debug>0) error_log("404 ".$_REQUEST["file"]);
-		header("HTTP/1.0 404 Not Found");
-		$error404 = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">';
-		$error404 .= '<html><head>';
-		$error404 .= '<title>404 Not Found</title>';
-		$error404 .= '</head><body>';
-		$error404 .= '<h1>Not Found</h1>';
-		$error404 .= '<p>The requested URL was not found on this server.</p>';
-		$error404 .= '<hr>';
-		$error404 .= '</body></html>';
-		echo($error404);
-		exit;
-	}
-	$doc_url = str_replace('../','',$_REQUEST['file']);
-	if ($debug >0) error_log($doc_url);
-	$full_file_name = $coursePath.$doc_url;
-    if (Security::check_abs_path($full_file_name, $coursePath.'/')) {
-	   DocumentManager::file_send_for_download($full_file_name,false);
+    die();
+} else {
+    if ($action == "upload") {
+        if ($debug > 0) {
+            error_log("upload".$_FILES['Filedata']);
+        }
+        /*==== PERMISSION ====*/
+        $permissions = CourseManager::get_user_in_course_status($user_id, $cidReq);
+        if ($permissions != COURSEMANAGER) {
+            if ($debug > 0) {
+                error_log("Upload from videoconf not allowed !!!", 0);
+            }
+            die('Not allowed'); // this user is not allowed to add upload documents
+        }
+        /*==== UPLOAD ====*/
+        $destPath = $coursePath.VIDEOCONF_UPLOAD_PATH;
+
+        /*==== creation of /videoconf ====*/
+        if (!is_dir($destPath)) {
+            $result = FileManager::create_unexisting_directory(
+                $_course,
+                $user_id,
+                api_get_session_id(),
+                0,
+                null,
+                $coursePath,
+                VIDEOCONF_UPLOAD_PATH
+            );
+            if (!$result) {
+                if ($debug > 0) {
+                    error_log("Can't create ".$destPath." folder", 0);
+                }
+            }
+        }
+
+        /*==== file upload ====*/
+        $newPath = $_FILES['Filedata']['name'];
+        if ($debug > 0) {
+            error_log($newPath);
+        }
+
+        /*==== extension extraction ====*/
+        $file_name = (strrpos($newPath, '.') > 0 ? substr($newPath, 0, strrpos($newPath, '.')) : $newPath);
+        $file_extension = (strrpos($newPath, '.') > 0 ? substr($newPath, strrpos($newPath, '.'), 10) : '');
+        if ($debug > 0) {
+            error_log(strrpos($newPath, '.'));
+        }
+        if ($debug > 0) {
+            error_log($file_extension);
+        }
+
+        /*==== conversion if needed ====*/
+        if (!in_array(strtolower($file_extension), $image_extension)) {
+            if ($debug > 0) {
+                error_log("converting: ".$file_extension);
+            }
+            $take_slide_name = false;
+            $o_ppt = new OpenofficePresentation($take_slide_name);
+            $o_ppt->set_slide_size(640, 480);
+            $o_ppt->convert_document($_FILES['Filedata'], 'add_docs_to_visio');
+        }
+
+        echo '<html><body><script language="javascript">setTimeout(1000,window.close());</script></body></html>';
+    } else {
+        if ($action == "service") {
+            /*==== List files ====*/
+            if ($debug > 0) {
+                error_log("sending file list", 0);
+            }
+            $subaction = $_REQUEST["subaction"];
+            $is_manager = (CourseManager::get_user_in_course_status($user_id, $cidReq) == COURSEMANAGER);
+            if ($subaction == "list") {
+                // FIXME: check security around $_REQUEST["cwd"]
+                $cwd = $_REQUEST["cwd"];
+
+
+                // treat /..
+                $nParent = 0; // the number of /.. into the url
+                while (substr($cwd, -3, 3) == "/..") {
+                    // go to parent directory
+                    $cwd = substr($cwd, 0, -3);
+                    if (strlen($cwd) == 0) {
+                        $cwd = "/";
+                    }
+                    $nParent++;
+                }
+                for (; $nParent > 0; $nParent--) {
+                    $cwd = (strrpos($cwd, '/') > -1 ? substr($cwd, 0, strrpos($cwd, '/')) : $cwd);
+                }
+
+                if (strlen($cwd) == 0) {
+                    $cwd = "/";
+                }
+
+                if (Security::check_abs_path($cwd, api_get_path(SYS_PATH))) {
+                    die();
+                }
+
+                // check if user can delete files. He must be manager and be inside /videoconf
+                $is_below_videoconf_dir = (substr($cwd, 0, strlen(VIDEOCONF_UPLOAD_PATH)) == VIDEOCONF_UPLOAD_PATH);
+                if ($debug > 0) {
+                    error_log('Current working directory: '.$cwd);
+                }
+                if ($debug > 0) {
+                    error_log('Videoconf upload path: '.VIDEOCONF_UPLOAD_PATH);
+                }
+                /* $canDelete = ($canDelete && $isBellowVideoConfUploadPath);
+                */
+                $can_delete = ($is_manager && $is_below_videoconf_dir);
+
+                // get files list
+                $files = DocumentManager::get_all_document_data($_course, $cwd, 0, null, false);
+                printf("<dokeosobject><fileListMeta></fileListMeta><fileList>");
+                printf("<folders>");
+
+                // title filter
+                if (is_array($files)) {
+                    foreach (array_keys($files) as $k) {
+                        // converting to UTF-8
+                        $files[$k]['title'] = api_convert_encoding(
+                            api_strlen($files[$k]['title']) > 32 ?
+                                api_substr($files[$k]['title'], 0, 32)."..." :
+                                $files[$k]['title'],
+                            'utf-8',
+                            api_get_system_encoding()
+                        );
+                        // removing '<', '>' and '_'
+                        $files[$k]['title'] = str_replace(array('<', '>', '_'), ' ', $files[$k]['title']);
+                    }
+                }
+
+                if (is_array($files)) {
+
+                    foreach ($files as $i) {
+                        if ($i["filetype"] == "folder") {
+                            printf(
+                                '<folder><path>%s</path><title>%s</title><canDelete>%s</canDelete></folder>',
+                                $i['path'],
+                                $i['title'],
+                                ($can_delete ? 'true' : 'false')
+                            );
+                        }
+                    }
+                }
+                printf("</folders><files>");
+                if (is_array($files)) {
+                    foreach ($files as $i) {
+                        $extension = (strrpos($i['path'], '.') > 0 ? substr(
+                            $i['path'],
+                            strrpos($i['path'], '.'),
+                            10
+                        ) : '');
+                        if ($i["filetype"] == "file" && in_array(strtolower($extension), $image_extension)) {
+                            printf(
+                                '<file><path>%s</path><title>%s</title><canDelete>%s</canDelete></file>',
+                                $i['path'],
+                                $i['title'],
+                                ($can_delete ? 'true' : 'false')
+                            );
+                        }
+                    }
+                }
+                printf("</files><ppts>");
+                printf("</ppts>");
+                printf("</fileList></dokeosobject>");
+            } else {
+                if ($subaction == "delete") {
+                    /*==== PERMISSION ====*/
+                    $permissions = CourseManager::get_user_in_course_status($user_id, $cidReq);
+                    if ($permissions != COURSEMANAGER) {
+                        if ($debug > 0) {
+                            error_log("Upload from videoconf not allowed !!!", 0);
+                        }
+                        die(); // this user is not allowed to add upload documents
+                    }
+                    /*==== DELETE ====*/
+                    $path = str_replace('../', '', $_REQUEST["path"]);
+                    if ((substr($path, 0, strlen(VIDEOCONF_UPLOAD_PATH)) != VIDEOCONF_UPLOAD_PATH)) {
+                        if ($debug > 0) {
+                            error_log("Delete from videoconf for " + $path + " NOT ALLOWED", 0);
+                        }
+                        die();
+                    }
+                    DocumentManager::delete_document($_course, $path, $coursePath);
+                    echo "<result>OK</result>"; // We have to return something to OpenLaszlo
+                }
+            }
+        } else {
+            if ($action == "download") {
+                /*==== DOWNLOAD ====*/
+                //check if the document is in the database
+                if (!DocumentManager::get_document_id($_course, $_REQUEST['file'])) {
+                    //file not found!
+                    if ($debug > 0) {
+                        error_log("404 ".$_REQUEST["file"]);
+                    }
+                    header("HTTP/1.0 404 Not Found");
+                    $error404 = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">';
+                    $error404 .= '<html><head>';
+                    $error404 .= '<title>404 Not Found</title>';
+                    $error404 .= '</head><body>';
+                    $error404 .= '<h1>Not Found</h1>';
+                    $error404 .= '<p>The requested URL was not found on this server.</p>';
+                    $error404 .= '<hr>';
+                    $error404 .= '</body></html>';
+                    echo($error404);
+                    exit;
+                }
+                $doc_url = str_replace('../', '', $_REQUEST['file']);
+                if ($debug > 0) {
+                    error_log($doc_url);
+                }
+                $full_file_name = $coursePath.$doc_url;
+                if (Security::check_abs_path($full_file_name, $coursePath.'/')) {
+                    DocumentManager::file_send_for_download($full_file_name, false);
+                }
+                exit;
+            }
+        }
     }
-	exit;
 }

+ 67 - 67
main/conference/audiopost.php

@@ -7,77 +7,77 @@
 require_once '../inc/global.inc.php';
 
 // check the request comes from our red5 server
-$ips = gethostbynamel(api_get_setting('service_visio','visio_host'));
+$ips = gethostbynamel(api_get_setting('service_visio', 'visio_host'));
 $is_our_server = false;
 
 // ignoring null file
-if ($_FILES["file"]["size"] == 0)
-	exit(0);
-
-if(is_array($ips))
-{
-	foreach($ips as $ip)
-	{
-		//get 255 range for known server address
-		$split = split('.',$ip);
-		$ip_range_server = $split[0].'.'.$split[1].'.'.$split[2];
-		//get 255 range for request source address
-		$split = split('.',$_SERVER['REMOTE_ADDR']);
-		$ip_range_request = $split[0].'.'.$split[1].'.'.$split[2];
-		if($ip_range_server == $ip_range_request){$is_our_server = true;}
-	}
+if ($_FILES["file"]["size"] == 0) {
+    exit(0);
 }
-if($is_our_server)
-{
-	if(api_get_setting('service_visio','active')=='true')
-	{
-		//check encryption key
-		$string1 = $_GET['course_code'].$_GET['user_id'].gmdate('Ymd').$_configuration['security_key'];
-		$string2 = $_GET['course_code'].$_GET['user_id'].(gmdate('Ymd')-1).$_configuration['security_key'];
-		if(md5($string1) == $_GET['checker'] or md5($string2) == $_GET['checker'])
-		{
-			$course_info = api_get_course_info($_GET['course_code']);
-			$target = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/audio/';
-			$basename = basename( $_FILES['file']['name']);
-			$target = $target . $basename ;
-			if(!move_uploaded_file($_FILES['file']['tmp_name'], $target))
-			{
-				error_log(__FILE__.':'.__LINE__.': File upload to '.$target.' failed',0);
-			}
-			else
-			{
-				require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-				$id = add_document($course_info,'/audio/'.$basename,'file',filesize($target),$basename);
-				if($id !== false)
-				{
-					$res = api_item_property_update($course_info,TOOL_DOCUMENT,$id,'DocumentAdded',$_GET['user_id']);
-					if($res === false)
-					{
-						error_log(__FILE__.':'.__LINE__.': Something went wrong with item properties update of '.$target,0);
-					}
-					else
-					{//make sound invisible?
-						//$res = api_item_property_update($course_info,TOOL_DOCUMENT,$id,'invisible',$_GET['user_id']);
-					}
-				}
-				else
-				{
-					error_log(__FILE__.':'.__LINE__.': Could not create document record for document '.$target,0);
-				}
-			}
-		}
-		else
-		{
-			error_log(__FILE__.':'.__LINE__.': Attempting to save file but hash check did not suceed (hacking attempt?)',0);
-		}
-	}
-	else
-	{
-		error_log(__FILE__.':'.__LINE__.': Attempting to save file but videoconf is not enabled',0);
-	}
+
+if (is_array($ips)) {
+    foreach ($ips as $ip) {
+        //get 255 range for known server address
+        $split = split('.', $ip);
+        $ip_range_server = $split[0].'.'.$split[1].'.'.$split[2];
+        //get 255 range for request source address
+        $split = split('.', $_SERVER['REMOTE_ADDR']);
+        $ip_range_request = $split[0].'.'.$split[1].'.'.$split[2];
+        if ($ip_range_server == $ip_range_request) {
+            $is_our_server = true;
+        }
+    }
 }
-else
-{
-	error_log(__FILE__.':'.__LINE__.': Attempting to save file but coming from unknown source',0);
+if ($is_our_server) {
+    if (api_get_setting('service_visio', 'active') == 'true') {
+        //check encryption key
+        $string1 = $_GET['course_code'].$_GET['user_id'].gmdate('Ymd').$_configuration['security_key'];
+        $string2 = $_GET['course_code'].$_GET['user_id'].(gmdate('Ymd') - 1).$_configuration['security_key'];
+        if (md5($string1) == $_GET['checker'] or md5($string2) == $_GET['checker']) {
+            $course_info = api_get_course_info($_GET['course_code']);
+            $target = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/audio/';
+            $basename = basename($_FILES['file']['name']);
+            $target = $target.$basename;
+            if (!move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
+                error_log(__FILE__.':'.__LINE__.': File upload to '.$target.' failed', 0);
+            } else {
+                $id = FileManager::add_document(
+                    $course_info,
+                    '/audio/'.$basename,
+                    'file',
+                    filesize($target),
+                    $basename
+                );
+                if ($id !== false) {
+                    $res = api_item_property_update(
+                        $course_info,
+                        TOOL_DOCUMENT,
+                        $id,
+                        'DocumentAdded',
+                        $_GET['user_id']
+                    );
+                    if ($res === false) {
+                        error_log(
+                            __FILE__.':'.__LINE__.': Something went wrong with item properties update of '.$target,
+                            0
+                        );
+                    } else { //make sound invisible?
+                        //$res = api_item_property_update($course_info,TOOL_DOCUMENT,$id,'invisible',$_GET['user_id']);
+                    }
+                } else {
+                    error_log(__FILE__.':'.__LINE__.': Could not create document record for document '.$target, 0);
+                }
+            }
+        } else {
+            error_log(
+                __FILE__.':'.__LINE__.': Attempting to save file but hash check did not suceed (hacking attempt?)',
+                0
+            );
+        }
+    } else {
+        error_log(__FILE__.':'.__LINE__.': Attempting to save file but videoconf is not enabled', 0);
+    }
+} else {
+    error_log(__FILE__.':'.__LINE__.': Attempting to save file but coming from unknown source', 0);
 }
 ?>

+ 11 - 13
main/course_info/download.php

@@ -11,14 +11,12 @@
 require_once '../inc/global.inc.php';
 $this_section = SECTION_COURSES;
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 if ($_GET['session']) {
-	$archive_path = api_get_path(SYS_ARCHIVE_PATH).'temp/';
-	$_cid = true;
-	$is_courseAdmin = true;
+    $archive_path = api_get_path(SYS_ARCHIVE_PATH).'temp/';
+    $_cid = true;
+    $is_courseAdmin = true;
 } else {
-	$archive_path = api_get_path(SYS_ARCHIVE_PATH);
+    $archive_path = api_get_path(SYS_ARCHIVE_PATH);
 }
 
 $archive_file = $_GET['archive'];
@@ -27,28 +25,28 @@ $archive_file = str_replace(array('..', '/', '\\'), '', $archive_file);
 list($extension) = getextension($archive_file);
 
 if (empty($extension) || !file_exists($archive_path.$archive_file)) {
-	exit;
+    exit;
 }
 
-$extension = strtolower($extension); 
+$extension = strtolower($extension);
 $content_type = '';
 
 if (in_array($extension, array('xml', 'csv')) && (api_is_platform_admin(true) || api_is_drh())) {
-	$content_type = 'application/force-download';
+    $content_type = 'application/force-download';
 } elseif ($extension == 'zip' && $_cid && (api_is_platform_admin(true) || $is_courseAdmin)) {
-	$content_type = 'application/force-download';
+    $content_type = 'application/force-download';
 }
 
 if (empty($content_type)) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
-if (Security::check_abs_path($archive_path.$archive_file, $archive_path)) {        
+if (Security::check_abs_path($archive_path.$archive_file, $archive_path)) {
     header('Expires: Wed, 01 Jan 1990 00:00:00 GMT');
     header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
     header('Cache-Control: public');
     header('Pragma: no-cache');
-    
+
     header('Content-Type: '.$content_type);
     header('Content-Length: '.filesize($archive_path.$archive_file));
     header('Content-Disposition: attachment; filename='.$archive_file);

Fișier diff suprimat deoarece este prea mare
+ 468 - 103
main/coursecopy/classes/CourseRestorer.class.php


+ 63 - 41
main/coursecopy/copy_course.php

@@ -11,24 +11,23 @@ $language_file = array('exercice', 'coursebackup', 'admin');
 
 // Setting the global file that gets the general configuration, the databases, the languages, ...
 require_once '../inc/global.inc.php';
-$current_course_tool  = TOOL_COURSE_MAINTENANCE;
+$current_course_tool = TOOL_COURSE_MAINTENANCE;
 api_protect_course_script(true);
 
 // Including additional libraries
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once 'classes/CourseBuilder.class.php';
 require_once 'classes/CourseRestorer.class.php';
 require_once 'classes/CourseSelectForm.class.php';
 
 // Notice for unauthorized people.
 if (!api_is_allowed_to_edit()) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 // Remove memory and time limits as much as possible as this might be a long process...
 if (function_exists('ini_set')) {
-	ini_set('memory_limit', '256M');
-	ini_set('max_execution_time', 1800);
+    ini_set('memory_limit', '256M');
+    ini_set('max_execution_time', 1800);
     //ini_set('post_max_size', "512M");
 }
 
@@ -46,46 +45,51 @@ echo Display::page_header(get_lang('CopyCourse'));
 
 // If a CourseSelectForm is posted or we should copy all resources, then copy them
 if ((isset($_POST['action']) && $_POST['action'] == 'course_select_form') || (isset($_POST['copy_option']) && $_POST['copy_option'] == 'full_copy')) {
-	if (isset($_POST['action']) && $_POST['action'] == 'course_select_form') {
-		$course = CourseSelectForm :: get_posted_course('copy_course');
-	} else {
-		$cb = new CourseBuilder();
-		$course = $cb->build();
-	}
-	$cr = new CourseRestorer($course);
-	$cr->set_file_option($_POST['same_file_name_option']);
-	$cr->restore($_POST['destination_course']);
-	Display::display_normal_message(get_lang('CopyFinished').': <a href="'.api_get_course_url($_POST['destination_course']).'">'.$_POST['destination_course'].'</a>',false);
+    if (isset($_POST['action']) && $_POST['action'] == 'course_select_form') {
+        $course = CourseSelectForm :: get_posted_course('copy_course');
+    } else {
+        $cb = new CourseBuilder();
+        $course = $cb->build();
+    }
+    $cr = new CourseRestorer($course);
+    $cr->set_file_option($_POST['same_file_name_option']);
+    $cr->restore($_POST['destination_course']);
+    Display::display_normal_message(
+        get_lang('CopyFinished').': <a href="'.api_get_course_url(
+            $_POST['destination_course']
+        ).'">'.$_POST['destination_course'].'</a>',
+        false
+    );
 } elseif (isset ($_POST['copy_option']) && $_POST['copy_option'] == 'select_items') {
-	$cb = new CourseBuilder();
-	$course = $cb->build();
+    $cb = new CourseBuilder();
+    $course = $cb->build();
 
     $hidden_fields = array();
-	$hidden_fields['same_file_name_option'] = $_POST['same_file_name_option'];
-	$hidden_fields['destination_course']    = $_POST['destination_course'];
-	CourseSelectForm :: display_form($course, $hidden_fields, true);
+    $hidden_fields['same_file_name_option'] = $_POST['same_file_name_option'];
+    $hidden_fields['destination_course'] = $_POST['destination_course'];
+    CourseSelectForm :: display_form($course, $hidden_fields, true);
 } else {
-	$table_c = Database :: get_main_table(TABLE_MAIN_COURSE);
-	$table_cu = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-	$user_info = api_get_user_info();
-	$course_info = api_get_course_info();
-	$sql = 'SELECT * FROM '.$table_c.' c, '.$table_cu.' cu WHERE cu.course_code = c.code';
-	if (!api_is_platform_admin()) {
-		$sql .= ' AND cu.status=1 ';
-	}
-	$sql .= ' AND target_course_code IS NULL AND cu.user_id = '.$user_info['user_id'].' AND c.code != '."'".$course_info['sysCode']."'".' ORDER BY title ASC';
-	$res = Database::query($sql);
-	if (Database::num_rows($res) == 0) {
-		Display::display_normal_message(get_lang('NoDestinationCoursesAvailable'));
-	} else {
+    $table_c = Database :: get_main_table(TABLE_MAIN_COURSE);
+    $table_cu = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+    $user_info = api_get_user_info();
+    $course_info = api_get_course_info();
+    $sql = 'SELECT * FROM '.$table_c.' c, '.$table_cu.' cu WHERE cu.course_code = c.code';
+    if (!api_is_platform_admin()) {
+        $sql .= ' AND cu.status=1 ';
+    }
+    $sql .= ' AND target_course_code IS NULL AND cu.user_id = '.$user_info['user_id'].' AND c.code != '."'".$course_info['sysCode']."'".' ORDER BY title ASC';
+    $res = Database::query($sql);
+    if (Database::num_rows($res) == 0) {
+        Display::display_normal_message(get_lang('NoDestinationCoursesAvailable'));
+    } else {
         $options = array();
         while ($obj = Database::fetch_object($res)) {
             $options[$obj->code] = $obj->title;
         }
 
         $form = new FormValidator('copy_course', 'post', 'copy_course.php?'.api_get_cidreq());
-        $form->addElement('header','' );
-        $form->addElement('select','destination_course', get_lang('SelectDestinationCourse'), $options);
+        $form->addElement('header', '');
+        $form->addElement('select', 'destination_course', get_lang('SelectDestinationCourse'), $options);
 
         $group = array();
         $group[] = $form->createElement('radio', 'copy_option', null, get_lang('FullCopy'), 'full_copy');
@@ -93,17 +97,35 @@ if ((isset($_POST['action']) && $_POST['action'] == 'course_select_form') || (is
         $form->addGroup($group, '', get_lang('SelectOptionForBackup'));
 
         $group = array();
-        $group[] = $form->createElement('radio', 'same_file_name_option', null, get_lang('SameFilenameSkip'), FILE_SKIP);
-        $group[] = $form->createElement('radio', 'same_file_name_option', null, get_lang('SameFilenameRename'), FILE_RENAME);
-        $group[] = $form->createElement('radio', 'same_file_name_option', null, get_lang('SameFilenameOverwrite'), FILE_OVERWRITE);
+        $group[] = $form->createElement(
+            'radio',
+            'same_file_name_option',
+            null,
+            get_lang('SameFilenameSkip'),
+            FILE_SKIP
+        );
+        $group[] = $form->createElement(
+            'radio',
+            'same_file_name_option',
+            null,
+            get_lang('SameFilenameRename'),
+            FILE_RENAME
+        );
+        $group[] = $form->createElement(
+            'radio',
+            'same_file_name_option',
+            null,
+            get_lang('SameFilenameOverwrite'),
+            FILE_OVERWRITE
+        );
         $form->addGroup($group, '', get_lang('SameFilename'));
 
-        $form->addElement('style_submit_button', 'submit', get_lang('CopyCourse'),'class="save"');
+        $form->addElement('style_submit_button', 'submit', get_lang('CopyCourse'), 'class="save"');
 
-        $form->setDefaults(array('copy_option' =>'select_items','same_file_name_option' => FILE_OVERWRITE));
+        $form->setDefaults(array('copy_option' => 'select_items', 'same_file_name_option' => FILE_OVERWRITE));
         $form->display();
 
-	}
+    }
 }
 
 /*	FOOTER	*/

+ 327 - 280
main/coursecopy/copy_course_session.php

@@ -4,7 +4,7 @@
  * Copy resources from one course in a session to another one.
  *
  * @author Christian Fasanando <christian.fasanando@dokeos.com>
- * @author Julio Montoya	<gugli100@gmail.com> Lots of bug fixes/improvements
+ * @author Julio Montoya    <gugli100@gmail.com> Lots of bug fixes/improvements
  * @package chamilo.backup
  */
 /**
@@ -17,10 +17,9 @@ $language_file = array('coursebackup', 'admin');
 
 $cidReset = true;
 require_once '../inc/global.inc.php';
-$current_course_tool  = TOOL_COURSE_MAINTENANCE;
+$current_course_tool = TOOL_COURSE_MAINTENANCE;
 api_protect_course_script(true, true);
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'xajax/xajax.inc.php';
 
 require_once 'classes/CourseBuilder.class.php';
@@ -31,13 +30,13 @@ $xajax = new xajax();
 $xajax->registerFunction('search_courses');
 
 if (!api_is_allowed_to_edit() && !api_is_session_admin()) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 // Remove memory and time limits as much as possible as this might be a long process...
 if (function_exists('ini_set')) {
-	ini_set('memory_limit', '256M');
-	ini_set('max_execution_time', 1800);
+    ini_set('memory_limit', '256M');
+    ini_set('max_execution_time', 1800);
 }
 
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -46,207 +45,249 @@ $nameTools = get_lang('CopyCourse');
 $interbreadcrumb[] = array('url' => '../admin/index.php', 'name' => get_lang('PlatformAdmin'));
 
 // Database Table Definitions
-$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
+$tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
 
 /* FUNCTIONS */
 
-function make_select_session_list($name, $sessions, $attr = array()) {
-	
-	$attrs = '';
-	if (count($attr) > 0) {
-		foreach ($attr as $key => $value) {
-			$attrs .= ' '.$key.'="'.$value.'"';
-		}
-	}	
-	$output = '<select name="'.$name.'" '.$attrs.'>';
-	
-	if (count($sessions) == 0) {
-		$output .= '<option value = "0">'.get_lang('ThereIsNotStillASession').'</option>';
-	} else {
-		$output .= '<option value = "0">'.get_lang('SelectASession').'</option>';
-	}
-
-	if (is_array($sessions)) {
-		foreach ($sessions as $session) {
+function make_select_session_list($name, $sessions, $attr = array())
+{
+
+    $attrs = '';
+    if (count($attr) > 0) {
+        foreach ($attr as $key => $value) {
+            $attrs .= ' '.$key.'="'.$value.'"';
+        }
+    }
+    $output = '<select name="'.$name.'" '.$attrs.'>';
+
+    if (count($sessions) == 0) {
+        $output .= '<option value = "0">'.get_lang('ThereIsNotStillASession').'</option>';
+    } else {
+        $output .= '<option value = "0">'.get_lang('SelectASession').'</option>';
+    }
+
+    if (is_array($sessions)) {
+        foreach ($sessions as $session) {
             $category_name = '';
             if (!empty($session['category_name'])) {
                 $category_name = ' ('.$session['category_name'].')';
             }
-            
-			$output .= '<option value="'.$session['id'].'">'.$session['name'].' '.$category_name.'</option>';
-		}
-	}
-	$output .= '</select>';
- 	return $output;
+
+            $output .= '<option value="'.$session['id'].'">'.$session['name'].' '.$category_name.'</option>';
+        }
+    }
+    $output .= '</select>';
+
+    return $output;
 }
 
-function display_form() {
-	$html  = '';
-	$sessions = SessionManager::get_sessions_list(null, array('name ASC'));
-	
-	// Actions
-	$html .= '<div class="actions">';
-	// Link back to the documents overview
-	$html .= '<a href="../admin/index.php">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'),'',ICON_SIZE_MEDIUM).'</a>';
-	$html .= '</div>';
+function display_form()
+{
+    $html = '';
+    $sessions = SessionManager::get_sessions_list(null, array('name ASC'));
+
+    // Actions
+    $html .= '<div class="actions">';
+    // Link back to the documents overview
+    $html .= '<a href="../admin/index.php">'.Display::return_icon(
+        'back.png',
+        get_lang('BackTo').' '.get_lang('PlatformAdmin'),
+        '',
+        ICON_SIZE_MEDIUM
+    ).'</a>';
+    $html .= '</div>';
 
     $html .= Display::return_message(get_lang('CopyCourseFromSessionToSessionExplanation'));
-    
-	$html .= '<form name="formulaire" method="post" action="'.api_get_self().'" >';    
-	$html .= '<table border="0" cellpadding="5" cellspacing="0" width="100%">';
-    
-	// origin
-	$html .= '<tr><td width="15%"><b>'.get_lang('OriginCoursesFromSession').':</b></td>';
-	$html .= '<td width="10%" align="left">'.make_select_session_list('sessions_list_origin', $sessions, array('onchange' => 'javascript: xajax_search_courses(this.value,\'origin\');')).'</td>';	
-	$html .= '<td width="50%"><div id="ajax_list_courses_origin">';
-	$html .= '<select id="origin" name="SessionCoursesListOrigin[]"  style="width:380px;"></select></div></td></tr>';
-    
-    //destination    
-    $html .= '<tr><td width="15%"><b>'.get_lang('DestinationCoursesFromSession').':</b></td>';    
+
+    $html .= '<form name="formulaire" method="post" action="'.api_get_self().'" >';
+    $html .= '<table border="0" cellpadding="5" cellspacing="0" width="100%">';
+
+    // origin
+    $html .= '<tr><td width="15%"><b>'.get_lang('OriginCoursesFromSession').':</b></td>';
+    $html .= '<td width="10%" align="left">'.make_select_session_list(
+        'sessions_list_origin',
+        $sessions,
+        array('onchange' => 'javascript: xajax_search_courses(this.value,\'origin\');')
+    ).'</td>';
+    $html .= '<td width="50%"><div id="ajax_list_courses_origin">';
+    $html .= '<select id="origin" name="SessionCoursesListOrigin[]"  style="width:380px;"></select></div></td></tr>';
+
+    //destination
+    $html .= '<tr><td width="15%"><b>'.get_lang('DestinationCoursesFromSession').':</b></td>';
     $html .= '<td width="10%" align="left"><div id="ajax_sessions_list_destination">';
-	$html .= '<select name="sessions_list_destination" onchange="javascript: xajax_search_courses(this.value,\'destination\');">';
-	$html .= '<option value = "0">'.get_lang('ThereIsNotStillASession').'</option></select ></div></td>';    
-	
-	$html .= '<td width="50%">';
-	$html .= '<div id="ajax_list_courses_destination">';
-	$html .= '<select id="destination" name="SessionCoursesListDestination[]" style="width:380px;" ></select></div></td>';
-	$html .= '</tr></table>';
-	
-	$html .= '<h3>'.get_lang('TypeOfCopy').'</h3>';
+    $html .= '<select name="sessions_list_destination" onchange="javascript: xajax_search_courses(this.value,\'destination\');">';
+    $html .= '<option value = "0">'.get_lang('ThereIsNotStillASession').'</option></select ></div></td>';
+
+    $html .= '<td width="50%">';
+    $html .= '<div id="ajax_list_courses_destination">';
+    $html .= '<select id="destination" name="SessionCoursesListDestination[]" style="width:380px;" ></select></div></td>';
+    $html .= '</tr></table>';
+
+    $html .= '<h3>'.get_lang('TypeOfCopy').'</h3>';
     $html .= '<label class="radio"><input type="radio" id="copy_option_1" name="copy_option" value="full_copy" checked="checked"/>';
     $html .= get_lang('FullCopy').'</label><br/>';
     $html .= '<label class="radio"><input type="radio" id="copy_option_2" name="copy_option" value="select_items" disabled="disabled"/>';
     $html .= ' '.get_lang('LetMeSelectItems').'</label><br/>';
-    
-    $html .= '<label class="checkbox"><input type="checkbox" id="copy_base_content_id" name="copy_only_session_items" />'.get_lang('CopyOnlySessionItems').'</label><br /><br/>';
-	
-	$html .= '<button class="save" type="submit" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;">'.get_lang('CopyCourse').'</button>';
+
+    $html .= '<label class="checkbox"><input type="checkbox" id="copy_base_content_id" name="copy_only_session_items" />'.get_lang(
+        'CopyOnlySessionItems'
+    ).'</label><br /><br/>';
+
+    $html .= '<button class="save" type="submit" onclick="javascript:if(!confirm('."'".addslashes(
+        api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)
+    )."'".')) return false;">'.get_lang('CopyCourse').'</button>';
     $html .= '</form>';
-	echo $html;
+    echo $html;
 }
 
-function search_courses($id_session, $type) {	
-	global $tbl_course, $tbl_session_rel_course, $course_list;
-	$xajax_response = new XajaxResponse();
-	$select_destination = '';
-	if (!empty($type)) {
+function search_courses($id_session, $type)
+{
+    global $tbl_course, $tbl_session_rel_course, $course_list;
+    $xajax_response = new XajaxResponse();
+    $select_destination = '';
+    if (!empty($type)) {
+
+        $id_session = intval($id_session);
 
-		$id_session = intval($id_session);
+        if ($type == 'origin') {
 
-		if ($type == 'origin') {
-		    
             $course_list = SessionManager::get_course_list_by_session_id($id_session);
-     
-			$temp_course_list = array();
-			$return .= '<select id="origin" name="SessionCoursesListOrigin[]" style="width:380px;" onclick="javascript: checkSelected(this.id,\'copy_option_2\',\'title_option2\',\'destination\');">';
-			
-			foreach ($course_list as $course) {			    
-				$temp_course_list[] = "'{$course['code']}'";
-				$course_title=str_replace("'","\'",$course_title);
-				$return .= '<option value="'.$course['code'].'" title="'.@htmlspecialchars($course['title'].' ('.$course['visual_code'].')', ENT_QUOTES, api_get_system_encoding()).'">'.$course['title'].' ('.$course['visual_code'].')</option>';
-			}
-
-			$return .= '</select>';
-			$_SESSION['course_list']     = $temp_course_list;
-			$_SESSION['session_origin']  = $id_session;
-
-			// Build select for destination sessions where is not included current session from select origin
-			if (!empty($id_session)) {
-			    
-			    $sessions = SessionManager::get_sessions_list(null, array('name ASC'));
-
-				$select_destination .= '<select name="sessions_list_destination" width="380px" onchange = "javascript: xajax_search_courses(this.value,\'destination\');">';
-				$select_destination .= '<option value = "0">-- '.get_lang('SelectASession').' --</option>';
-				foreach ($sessions as $session) {
-				    if ($id_session == $session['id']) { continue; };
-				    if (!empty($session['category_name'])) {
-				        $session['category_name'] = ' ('.$session['category_name'].') '; 
-				    }
-					$select_destination .= '<option value="'.$session['id'].'">'.$session['name'].' '.$session['category_name'].'</option>';
-				}
-				$select_destination .= '</select>';
-				$xajax_response -> addAssign('ajax_sessions_list_destination', 'innerHTML', api_utf8_encode($select_destination));
-			} else {
-				$select_destination .= '<select name="sessions_list_destination" width="380px" onchange = "javascript: xajax_search_courses(this.value,\'destination\');">';
-				$select_destination .= '<option value = "0">'.get_lang('ThereIsNotStillASession').'</option>';
-				$select_destination .= '</select>';
-				$xajax_response -> addAssign('ajax_sessions_list_destination', 'innerHTML', api_utf8_encode($select_destination));
-			}
-
-			// Select multiple destination empty
-			$select_multiple_empty = '<select id="destination" name="SessionCoursesListDestination[]" style="width:380px;"></select>';
-
-			// Send response by ajax
-			$xajax_response -> addAssign('ajax_list_courses_origin', 'innerHTML', api_utf8_encode($return));
-			$xajax_response -> addAssign('ajax_list_courses_destination', 'innerHTML', api_utf8_encode($select_multiple_empty));
-		} else {
-			//Left Select - Destination
-			
-			$list_courses_origin = implode(',', $_SESSION['course_list']);
-			$session_origin = $_SESSION['session_origin'];
-
-			// Search courses by id_session where course codes is include en courses list destination
-			$sql = "SELECT c.code, c.visual_code, c.title, src.id_session
+
+            $temp_course_list = array();
+            $return .= '<select id="origin" name="SessionCoursesListOrigin[]" style="width:380px;" onclick="javascript: checkSelected(this.id,\'copy_option_2\',\'title_option2\',\'destination\');">';
+
+            foreach ($course_list as $course) {
+                $temp_course_list[] = "'{$course['code']}'";
+                $course_title = str_replace("'", "\'", $course_title);
+                $return .= '<option value="'.$course['code'].'" title="'.@htmlspecialchars(
+                    $course['title'].' ('.$course['visual_code'].')',
+                    ENT_QUOTES,
+                    api_get_system_encoding()
+                ).'">'.$course['title'].' ('.$course['visual_code'].')</option>';
+            }
+
+            $return .= '</select>';
+            $_SESSION['course_list'] = $temp_course_list;
+            $_SESSION['session_origin'] = $id_session;
+
+            // Build select for destination sessions where is not included current session from select origin
+            if (!empty($id_session)) {
+
+                $sessions = SessionManager::get_sessions_list(null, array('name ASC'));
+
+                $select_destination .= '<select name="sessions_list_destination" width="380px" onchange = "javascript: xajax_search_courses(this.value,\'destination\');">';
+                $select_destination .= '<option value = "0">-- '.get_lang('SelectASession').' --</option>';
+                foreach ($sessions as $session) {
+                    if ($id_session == $session['id']) {
+                        continue;
+                    }
+                    ;
+                    if (!empty($session['category_name'])) {
+                        $session['category_name'] = ' ('.$session['category_name'].') ';
+                    }
+                    $select_destination .= '<option value="'.$session['id'].'">'.$session['name'].' '.$session['category_name'].'</option>';
+                }
+                $select_destination .= '</select>';
+                $xajax_response->addAssign(
+                    'ajax_sessions_list_destination',
+                    'innerHTML',
+                    api_utf8_encode($select_destination)
+                );
+            } else {
+                $select_destination .= '<select name="sessions_list_destination" width="380px" onchange = "javascript: xajax_search_courses(this.value,\'destination\');">';
+                $select_destination .= '<option value = "0">'.get_lang('ThereIsNotStillASession').'</option>';
+                $select_destination .= '</select>';
+                $xajax_response->addAssign(
+                    'ajax_sessions_list_destination',
+                    'innerHTML',
+                    api_utf8_encode($select_destination)
+                );
+            }
+
+            // Select multiple destination empty
+            $select_multiple_empty = '<select id="destination" name="SessionCoursesListDestination[]" style="width:380px;"></select>';
+
+            // Send response by ajax
+            $xajax_response->addAssign('ajax_list_courses_origin', 'innerHTML', api_utf8_encode($return));
+            $xajax_response->addAssign(
+                'ajax_list_courses_destination',
+                'innerHTML',
+                api_utf8_encode($select_multiple_empty)
+            );
+        } else {
+            //Left Select - Destination
+
+            $list_courses_origin = implode(',', $_SESSION['course_list']);
+            $session_origin = $_SESSION['session_origin'];
+
+            // Search courses by id_session where course codes is include en courses list destination
+            $sql = "SELECT c.code, c.visual_code, c.title, src.id_session
 					FROM $tbl_course c, $tbl_session_rel_course src
 					WHERE src.course_code = c.code
 					AND src.id_session = '".intval($id_session)."'";
-					//AND c.code IN ($list_courses_origin)";
-			$rs = Database::query($sql);
-
-			$course_list_destination = array();
-			//onmouseover="javascript: this.disabled=true;" onmouseout="javascript: this.disabled=false;"
-			$return .= '<select id="destination" name="SessionCoursesListDestination[]" style="width:380px;" >';
-			while ($course = Database :: fetch_array($rs)) {
-				$course_list_destination[] = $course['code'];
-				$course_title = str_replace("'", "\'", $course_title);
-				$return .= '<option value="'.$course['code'].'" title="'.@htmlspecialchars($course['title'].' ('.$course['visual_code'].')', ENT_QUOTES, api_get_system_encoding()).'">'.$course['title'].' ('.$course['visual_code'].')</option>';
-			}
-			$return .= '</select>';
-			$_SESSION['course_list_destination'] = $course_list_destination;
-
-			// Send response by ajax
-			$xajax_response -> addAssign('ajax_list_courses_destination', 'innerHTML', api_utf8_encode($return));
-/*
-			// Disable option from session courses list origin where if no the same con the destination
-			$sql = "SELECT c.code, c.visual_code, c.title, src.id_session
-					FROM $tbl_course c, $tbl_session_rel_course src
-					WHERE src.course_code = c.code
-					AND src.id_session = '".intval($session_origin)."'";
-			$result = Database::query($sql);
-
-			$return_option_disabled = '<select id="origin" name="SessionCoursesListOrigin[]" multiple="multiple" size="20" style="width:320px;" onclick="javascript: checkSelected(this.id,\'copy_option_2\',\'title_option2\',\'destination\');">';
-			while ($cours = Database :: fetch_array($result)) {
-				$course_title=str_replace("'", "\'", $course_title);
-				if (count($course_list_destination) > 0) {
-					if (!in_array($cours['code'], $course_list_destination)) {
-						$return_option_disabled .= '<optgroup style="color:#ccc" label="'.$cours['title'].' ('.$cours['visual_code'].')" >'.$cours['title'].' ('.$cours['visual_code'].')</optgroup>';
-					} else {
-						$return_option_disabled .= '<option value="'.$cours['code'].'" title="'.@htmlspecialchars($cours['title'].' ('.$cours['visual_code'].')', ENT_QUOTES, api_get_system_encoding()).'">'.$cours['title'].' ('.$cours['visual_code'].')</option>';
-					}
-				} else {
-					if (empty($id_session)) {
-						$return_option_disabled .= '<option value="'.$cours['code'].'" title="'.@htmlspecialchars($cours['title'].' ('.$cours['visual_code'].')', ENT_QUOTES, api_get_system_encoding()).'">'.$cours['title'].' ('.$cours['visual_code'].')</option>';
-					} else {
-						$return_option_disabled .= '<optgroup style="color:#ccc" label="'.$cours['title'].'('.$cours['visual_code'].')" >'.$cours['title'].' ('.$cours['visual_code'].')</optgroup>';
-					}
-				}
-			}
-			$return_option_disabled .= '</select>';*/
-			// Send response by ajax
-			//$xajax_response -> addAssign('ajax_list_courses_origin', 'innerHTML', api_utf8_encode($return_option_disabled));
-		}
-	}
-	return $xajax_response;
+            //AND c.code IN ($list_courses_origin)";
+            $rs = Database::query($sql);
+
+            $course_list_destination = array();
+            //onmouseover="javascript: this.disabled=true;" onmouseout="javascript: this.disabled=false;"
+            $return .= '<select id="destination" name="SessionCoursesListDestination[]" style="width:380px;" >';
+            while ($course = Database :: fetch_array($rs)) {
+                $course_list_destination[] = $course['code'];
+                $course_title = str_replace("'", "\'", $course_title);
+                $return .= '<option value="'.$course['code'].'" title="'.@htmlspecialchars(
+                    $course['title'].' ('.$course['visual_code'].')',
+                    ENT_QUOTES,
+                    api_get_system_encoding()
+                ).'">'.$course['title'].' ('.$course['visual_code'].')</option>';
+            }
+            $return .= '</select>';
+            $_SESSION['course_list_destination'] = $course_list_destination;
+
+            // Send response by ajax
+            $xajax_response->addAssign('ajax_list_courses_destination', 'innerHTML', api_utf8_encode($return));
+            /*
+                        // Disable option from session courses list origin where if no the same con the destination
+                        $sql = "SELECT c.code, c.visual_code, c.title, src.id_session
+                                FROM $tbl_course c, $tbl_session_rel_course src
+                                WHERE src.course_code = c.code
+                                AND src.id_session = '".intval($session_origin)."'";
+                        $result = Database::query($sql);
+
+                        $return_option_disabled = '<select id="origin" name="SessionCoursesListOrigin[]" multiple="multiple" size="20" style="width:320px;" onclick="javascript: checkSelected(this.id,\'copy_option_2\',\'title_option2\',\'destination\');">';
+                        while ($cours = Database :: fetch_array($result)) {
+                            $course_title=str_replace("'", "\'", $course_title);
+                            if (count($course_list_destination) > 0) {
+                                if (!in_array($cours['code'], $course_list_destination)) {
+                                    $return_option_disabled .= '<optgroup style="color:#ccc" label="'.$cours['title'].' ('.$cours['visual_code'].')" >'.$cours['title'].' ('.$cours['visual_code'].')</optgroup>';
+                                } else {
+                                    $return_option_disabled .= '<option value="'.$cours['code'].'" title="'.@htmlspecialchars($cours['title'].' ('.$cours['visual_code'].')', ENT_QUOTES, api_get_system_encoding()).'">'.$cours['title'].' ('.$cours['visual_code'].')</option>';
+                                }
+                            } else {
+                                if (empty($id_session)) {
+                                    $return_option_disabled .= '<option value="'.$cours['code'].'" title="'.@htmlspecialchars($cours['title'].' ('.$cours['visual_code'].')', ENT_QUOTES, api_get_system_encoding()).'">'.$cours['title'].' ('.$cours['visual_code'].')</option>';
+                                } else {
+                                    $return_option_disabled .= '<optgroup style="color:#ccc" label="'.$cours['title'].'('.$cours['visual_code'].')" >'.$cours['title'].' ('.$cours['visual_code'].')</optgroup>';
+                                }
+                            }
+                        }
+                        $return_option_disabled .= '</select>';*/
+            // Send response by ajax
+            //$xajax_response -> addAssign('ajax_list_courses_origin', 'innerHTML', api_utf8_encode($return_option_disabled));
+        }
+    }
+
+    return $xajax_response;
 }
-$xajax -> processRequests();
+
+$xajax->processRequests();
 
 /* HTML head extra */
 
-$htmlHeadXtra[] = $xajax->getJavascript( api_get_path(WEB_LIBRARY_PATH).'xajax/');
+$htmlHeadXtra[] = $xajax->getJavascript(api_get_path(WEB_LIBRARY_PATH).'xajax/');
 $htmlHeadXtra[] = '<script type="text/javascript">
 
 						function checkSelected(id_select,id_radio,id_title,id_destination) {
@@ -294,115 +335,121 @@ if (isset($_POST['copy_only_session_items']) && $_POST['copy_only_session_items'
     $with_base_content = false;
 }
 
-        
+
 /*  MAIN CODE  */
 
 if ((isset($_POST['action']) && $_POST['action'] == 'course_select_form') || (isset($_POST['copy_option']) && $_POST['copy_option'] == 'full_copy')) {
 
-	$destination_course = $origin_course = $destination_session = $origin_session = '';
-
-	if (isset ($_POST['action']) && $_POST['action'] == 'course_select_form') {
-	
-		$destination_course	 	= $_POST['destination_course'];
-		$origin_course 			= $_POST['origin_course'];
-		$destination_session 	= $_POST['destination_session'];
-		$origin_session 		= $_POST['origin_session'];
-		
-		$course = CourseSelectForm :: get_posted_course('copy_course', $origin_session, $origin_course);
-		
-		$cr = new CourseRestorer($course);
-		//$cr->set_file_option($_POST['same_file_name_option']);
-		$cr->restore($destination_course, $destination_session);
-		Display::display_confirmation_message(get_lang('CopyFinished'));
-		display_form();
-	} else {
-
-		$arr_course_origin 		= array();
-		$arr_course_destination = array();
-		$destination_session 	= '';
-		$origin_session 		= '';
-
-		if (isset($_POST['SessionCoursesListOrigin'])) {
-			$arr_course_origin 		= $_POST['SessionCoursesListOrigin'];
-		}
-		if (isset($_POST['SessionCoursesListDestination'])) {
-			$arr_course_destination = $_POST['SessionCoursesListDestination'];
-		}
-		if (isset($_POST['sessions_list_destination'])) {
-			$destination_session 	= $_POST['sessions_list_destination'];
-		}
-		if (isset($_POST['sessions_list_origin'])) {
-			$origin_session 		= $_POST['sessions_list_origin'];
-		}
-  
-		if ((is_array($arr_course_origin) && count($arr_course_origin) > 0) && !empty($destination_session)) {
-			//We need only one value			
-			if (count($arr_course_origin) > 1 || count($arr_course_destination) > 1) {
-				Display::display_error_message(get_lang('YouMustSelectACourseFromOriginalSession'));				
-			} else {
-				//foreach ($arr_course_origin as $course_origin) {
-				//first element of the array
-				$course_code = $arr_course_origin[0];
-				$course_destinatination = $arr_course_destination[0];
-				
-				$course_origin = api_get_course_info($course_code);				
-				$cb = new CourseBuilder('', $course_origin);
-				$course = $cb->build($origin_session, $course_code, $with_base_content);
-				$cr = new CourseRestorer($course);				
-				$cr->restore($course_destinatination, $destination_session);
-				
-			}
-			Display::display_confirmation_message(get_lang('CopyFinished'));
-			display_form();
-		} else {
-			Display::display_error_message(get_lang('YouMustSelectACourseFromOriginalSession'));
-			display_form();
-		}
-	}
+    $destination_course = $origin_course = $destination_session = $origin_session = '';
+
+    if (isset ($_POST['action']) && $_POST['action'] == 'course_select_form') {
+
+        $destination_course = $_POST['destination_course'];
+        $origin_course = $_POST['origin_course'];
+        $destination_session = $_POST['destination_session'];
+        $origin_session = $_POST['origin_session'];
+
+        $course = CourseSelectForm :: get_posted_course('copy_course', $origin_session, $origin_course);
+
+        $cr = new CourseRestorer($course);
+        //$cr->set_file_option($_POST['same_file_name_option']);
+        $cr->restore($destination_course, $destination_session);
+        Display::display_confirmation_message(get_lang('CopyFinished'));
+        display_form();
+    } else {
+
+        $arr_course_origin = array();
+        $arr_course_destination = array();
+        $destination_session = '';
+        $origin_session = '';
+
+        if (isset($_POST['SessionCoursesListOrigin'])) {
+            $arr_course_origin = $_POST['SessionCoursesListOrigin'];
+        }
+        if (isset($_POST['SessionCoursesListDestination'])) {
+            $arr_course_destination = $_POST['SessionCoursesListDestination'];
+        }
+        if (isset($_POST['sessions_list_destination'])) {
+            $destination_session = $_POST['sessions_list_destination'];
+        }
+        if (isset($_POST['sessions_list_origin'])) {
+            $origin_session = $_POST['sessions_list_origin'];
+        }
+
+        if ((is_array($arr_course_origin) && count($arr_course_origin) > 0) && !empty($destination_session)) {
+            //We need only one value
+            if (count($arr_course_origin) > 1 || count($arr_course_destination) > 1) {
+                Display::display_error_message(get_lang('YouMustSelectACourseFromOriginalSession'));
+            } else {
+                //foreach ($arr_course_origin as $course_origin) {
+                //first element of the array
+                $course_code = $arr_course_origin[0];
+                $course_destinatination = $arr_course_destination[0];
+
+                $course_origin = api_get_course_info($course_code);
+                $cb = new CourseBuilder('', $course_origin);
+                $course = $cb->build($origin_session, $course_code, $with_base_content);
+                $cr = new CourseRestorer($course);
+                $cr->restore($course_destinatination, $destination_session);
+
+            }
+            Display::display_confirmation_message(get_lang('CopyFinished'));
+            display_form();
+        } else {
+            Display::display_error_message(get_lang('YouMustSelectACourseFromOriginalSession'));
+            display_form();
+        }
+    }
 } elseif (isset($_POST['copy_option']) && $_POST['copy_option'] == 'select_items') {
 
-	// Else, if a CourseSelectForm is requested, show it
-	if (api_get_setting('show_glossary_in_documents') != 'none') {
-		Display::display_normal_message(get_lang('ToExportDocumentsWithGlossaryYouHaveToSelectGlossary'));
-	}
-
-	$arr_course_origin 		= array();
-	$arr_course_destination = array();
-	$destination_session 	= '';
-	$origin_session 		= '';
-
-	if (isset($_POST['SessionCoursesListOrigin'])) {
-		$arr_course_origin 		= $_POST['SessionCoursesListOrigin'];
-	}
-	if (isset($_POST['SessionCoursesListDestination'])) {
-		$arr_course_destination = $_POST['SessionCoursesListDestination'];
-	}
-	if (isset($_POST['sessions_list_destination'])) {
-		$destination_session 	= $_POST['sessions_list_destination'];
-	}
-	if (isset($_POST['sessions_list_origin'])) {
-		$origin_session 		= $_POST['sessions_list_origin'];
-	}
-
-	if ((is_array($arr_course_origin) && count($arr_course_origin) > 0) && !empty($destination_session)) {
-		Display::display_normal_message(get_lang('ToExportLearnpathWithQuizYouHaveToSelectQuiz'));
-		$course_origin = api_get_course_info($arr_course_origin[0]);		
-		$cb = new CourseBuilder('', $course_origin);
-		$course = $cb->build($origin_session, $arr_course_origin[0], $with_base_content);
-		//$hidden_fields['same_file_name_option'] = $_POST['same_file_name_option'];
-		$hidden_fields['destination_course'] 	= $arr_course_destination[0];
-		$hidden_fields['origin_course'] 		= $arr_course_origin[0];
-		$hidden_fields['destination_session'] 	= $destination_session;
-		$hidden_fields['origin_session'] 		= $origin_session;				
-				
-		CourseSelectForm :: display_form($course, $hidden_fields, true);
-		echo '<div style="float:right"><a href="javascript:window.back();">'.Display::return_icon('back.png', get_lang('Back').' '.get_lang('To').' '.get_lang('PlatformAdmin'), array('style' => 'vertical-align:middle')).get_lang('Back').'</a></div>';
-	} else {
-		Display::display_error_message(get_lang('You must select a course from original session and select a destination session'));
-		display_form();
-	}
+    // Else, if a CourseSelectForm is requested, show it
+    if (api_get_setting('show_glossary_in_documents') != 'none') {
+        Display::display_normal_message(get_lang('ToExportDocumentsWithGlossaryYouHaveToSelectGlossary'));
+    }
+
+    $arr_course_origin = array();
+    $arr_course_destination = array();
+    $destination_session = '';
+    $origin_session = '';
+
+    if (isset($_POST['SessionCoursesListOrigin'])) {
+        $arr_course_origin = $_POST['SessionCoursesListOrigin'];
+    }
+    if (isset($_POST['SessionCoursesListDestination'])) {
+        $arr_course_destination = $_POST['SessionCoursesListDestination'];
+    }
+    if (isset($_POST['sessions_list_destination'])) {
+        $destination_session = $_POST['sessions_list_destination'];
+    }
+    if (isset($_POST['sessions_list_origin'])) {
+        $origin_session = $_POST['sessions_list_origin'];
+    }
+
+    if ((is_array($arr_course_origin) && count($arr_course_origin) > 0) && !empty($destination_session)) {
+        Display::display_normal_message(get_lang('ToExportLearnpathWithQuizYouHaveToSelectQuiz'));
+        $course_origin = api_get_course_info($arr_course_origin[0]);
+        $cb = new CourseBuilder('', $course_origin);
+        $course = $cb->build($origin_session, $arr_course_origin[0], $with_base_content);
+        //$hidden_fields['same_file_name_option'] = $_POST['same_file_name_option'];
+        $hidden_fields['destination_course'] = $arr_course_destination[0];
+        $hidden_fields['origin_course'] = $arr_course_origin[0];
+        $hidden_fields['destination_session'] = $destination_session;
+        $hidden_fields['origin_session'] = $origin_session;
+
+        CourseSelectForm :: display_form($course, $hidden_fields, true);
+        echo '<div style="float:right"><a href="javascript:window.back();">'.Display::return_icon(
+            'back.png',
+            get_lang('Back').' '.get_lang('To').' '.get_lang('PlatformAdmin'),
+            array('style' => 'vertical-align:middle')
+        ).get_lang('Back').'</a></div>';
+    } else {
+        Display::display_error_message(
+            get_lang('You must select a course from original session and select a destination session')
+        );
+        display_form();
+    }
 } else {
-	display_form();
+    display_form();
 }
 
 Display::display_footer();

+ 48 - 39
main/coursecopy/create_backup.php

@@ -14,7 +14,7 @@ $language_file = array('exercice', 'admin', 'coursebackup');
 
 // Including the global initialization file
 require_once '../inc/global.inc.php';
-$current_course_tool  = TOOL_COURSE_MAINTENANCE;
+$current_course_tool = TOOL_COURSE_MAINTENANCE;
 
 api_protect_course_script(true);
 
@@ -22,13 +22,13 @@ api_check_archive_dir();
 
 // Check access rights (only teachers are allowed here)
 if (!api_is_allowed_to_edit()) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 // Remove memory and time limits as much as possible as this might be a long process...
 if (function_exists('ini_set')) {
-	ini_set('memory_limit', '256M');
-	ini_set('max_execution_time', 1800);
+    ini_set('memory_limit', '256M');
+    ini_set('max_execution_time', 1800);
 }
 
 // Section for the tabs
@@ -42,7 +42,6 @@ $nameTools = get_lang('CreateBackup');
 Display::display_header($nameTools);
 
 // Include additional libraries
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once 'classes/CourseBuilder.class.php';
 require_once 'classes/CourseArchiver.class.php';
 require_once 'classes/CourseRestorer.class.php';
@@ -54,43 +53,53 @@ echo Display::page_header($nameTools);
 /*	MAIN CODE */
 
 if ((isset($_POST['action']) && $_POST['action'] == 'course_select_form') || (isset($_POST['backup_option']) && $_POST['backup_option'] == 'full_backup')) {
-	if (isset ($_POST['action']) && $_POST['action'] == 'course_select_form') {
-		$course = CourseSelectForm::get_posted_course();        
-	} else {
-		$cb = new CourseBuilder();
-		$course = $cb->build();
-	}
-	$zip_file = CourseArchiver::write_course($course); 
-	Display::display_confirmation_message(get_lang('BackupCreated'));
-	echo '<br /><a class="btn btn-primary btn-large" href="../course_info/download.php?archive='.$zip_file.'">'.get_lang('Download').'</a>';
+    if (isset ($_POST['action']) && $_POST['action'] == 'course_select_form') {
+        $course = CourseSelectForm::get_posted_course();
+    } else {
+        $cb = new CourseBuilder();
+        $course = $cb->build();
+    }
+    $zip_file = CourseArchiver::write_course($course);
+    Display::display_confirmation_message(get_lang('BackupCreated'));
+    echo '<br /><a class="btn btn-primary btn-large" href="../course_info/download.php?archive='.$zip_file.'">'.get_lang(
+        'Download'
+    ).'</a>';
 
 } elseif (isset($_POST['backup_option']) && $_POST['backup_option'] == 'select_items') {
-	$cb = new CourseBuilder('partial');
-	$course = $cb->build();
-	CourseSelectForm::display_form($course);
+    $cb = new CourseBuilder('partial');
+    $course = $cb->build();
+    CourseSelectForm::display_form($course);
 } else {
-	$cb = new CourseBuilder();
-	$course = $cb->build();
-	if (!$course->has_resources()) {
-		echo get_lang('NoResourcesToBackup');
-	} else {		
-		
-		$form = new FormValidator('create_backup_form', 'post');
-		$form->addElement('header',get_lang('SelectOptionForBackup'));
-		
-		$form->addElement('radio', 'backup_option', '', get_lang('CreateFullBackup'), 'full_backup');
-		$form->addElement('radio', 'backup_option', '',  get_lang('LetMeSelectItems'), 'select_items');
-		
-		$form->addElement('style_submit_button', null, get_lang('CreateBackup'), 'class="save"');
-
-		$form->add_progress_bar();
-		// When progress bar appears we have to hide the title "Please select a backup-option".
-		$form->updateAttributes(array('onsubmit' => str_replace('javascript: ', 'javascript: page_title = getElementById(\'page_title\'); if (page_title) { setTimeout(\'page_title.style.display = \\\'none\\\';\', 2000); } ', $form->getAttribute('onsubmit'))));
-
-		$values['backup_option'] = 'full_backup';
-		$form->setDefaults($values);
-		$form->display();
-	}
+    $cb = new CourseBuilder();
+    $course = $cb->build();
+    if (!$course->has_resources()) {
+        echo get_lang('NoResourcesToBackup');
+    } else {
+
+        $form = new FormValidator('create_backup_form', 'post');
+        $form->addElement('header', get_lang('SelectOptionForBackup'));
+
+        $form->addElement('radio', 'backup_option', '', get_lang('CreateFullBackup'), 'full_backup');
+        $form->addElement('radio', 'backup_option', '', get_lang('LetMeSelectItems'), 'select_items');
+
+        $form->addElement('style_submit_button', null, get_lang('CreateBackup'), 'class="save"');
+
+        $form->add_progress_bar();
+        // When progress bar appears we have to hide the title "Please select a backup-option".
+        $form->updateAttributes(
+            array(
+                'onsubmit' => str_replace(
+                    'javascript: ',
+                    'javascript: page_title = getElementById(\'page_title\'); if (page_title) { setTimeout(\'page_title.style.display = \\\'none\\\';\', 2000); } ',
+                    $form->getAttribute('onsubmit')
+                )
+            )
+        );
+
+        $values['backup_option'] = 'full_backup';
+        $form->setDefaults($values);
+        $form->display();
+    }
 }
 
 /*	FOOTER */

+ 173 - 112
main/coursecopy/import_backup.php

@@ -16,18 +16,18 @@ $language_file = array('exercice', 'coursebackup', 'admin');
 
 // Including the global initialization file
 require '../inc/global.inc.php';
-$current_course_tool  = TOOL_COURSE_MAINTENANCE;
+$current_course_tool = TOOL_COURSE_MAINTENANCE;
 api_protect_course_script(true);
 
 // Check access rights (only teachers are allowed here)
 if (!api_is_allowed_to_edit()) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 // Remove memory and time limits as much as possible as this might be a long process...
 if (function_exists('ini_set')) {
-	ini_set('memory_limit', '256M');
-	ini_set('max_execution_time', 1800);
+    ini_set('memory_limit', '256M');
+    ini_set('max_execution_time', 1800);
 }
 
 // Section for the tabs
@@ -41,7 +41,6 @@ $nameTools = get_lang('ImportBackup');
 Display::display_header($nameTools);
 
 // Include additional libraries
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once 'classes/CourseBuilder.class.php';
 require_once 'classes/CourseArchiver.class.php';
 require_once 'classes/CourseRestorer.class.php';
@@ -52,132 +51,194 @@ echo Display::page_header($nameTools);
 
 /*	MAIN CODE */
 
-if ((isset($_POST['action']) && $_POST['action'] == 'course_select_form' ) || (isset($_POST['import_option']) && $_POST['import_option'] == 'full_backup' )) {
-	$error = false;
-	if (isset($_POST['action']) && $_POST['action'] == 'course_select_form') {
-		// Partial backup here we recover the documents posted
-		$course = CourseSelectForm::get_posted_course();
-        
-	} else {
-		if ($_POST['backup_type'] == 'server') {
-			$filename = $_POST['backup_server'];
-			$delete_file = false;
-		} else {
-			if ($_FILES['backup']['error'] == 0) {
-				$filename = CourseArchiver::import_uploaded_file($_FILES['backup']['tmp_name']);
-				if ($filename === false) {
-                	$error = true;
-                } else                {
+if ((isset($_POST['action']) && $_POST['action'] == 'course_select_form') || (isset($_POST['import_option']) && $_POST['import_option'] == 'full_backup')) {
+    $error = false;
+    if (isset($_POST['action']) && $_POST['action'] == 'course_select_form') {
+        // Partial backup here we recover the documents posted
+        $course = CourseSelectForm::get_posted_course();
+
+    } else {
+        if ($_POST['backup_type'] == 'server') {
+            $filename = $_POST['backup_server'];
+            $delete_file = false;
+        } else {
+            if ($_FILES['backup']['error'] == 0) {
+                $filename = CourseArchiver::import_uploaded_file($_FILES['backup']['tmp_name']);
+                if ($filename === false) {
+                    $error = true;
+                } else {
                     $delete_file = true;
                 }
-			} else {
-				$error = true;
-			}
-		}
-    
+            } else {
+                $error = true;
+            }
+        }
+
         if (!$error) {
-		  // Full backup
-		  $course = CourseArchiver::read_course($filename, $delete_file);
+            // Full backup
+            $course = CourseArchiver::read_course($filename, $delete_file);
         }
-	}
-
-	if (!$error && $course->has_resources()) {
-		$cr = new CourseRestorer($course);
-		$cr->set_file_option($_POST['same_file_name_option']);
-		$cr->restore();
-		Display::display_normal_message(get_lang('ImportFinished'));
-        echo '<a class="btn" href="'.api_get_path(WEB_COURSE_PATH).api_get_course_path().'/index.php">'.get_lang('CourseHomepage').'</a>';
-	} else {
-		if (!$error) {
-			Display::display_warning_message(get_lang('NoResourcesInBackupFile'));
+    }
+
+    if (!$error && $course->has_resources()) {
+        $cr = new CourseRestorer($course);
+        $cr->set_file_option($_POST['same_file_name_option']);
+        $cr->restore();
+        Display::display_normal_message(get_lang('ImportFinished'));
+        echo '<a class="btn" href="'.api_get_path(WEB_COURSE_PATH).api_get_course_path().'/index.php">'.get_lang(
+            'CourseHomepage'
+        ).'</a>';
+    } else {
+        if (!$error) {
+            Display::display_warning_message(get_lang('NoResourcesInBackupFile'));
             echo  '<a class="btn" href="import_backup.php?'.api_get_cidreq().'">'.get_lang('TryAgain').'</a>';
-		} elseif ($filename === false) {
+        } elseif ($filename === false) {
             Display::display_error_message(get_lang('ArchivesDirectoryNotWriteableContactAdmin'));
             echo '<a class="btn" href="import_backup.php?'.api_get_cidreq().'">'.get_lang('TryAgain').'</a>';
         } else {
             if ($filename == '') {
-               Display::display_error_message(get_lang('SelectBackupFile')); 
-               echo '<a class="btn" href="import_backup.php?'.api_get_cidreq().'">'.get_lang('TryAgain').'</a>';
+                Display::display_error_message(get_lang('SelectBackupFile'));
+                echo '<a class="btn" href="import_backup.php?'.api_get_cidreq().'">'.get_lang('TryAgain').'</a>';
             } else {
-    			Display::display_error_message(get_lang('UploadError'));
+                Display::display_error_message(get_lang('UploadError'));
                 echo '<a class="btn" href="import_backup.php?'.api_get_cidreq().'">'.get_lang('TryAgain').'</a>';
             }
-		}
-	}
-	CourseArchiver::clean_backup_dir();
+        }
+    }
+    CourseArchiver::clean_backup_dir();
 } elseif (isset($_POST['import_option']) && $_POST['import_option'] == 'select_items') {
-	if ($_POST['backup_type'] == 'server') {
-		$filename = $_POST['backup_server'];
-		$delete_file = false;
-	} else {
-		$filename = CourseArchiver::import_uploaded_file($_FILES['backup']['tmp_name']);
-		$delete_file = true;
-	}
-	$course = CourseArchiver::read_course($filename, $delete_file);
-  
-	if ($course->has_resources() && ($filename !== false)) {
-		CourseSelectForm::display_form($course, array('same_file_name_option' => $_POST['same_file_name_option']));
-	} elseif ($filename === false) {
-    	Display::display_error_message(get_lang('ArchivesDirectoryNotWriteableContactAdmin'));
+    if ($_POST['backup_type'] == 'server') {
+        $filename = $_POST['backup_server'];
+        $delete_file = false;
+    } else {
+        $filename = CourseArchiver::import_uploaded_file($_FILES['backup']['tmp_name']);
+        $delete_file = true;
+    }
+    $course = CourseArchiver::read_course($filename, $delete_file);
+
+    if ($course->has_resources() && ($filename !== false)) {
+        CourseSelectForm::display_form($course, array('same_file_name_option' => $_POST['same_file_name_option']));
+    } elseif ($filename === false) {
+        Display::display_error_message(get_lang('ArchivesDirectoryNotWriteableContactAdmin'));
         echo '<a class="btn" href="import_backup.php?'.api_get_cidreq().'">'.get_lang('TryAgain').'</a>';
     } else {
-		Display::display_warning_message(get_lang('NoResourcesInBackupFile'));
+        Display::display_warning_message(get_lang('NoResourcesInBackupFile'));
         echo '<a class="btn" href="import_backup.php?'.api_get_cidreq().'">'.get_lang('TryAgain').'</a>';
-	}
+    }
 } else {
-	$user = api_get_user_info();
-	$backups = CourseArchiver::get_available_backups($is_platformAdmin ?null:$user['user_id']);
-	$backups_available = count($backups) > 0;
+    $user = api_get_user_info();
+    $backups = CourseArchiver::get_available_backups($is_platformAdmin ? null : $user['user_id']);
+    $backups_available = count($backups) > 0;
 
-	$form = new FormValidator('import_backup_form', 'post', 'import_backup.php', '', 'multipart/form-data');
+    $form = new FormValidator('import_backup_form', 'post', 'import_backup.php', '', 'multipart/form-data');
     $form->addElement('header', get_lang('SelectBackupFile'));
-	$renderer = $form->defaultRenderer();
-	$renderer->setElementTemplate('<div>{element}</div> ');
-
-	$form->addElement('hidden', 'action', 'restore_backup');
-
-	$form->addElement('radio', 'backup_type', '', get_lang('LocalFile'), 'local', 'id="bt_local" class="checkbox" onclick="javascript: document.import_backup_form.backup_server.disabled=true;document.import_backup_form.backup.disabled=false;"');
-	$form->addElement('file', 'backup', '', 'style="margin-left: 50px;"');
-	$form->addElement('html', '<br />');
-
-	if ($backups_available) {
-		$form->addElement('radio', 'backup_type', '', get_lang('ServerFile'), 'server', 'id="bt_server" class="checkbox" onclick="javascript: document.import_backup_form.backup_server.disabled=false;document.import_backup_form.backup.disabled=true;"');
-		$options['null'] = '-';
-		foreach ($backups as $index => $backup) {
-			$options[$backup['file']] = $backup['course_code'].' ('.$backup['date'].')';
-		}
-		$form->addElement('select', 'backup_server', '', $options, 'style="margin-left: 50px;"');
-		$form->addElement('html', '<script type="text/javascript">document.import_backup_form.backup_server.disabled=true;</script>');
-	} else {
-		$form->addElement('radio', '', '', '<i>'.get_lang('NoBackupsAvailable').'</i>', '', 'disabled="true"');
-	}
-
-	$form->addElement('html', '<br /><br />');
-
-	$form->addElement('radio', 'import_option', '', get_lang('ImportFullBackup'), 'full_backup', 'id="import_option_1" class="checkbox"');
-	$form->addElement('radio', 'import_option', '', get_lang('LetMeSelectItems'), 'select_items', 'id="import_option_2" class="checkbox"');
-
-	$form->addElement('html', '<br /><br />');
-
-	$form->addElement('html', get_lang('SameFilename'));
-	$form->addElement('html', '<br /><br />');
-	$form->addElement('radio', 'same_file_name_option', '', get_lang('SameFilenameSkip'), FILE_SKIP, 'id="same_file_name_option_1" class="checkbox"');
-	$form->addElement('radio', 'same_file_name_option', '', get_lang('SameFilenameRename'), FILE_RENAME, 'id="same_file_name_option_2" class="checkbox"');
-	$form->addElement('radio', 'same_file_name_option', '', get_lang('SameFilenameOverwrite'), FILE_OVERWRITE, 'id="same_file_name_option_3" class="checkbox"');
-
-	$form->addElement('html', '<br />');
-	$form->addElement('style_submit_button', null, get_lang('ImportBackup'), 'class="save"');
-
-	$values['backup_type'] = 'local';
-	$values['import_option'] = 'full_backup';
-	$values['same_file_name_option'] = FILE_OVERWRITE;
-	$form->setDefaults($values);
-
-	$form->add_progress_bar();
-	// When progress bar appears we have to hide the title "Select backup file".
-	$form->updateAttributes(array('onsubmit' => str_replace('javascript: ', 'javascript: page_title = getElementById(\'page_title\'); if (page_title) { setTimeout(\'page_title.style.display = \\\'none\\\';\', 2000); } ', $form->getAttribute('onsubmit'))));
-
-	$form->display();
+    $renderer = $form->defaultRenderer();
+    $renderer->setElementTemplate('<div>{element}</div> ');
+
+    $form->addElement('hidden', 'action', 'restore_backup');
+
+    $form->addElement(
+        'radio',
+        'backup_type',
+        '',
+        get_lang('LocalFile'),
+        'local',
+        'id="bt_local" class="checkbox" onclick="javascript: document.import_backup_form.backup_server.disabled=true;document.import_backup_form.backup.disabled=false;"'
+    );
+    $form->addElement('file', 'backup', '', 'style="margin-left: 50px;"');
+    $form->addElement('html', '<br />');
+
+    if ($backups_available) {
+        $form->addElement(
+            'radio',
+            'backup_type',
+            '',
+            get_lang('ServerFile'),
+            'server',
+            'id="bt_server" class="checkbox" onclick="javascript: document.import_backup_form.backup_server.disabled=false;document.import_backup_form.backup.disabled=true;"'
+        );
+        $options['null'] = '-';
+        foreach ($backups as $index => $backup) {
+            $options[$backup['file']] = $backup['course_code'].' ('.$backup['date'].')';
+        }
+        $form->addElement('select', 'backup_server', '', $options, 'style="margin-left: 50px;"');
+        $form->addElement(
+            'html',
+            '<script type="text/javascript">document.import_backup_form.backup_server.disabled=true;</script>'
+        );
+    } else {
+        $form->addElement('radio', '', '', '<i>'.get_lang('NoBackupsAvailable').'</i>', '', 'disabled="true"');
+    }
+
+    $form->addElement('html', '<br /><br />');
+
+    $form->addElement(
+        'radio',
+        'import_option',
+        '',
+        get_lang('ImportFullBackup'),
+        'full_backup',
+        'id="import_option_1" class="checkbox"'
+    );
+    $form->addElement(
+        'radio',
+        'import_option',
+        '',
+        get_lang('LetMeSelectItems'),
+        'select_items',
+        'id="import_option_2" class="checkbox"'
+    );
+
+    $form->addElement('html', '<br /><br />');
+
+    $form->addElement('html', get_lang('SameFilename'));
+    $form->addElement('html', '<br /><br />');
+    $form->addElement(
+        'radio',
+        'same_file_name_option',
+        '',
+        get_lang('SameFilenameSkip'),
+        FILE_SKIP,
+        'id="same_file_name_option_1" class="checkbox"'
+    );
+    $form->addElement(
+        'radio',
+        'same_file_name_option',
+        '',
+        get_lang('SameFilenameRename'),
+        FILE_RENAME,
+        'id="same_file_name_option_2" class="checkbox"'
+    );
+    $form->addElement(
+        'radio',
+        'same_file_name_option',
+        '',
+        get_lang('SameFilenameOverwrite'),
+        FILE_OVERWRITE,
+        'id="same_file_name_option_3" class="checkbox"'
+    );
+
+    $form->addElement('html', '<br />');
+    $form->addElement('style_submit_button', null, get_lang('ImportBackup'), 'class="save"');
+
+    $values['backup_type'] = 'local';
+    $values['import_option'] = 'full_backup';
+    $values['same_file_name_option'] = FILE_OVERWRITE;
+    $form->setDefaults($values);
+
+    $form->add_progress_bar();
+    // When progress bar appears we have to hide the title "Select backup file".
+    $form->updateAttributes(
+        array(
+            'onsubmit' => str_replace(
+                'javascript: ',
+                'javascript: page_title = getElementById(\'page_title\'); if (page_title) { setTimeout(\'page_title.style.display = \\\'none\\\';\', 2000); } ',
+                $form->getAttribute('onsubmit')
+            )
+        )
+    );
+
+    $form->display();
 }
 
 /*	FOOTER */

+ 85 - 38
main/create_course/add_course.php

@@ -16,7 +16,7 @@
  */
 
 // Name of the language file that needs to be included.
-$language_file = array('create_course', 'registration','admin','exercice', 'course_description', 'course_info');
+$language_file = array('create_course', 'registration', 'admin', 'exercice', 'course_description', 'course_info');
 
 // Flag forcing the "current course" reset.
 $cidReset = true;
@@ -32,9 +32,6 @@ $this_section = SECTION_COURSES;
 // false - the new course is created immedialely, after filling this form.
 $course_validation_feature = api_get_setting('course_validation') == 'true';
 
-// Require additional libraries.
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 if ($course_validation_feature) {
     require_once api_get_path(LIBRARY_PATH).'course_request.lib.php';
 }
@@ -50,10 +47,14 @@ $htmlHeadXtra[] = '<script type="text/javascript">
     function advanced_parameters() {
         if(document.getElementById(\'options\').style.display == \'none\') {
             document.getElementById(\'options\').style.display = \'block\';
-            document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
+            document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" />&nbsp;'.get_lang(
+    'AdvancedParameters'
+).'\';
         } else {
             document.getElementById(\'options\').style.display = \'none\';
-            document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'\';
+            document.getElementById(\'img_plus_and_minus\').innerHTML=\'&nbsp;<img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang(
+    'AdvancedParameters'
+).'\';
         }
     }
 </script>';
@@ -82,23 +83,41 @@ $form = new FormValidator('add_course');
 $form->addElement('header', $tool_name);
 
 // Title
-$form->addElement('text', 'title', array(get_lang('CourseName'), get_lang('Ex')), array('class' => 'span6', 'id' => 'title'));
+$form->addElement(
+    'text',
+    'title',
+    array(get_lang('CourseName'), get_lang('Ex')),
+    array('class' => 'span6', 'id' => 'title')
+);
 $form->applyFilter('title', 'html_filter');
 $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
 
-$advanced = '<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>';
-$form -> addElement('advanced_settings',$advanced);
-$form -> addElement('html','<div id="options" style="display:none">');
+$advanced = '<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>';
+$form->addElement('advanced_settings', $advanced);
+$form->addElement('html', '<div id="options" style="display:none">');
 
 // Course category.
-$categories_select = $form->addElement('select', 'category_code', array(get_lang('Fac'), get_lang('TargetFac')), array(), array('id'=> 'category_code','class'=>'chzn-select', 'style'=>'width:350px'));
+$categories_select = $form->addElement(
+    'select',
+    'category_code',
+    array(get_lang('Fac'), get_lang('TargetFac')),
+    array(),
+    array('id' => 'category_code', 'class' => 'chzn-select', 'style' => 'width:350px')
+);
 $form->applyFilter('category_code', 'html_filter');
-$categories_select->addOption('-','');
+$categories_select->addOption('-', '');
 CourseManager::select_and_sort_categories($categories_select);
 
 
 // Course code
-$form->add_textfield('wanted_code', array(get_lang('Code'), get_lang('OnlyLettersAndNumbers')), '', array('class' => 'span3', 'maxlength' => CourseManager::MAX_COURSE_LENGTH_CODE));
+$form->add_textfield(
+    'wanted_code',
+    array(get_lang('Code'), get_lang('OnlyLettersAndNumbers')),
+    '',
+    array('class' => 'span3', 'maxlength' => CourseManager::MAX_COURSE_LENGTH_CODE)
+);
 $form->applyFilter('wanted_code', 'html_filter');
 $form->addRule('wanted_code', get_lang('Max'), 'maxlength', CourseManager::MAX_COURSE_LENGTH_CODE);
 
@@ -108,7 +127,11 @@ $form->addRule('wanted_code', get_lang('Max'), 'maxlength', CourseManager::MAX_C
 
 // The teacher
 //get_lang('ExplicationTrainers')
-$titular = & $form->addElement('hidden', 'tutor_name', ''); //array(get_lang('Professor'), null), null, array('size' => '60', 'disabled' => 'disabled'));
+$titular = & $form->addElement(
+    'hidden',
+    'tutor_name',
+    ''
+); //array(get_lang('Professor'), null), null, array('size' => '60', 'disabled' => 'disabled'));
 //$form->applyFilter('tutor_name', 'html_filter');
 
 if ($course_validation_feature) {
@@ -122,12 +145,17 @@ if ($course_validation_feature) {
     //$form->addRule('objetives', get_lang('ThisFieldIsRequired'), 'required');
 
     // Target audience of the requested course.
-    $form->addElement('textarea', 'target_audience', get_lang('TargetAudience'), array('class' => 'span6', 'rows' => '3'));
+    $form->addElement(
+        'textarea',
+        'target_audience',
+        get_lang('TargetAudience'),
+        array('class' => 'span6', 'rows' => '3')
+    );
     //$form->addRule('target_audience', get_lang('ThisFieldIsRequired'), 'required');
 }
 
 // Course language.
-$form->addElement('select_language', 'course_language', get_lang('Ln'), array(), array('style'=>'width:150px'));
+$form->addElement('select_language', 'course_language', get_lang('Ln'), array(), array('style' => 'width:150px'));
 $form->applyFilter('select_language', 'html_filter');
 
 // Exemplary content checkbox.
@@ -165,10 +193,15 @@ if ($course_validation_feature) {
 $obj = new GradeModel();
 $obj->fill_grade_model_select_in_form($form);
 
-$form->addElement('html','</div>');
+$form->addElement('html', '</div>');
 
 // Submit button.
-$form->addElement('button', 'submit', $course_validation_feature ? get_lang('CreateThisCourseRequest') : get_lang('CreateCourseArea'), 'class="add"');
+$form->addElement(
+    'button',
+    'submit',
+    $course_validation_feature ? get_lang('CreateThisCourseRequest') : get_lang('CreateCourseArea'),
+    'class="add"'
+);
 
 // The progress bar of this form.
 $form->add_progress_bar();
@@ -187,21 +220,23 @@ $message = null;
 if ($form->validate()) {
     $course_values = $form->exportValues();
 
-    $wanted_code        = $course_values['wanted_code'];
+    $wanted_code = $course_values['wanted_code'];
     //$tutor_name         = $course_values['tutor_name'];
-    $category_code      = $course_values['category_code'];
-    $title              = $course_values['title'];
-    $course_language    = $course_values['course_language'];
-    $exemplary_content  = !empty($course_values['exemplary_content']);
+    $category_code = $course_values['category_code'];
+    $title = $course_values['title'];
+    $course_language = $course_values['course_language'];
+    $exemplary_content = !empty($course_values['exemplary_content']);
 
     if ($course_validation_feature) {
-        $description     = $course_values['description'];
-        $objetives       = $course_values['objetives'];
+        $description = $course_values['description'];
+        $objetives = $course_values['objetives'];
         $target_audience = $course_values['target_audience'];
     }
 
     if ($wanted_code == '') {
-        $wanted_code = CourseManager::generate_course_code(api_substr($title, 0, CourseManager::MAX_COURSE_LENGTH_CODE));
+        $wanted_code = CourseManager::generate_course_code(
+            api_substr($title, 0, CourseManager::MAX_COURSE_LENGTH_CODE)
+        );
     }
 
     // Check whether the requested course code has already been occupied.
@@ -215,19 +250,19 @@ if ($form->validate()) {
         if (!$course_validation_feature) {
 
             $params = array();
-            $params['title']                = $title;
-            $params['exemplary_content']    = $exemplary_content;
-            $params['wanted_code']          = $wanted_code;
-            $params['category_code']        = $category_code;
-            $params['course_language']      = $course_language;
-            $params['gradebook_model_id']   = isset($course_values['gradebook_model_id']) ? $course_values['gradebook_model_id'] : null;
+            $params['title'] = $title;
+            $params['exemplary_content'] = $exemplary_content;
+            $params['wanted_code'] = $wanted_code;
+            $params['category_code'] = $category_code;
+            $params['course_language'] = $course_language;
+            $params['gradebook_model_id'] = isset($course_values['gradebook_model_id']) ? $course_values['gradebook_model_id'] : null;
 
             $course_info = CourseManager::create_course($params);
 
             if (!empty($course_info)) {
 
-                $directory  = $course_info['directory'];
-                $title      = $course_info['title'];
+                $directory = $course_info['directory'];
+                $title = $course_info['title'];
 
                 // Preparing a confirmation message.
                 $link = api_get_path(WEB_COURSE_PATH).$directory.'/';
@@ -246,14 +281,26 @@ if ($form->validate()) {
             }
         } else {
             // Create a request for a new course.
-            $request_id = CourseRequestManager::create_course_request($wanted_code, $title, $description, $category_code, $course_language, $objetives, $target_audience, api_get_user_id(), $exemplary_content);
+            $request_id = CourseRequestManager::create_course_request(
+                $wanted_code,
+                $title,
+                $description,
+                $category_code,
+                $course_language,
+                $objetives,
+                $target_audience,
+                api_get_user_id(),
+                $exemplary_content
+            );
 
             if ($request_id) {
                 $course_request_info = CourseRequestManager::get_course_request_info($request_id);
-                $message = (is_array($course_request_info) ? '<strong>'.$course_request_info['code'].'</strong> : ' : '').get_lang('CourseRequestCreated');
+                $message = (is_array(
+                    $course_request_info
+                ) ? '<strong>'.$course_request_info['code'].'</strong> : ' : '').get_lang('CourseRequestCreated');
                 $message = Display :: return_message($message, 'confirmation', false);
-                $message .=  '<div style="float: left; margin:0px; padding: 0px;">' .
-                    '<a class="btn" href="'.api_get_path(WEB_PATH).'user_portal.php">'.get_lang('Enter').'</a>' .
+                $message .= '<div style="float: left; margin:0px; padding: 0px;">'.
+                    '<a class="btn" href="'.api_get_path(WEB_PATH).'user_portal.php">'.get_lang('Enter').'</a>'.
                     '</div>';
             } else {
                 $message = Display :: return_message(get_lang('CourseRequestCreationFailed'), 'error', false);

+ 645 - 435
main/document/create_audio.php

@@ -2,14 +2,14 @@
 /* For licensing terms, see /license.txt */
 
 /**
- *	This file allows creating audio files from a text.
+ *    This file allows creating audio files from a text.
  *
- *	@package chamilo.document
+ * @package chamilo.document
  *
  * @author Juan Carlos Raña Trabado
  * @since 8/January/2011
  * TODO:clean all file
-*/
+ */
 /**
  * Code
  */
@@ -27,16 +27,16 @@ $nameTools = get_lang('CreateAudio');
 
 api_protect_course_script();
 api_block_anonymous_users();
-if (api_get_setting('enabled_text2audio') == 'false'){
-	api_not_allowed(true);
+if (api_get_setting('enabled_text2audio') == 'false') {
+    api_not_allowed(true);
 }
 
 $document_data = DocumentManager::get_document_data_by_id($_GET['id'], api_get_course_id());
 if (empty($document_data)) {
     if (api_is_in_group()) {
-        $group_properties   = GroupManager::get_group_properties(api_get_group_id());        
-        $document_id        = DocumentManager::get_document_id(api_get_course_info(), $group_properties['directory']);
-        $document_data      = DocumentManager::get_document_data_by_id($document_id, api_get_course_id());
+        $group_properties = GroupManager::get_group_properties(api_get_group_id());
+        $document_id = DocumentManager::get_document_id(api_get_course_info(), $group_properties['directory']);
+        $document_data = DocumentManager::get_document_data_by_id($document_id, api_get_course_id());
     }
 }
 $document_id = $document_data['id'];
@@ -49,50 +49,61 @@ $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
 // Please, do not modify this dirname formatting
 
 if (strstr($dir, '..')) {
-	$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 .= '/';
+    $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 = '/';
 }
 
 //groups //TODO: clean
 if (isset ($_SESSION['_gid']) && $_SESSION['_gid'] != 0) {
-	$req_gid = '&amp;gidReq='.$_SESSION['_gid'];
-	$interbreadcrumb[] = array ("url" => "../group/group_space.php?gidReq=".$_SESSION['_gid'], "name" => get_lang('GroupSpace'));
-	$noPHP_SELF = true;
-	$to_group_id = $_SESSION['_gid'];
-	$group = GroupManager :: get_group_properties($to_group_id);
-	$path = explode('/', $dir);
-	if ('/'.$path[1] != $group['directory']) {
-		api_not_allowed(true);
-	}
+    $req_gid = '&amp;gidReq='.$_SESSION['_gid'];
+    $interbreadcrumb[] = array(
+        "url" => "../group/group_space.php?gidReq=".$_SESSION['_gid'],
+        "name" => get_lang('GroupSpace')
+    );
+    $noPHP_SELF = true;
+    $to_group_id = $_SESSION['_gid'];
+    $group = GroupManager :: get_group_properties($to_group_id);
+    $path = explode('/', $dir);
+    if ('/'.$path[1] != $group['directory']) {
+        api_not_allowed(true);
+    }
 }
 
-$interbreadcrumb[] = array ("url" => "./document.php?curdirpath=".urlencode($dir).$req_gid, "name" => get_lang('Documents'));
+$interbreadcrumb[] = array(
+    "url" => "./document.php?curdirpath=".urlencode($dir).$req_gid,
+    "name" => get_lang('Documents')
+);
 
 if (!$is_allowed_in_course) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 
-if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || is_my_shared_folder(api_get_user_id(), Security::remove_XSS($dir),api_get_session_id()))) {
-	api_not_allowed(true);
+if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || is_my_shared_folder(
+    api_get_user_id(),
+    Security::remove_XSS($dir),
+    api_get_session_id()
+))
+) {
+    api_not_allowed(true);
 }
 
 
@@ -101,252 +112,301 @@ event_access_tool(TOOL_DOCUMENT);
 
 $display_dir = $dir;
 if (isset ($group)) {
-	$display_dir = explode('/', $dir);
-	unset ($display_dir[0]);
-	unset ($display_dir[1]);
-	$display_dir = implode('/', $display_dir);
+    $display_dir = explode('/', $dir);
+    unset ($display_dir[0]);
+    unset ($display_dir[1]);
+    $display_dir = implode('/', $display_dir);
 }
 
 // Interbreadcrumb for the current directory root path
-	// Copied from document.php
-	$dir_array = explode('/', $dir);
-	$array_len = count($dir_array);
-	
-	$dir_acum = '';
-	for ($i = 0; $i < $array_len; $i++) {
-		$url_dir = 'document.php?&curdirpath='.$dir_acum.$dir_array[$i];
-		//Max char 80
-		$url_to_who = cut($dir_array[$i],80);
-		if ($is_certificate_mode) {
-			$interbreadcrumb[] = array('url' => $url_dir.'&selectcat='.Security::remove_XSS($_GET['selectcat']), 'name' => $url_to_who);
-		} else {
-			$interbreadcrumb[] = array('url' => $url_dir, 'name' => $url_to_who);
-		}
-		$dir_acum .= $dir_array[$i].'/';
-	}
+// Copied from document.php
+$dir_array = explode('/', $dir);
+$array_len = count($dir_array);
+
+$dir_acum = '';
+for ($i = 0; $i < $array_len; $i++) {
+    $url_dir = 'document.php?&curdirpath='.$dir_acum.$dir_array[$i];
+    //Max char 80
+    $url_to_who = cut($dir_array[$i], 80);
+    if ($is_certificate_mode) {
+        $interbreadcrumb[] = array(
+            'url' => $url_dir.'&selectcat='.Security::remove_XSS($_GET['selectcat']),
+            'name' => $url_to_who
+        );
+    } else {
+        $interbreadcrumb[] = array('url' => $url_dir, 'name' => $url_to_who);
+    }
+    $dir_acum .= $dir_array[$i].'/';
+}
 
 Display :: display_header($nameTools, 'Doc');
 
 echo '<div class="actions">';
-		echo '<a href="document.php?id='.$document_id.'">'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('DocumentsOverview'),'',ICON_SIZE_MEDIUM).'</a>';
-		
-		echo '<a href="create_audio.php?'.api_get_cidreq().'&amp;id='.$document_id.'&amp;dt2a=google">'.Display::return_icon('google.png',get_lang('GoogleAudio'),'',ICON_SIZE_MEDIUM).'</a>';
-		
-		echo '<a href="create_audio.php?'.api_get_cidreq().'&amp;id='.$document_id.'&amp;dt2a=pediaphon">'.Display::return_icon('pediaphon.png', get_lang('Pediaphon'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '<a href="document.php?id='.$document_id.'">'.Display::return_icon(
+    'back.png',
+    get_lang('BackTo').' '.get_lang('DocumentsOverview'),
+    '',
+    ICON_SIZE_MEDIUM
+).'</a>';
+
+echo '<a href="create_audio.php?'.api_get_cidreq().'&amp;id='.$document_id.'&amp;dt2a=google">'.Display::return_icon(
+    'google.png',
+    get_lang('GoogleAudio'),
+    '',
+    ICON_SIZE_MEDIUM
+).'</a>';
+
+echo '<a href="create_audio.php?'.api_get_cidreq().'&amp;id='.$document_id.'&amp;dt2a=pediaphon">'.Display::return_icon(
+    'pediaphon.png',
+    get_lang('Pediaphon'),
+    '',
+    ICON_SIZE_MEDIUM
+).'</a>';
+
 
-		
 echo '</div>';
 
 ?>
 <!-- javascript and styles for textareaCounter-->
 <script type="text/javascript">
-var info;
-$(document).ready(function(){
-	var options = {
-		'maxCharacterSize': 100,
-		'originalStyle': 'originalTextareaInfo',
-		'warningStyle' : 'warningTextareaInfo',
-		'warningNumber': 20,
-		'displayFormat' : '#input/#max'
-	};
-	$('#textarea_google').textareaCount(options, function(data){
-		$('#textareaCallBack').html(data);				
-	});    
-});
-
-</script>		        
+    var info;
+    $(document).ready(function () {
+        var options = {
+            'maxCharacterSize':100,
+            'originalStyle':'originalTextareaInfo',
+            'warningStyle':'warningTextareaInfo',
+            'warningNumber':20,
+            'displayFormat':'#input/#max'
+        };
+        $('#textarea_google').textareaCount(options, function (data) {
+            $('#textareaCallBack').html(data);
+        });
+    });
+
+</script>
 <style>
-.overview {
-	background: #FFEC9D;
-	padding: 10px;
-	width: 90%;
-	border: 1px solid #CCCCCC;
-}
+    .overview {
+        background: #FFEC9D;
+        padding: 10px;
+        width: 90%;
+        border: 1px solid #CCCCCC;
+    }
+
+    .originalTextareaInfo {
+        font-size: 12px;
+        color: #000000;
+        text-align: right;
+    }
 
-.originalTextareaInfo {
-	font-size: 12px;
-	color: #000000;
-	text-align: right;
+    .warningTextareaInfo {
+        color: #FF0000;
+        font-weight: bold;
+        text-align: right;
+    }
+
+    #showData {
+        height: 70px;
+        width: 200px;
+        border: 1px solid #CCCCCC;
+        padding: 10px;
+        margin: 10px;
+    }
+</style>
+<div id="textareaCallBack"></div>
+<?php
+if (Security::remove_XSS($_POST['text2voice_mode']) == 'google') {
+    downloadMP3_google($filepath, $dir);
+} elseif (Security::remove_XSS($_POST['text2voice_mode']) == 'pediaphon') {
+    downloadMP3_pediaphon($filepath, $dir);
 }
 
-.warningTextareaInfo {
-	color: #FF0000;
-	font-weight:bold;
-	text-align: right;	
+$tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
+$sql_select = "SELECT * FROM $tbl_admin_languages";
+$result_select = Database::query($sql_select);
+
+$options = $options_pedia = array();
+$selected_language = null;
+$options_pedia['defaultmessage'] = get_lang('FirstSelectALanguage'); //need read before platform languages
+
+while ($row = Database::fetch_array($result_select)) {
+    if (api_get_setting('platformLanguage') == $row['english_name']) {
+        //$selected_language = $row['isocode'];//lang default is the default platform language
+    }
+
+    $options[$row['isocode']] = $row['original_name'].' ('.$row['english_name'].')';
+
+    if (in_array($row['isocode'], array('de', 'en', 'es', 'fr'))) {
+        $options_pedia[$row['isocode']] = $row['original_name'].' ('.$row['english_name'].')';
+    }
 }
 
-#showData {
-	height: 70px;
-	width: 200px;
-	border: 1px solid #CCCCCC;
-	padding: 10px;
-	margin: 10px;
+$icon = Display::return_icon('text2audio.png', get_lang('HelpText2Audio'), '', ICON_SIZE_MEDIUM);
+echo '<div class="page-header"><h2>'.$icon.get_lang('HelpText2Audio').'</h2></div>';
+
+
+if (Security::remove_XSS($_GET['dt2a']) == 'google') {
+    $selected_language = api_get_language_isocode(); //lang default is the course language
+    echo '<div>';
+    $form = new FormValidator('form1', 'post', null, '', array('id' => 'form1'));
+    $form->addElement('hidden', 'text2voice_mode', 'google');
+    $form->addElement('hidden', 'document_id', $document_id);
+    $form->addElement('text', 'title', get_lang('Title'));
+    $form->addElement('select', 'lang', get_lang('Language'), $options);
+    $form->addElement(
+        'textarea',
+        'text',
+        get_lang('InsertText2Audio'),
+        array('id' => 'textarea_google', 'class' => 'span6')
+    );
+    //echo Display :: return_icon('info3.gif', get_lang('HelpGoogleAudio'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
+    $form->addElement('style_submit_button', 'submit', get_lang('SaveMP3'), 'class="save"');
+    $defaults = array();
+    $defaults['lang'] = $selected_language;
+    $form->setDefaults($defaults);
+    $form->display();
+
+    echo '</div>';
 }
-</style>
-<div id="textareaCallBack"></div>
+
+if (Security::remove_XSS($_GET['dt2a']) == 'pediaphon') {
+    //lang default is a default message
+    $selected_language = "defaultmessage";
+
+    $options['defaultmessage'] = get_lang('FirstSelectALanguage');
+    echo '<div>';
+
+    $form = new FormValidator('form2', 'post', null, '', array('id' => 'form2'));
+    $form->addElement('hidden', 'text2voice_mode', 'pediaphon');
+    $form->addElement('hidden', 'document_id', $document_id);
+    $form->addElement('text', 'title', get_lang('Title'));
+    $form->addElement(
+        'select',
+        'lang',
+        get_lang('Language'),
+        $options_pedia,
+        array('onclick' => 'update_voices(this.selectedIndex);')
+    );
+    $form->addElement('select', 'voices', get_lang('Voice'), array(get_lang('FirstSelectALanguage')), array());
+    $speed_options = array();
+    $speed_options['1'] = get_lang('Normal');
+    $speed_options['0.75'] = get_lang('GoFaster');
+    $speed_options['0.8'] = get_lang('Fast');
+    $speed_options['1.2'] = get_lang('Slow');
+    $speed_options['1.6'] = get_lang('SlowDown');
+
+    $form->addElement('select', 'speed', get_lang('Speed'), $speed_options, array());
+    $form->addElement(
+        'textarea',
+        'text',
+        get_lang('InsertText2Audio'),
+        array('id' => 'textarea_pediaphon', 'class' => 'span6')
+    );
+    //echo Display :: return_icon('info3.gif', get_lang('HelpPediaphon'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
+
+    $form->addElement('style_submit_button', 'submit', get_lang('SaveMP3'), 'class="save"');
+    $defaults = array();
+    $defaults['lang'] = $selected_language;
+    $form->setDefaults($defaults);
+    $form->display();
+    echo '</div>';
+
+    ?>
+
+<!-- javascript form name form2 update voices -->
+<script type="text/javascript">
+    var langslist = document.form2.lang
+    var voiceslist = document.form2.voices
+    var voices = new Array()
+
+            < !--Default
+    message-- >
+            voices[0] = ["<?php echo get_lang('FirstSelectALanguage'); ?>"]
+
+            < !--German-- >
+            voices[1] = ["<?php echo get_lang('Female').' (de1)'; ?>|de1", "<?php echo get_lang(
+        'Male'
+    ).' (de2)'; ?>|de2", "<?php echo get_lang('Female').' (de3)'; ?>|de3", "<?php echo get_lang(
+        'Male'
+    ).' (de4)'; ?>|de4", "<?php echo get_lang('Female').' (de5)'; ?>|de5", "<?php echo get_lang(
+        'Male'
+    ).' (de6)'; ?>|de6", "<?php echo get_lang('Female').' (de7)'; ?>|de7", "<?php echo get_lang(
+        'Female'
+    ).' (de8 HQ)'; ?>|de8"]
+
+            < !--English-- >
+            voices[2] = ["<?php echo get_lang('Male').' (en1)'; ?>|en1", "<?php echo get_lang(
+        'Male'
+    ).' (en2 HQ)'; ?>|en2", "<?php echo get_lang('Female').' (us1)'; ?>| us1", "<?php echo get_lang(
+        'Male'
+    ).' (us2)'; ?>|us2", "<?php echo get_lang('Male').' (us3)'; ?>|us3", "<?php echo get_lang(
+        'Female'
+    ).'(us4 HQ)'; ?>|us4"]
+
+            < !--Spanish-- >
+            voices[3] = ["<?php echo get_lang('Male').' (es5 HQ)'; ?>|es5"]
+
+            < !--French-- >
+            voices[4] = ["<?php echo get_lang('Female').' (fr8 HQ)'; ?>|fr8"]
+
+
+    function update_voices(selectedvoicegroup) {
+        voiceslist.options.length = 0
+        for (i = 0; i < voices[selectedvoicegroup].length; i++)
+            voiceslist.options[voiceslist.options.length] = new Option(voices[selectedvoicegroup][i].split("|")[0], voices[selectedvoicegroup][i].split("|")[1])
+    }
+</script>
+
+
 <?php
-	if(Security::remove_XSS($_POST['text2voice_mode'])=='google'){  
-    	downloadMP3_google($filepath, $dir);
-	}
-	elseif(Security::remove_XSS($_POST['text2voice_mode'])=='pediaphon'){   
-    	downloadMP3_pediaphon($filepath, $dir);
-	}
-    
-    $tbl_admin_languages    = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
+}
+//end pediaphon
+
+//vozMe services
+//disabled for a time
+/*
+echo '<div>&nbsp;</div><input type="checkbox" value="1" name="checktext2voice" onclick="javascript: if(this.checked){document.getElementById(\'option3\').style.display=\'block\';}else{document.getElementById(\'option3\').style.display=\'none\';}"/>&nbsp;<img src="../img/file_sound.gif" title="'.get_lang('HelpvozMe').'" alt="'.get_lang('vozMe').'"/>&nbsp;'.get_lang('vozMe').'';
+echo '&nbsp;&nbsp;&nbsp;<span id="msg_error3" style="display:none;color:red"></span>';
+echo '<div id="option3" style="padding:4px; margin:5px; border:1px dotted; display:none;">';
+
+echo '<form id="form3" name="form3" method="post" action="http://vozme.com/text2voice.php" target="mymp3" class="formw">';
+    echo '<br/>';
+    echo '<label>'.get_lang('Language').': ';
+    $tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
     $sql_select = "SELECT * FROM $tbl_admin_languages";
-    $result_select = Database::query($sql_select);              
-
-    $options = $options_pedia = array();
-    $selected_language = null;
-	$options_pedia['defaultmessage'] = get_lang('FirstSelectALanguage');//need read before platform languages
-	
-    while ($row = Database::fetch_array($result_select)) {       
-        if (api_get_setting('platformLanguage')==$row['english_name']) {        
-            //$selected_language = $row['isocode'];//lang default is the default platform language
+    $result_select = Database::query($sql_select);
+    echo '<select name="lang" id="select">';
+    while ($row = Database::fetch_array($result_select)) {
+
+        if (in_array($row['isocode'], array('ca', 'en', 'es', 'hi', 'it', 'pt'))){
+
+            if (api_get_setting('platformLanguage')==$row['english_name']){
+                echo '<option value="'.$row['isocode'].'" selected="selected">'.$row['original_name'].' ('.$row['english_name'].')</option>';
+            }
+            else{
+                echo '<option value="'.$row['isocode'].'">'.$row['original_name'].' ('.$row['english_name'].')</option>';
+            }
         }
-		
-        $options[$row['isocode']] =$row['original_name'].' ('.$row['english_name'].')';
-
-        if (in_array($row['isocode'], array('de', 'en', 'es', 'fr'))){		
-            $options_pedia[$row['isocode']] =$row['original_name'].' ('.$row['english_name'].')';
-        }        
     }
-	
-	$icon = Display::return_icon('text2audio.png', get_lang('HelpText2Audio'),'',ICON_SIZE_MEDIUM);
-	echo '<div class="page-header"><h2>'.$icon.get_lang('HelpText2Audio').'</h2></div>'; 
-	
-  
-    if(Security::remove_XSS($_GET['dt2a'])=='google'){
-		$selected_language = api_get_language_isocode();//lang default is the course language
-		echo '<div>';
-		$form = new FormValidator('form1', 'post', null, '', array('id' => 'form1'));
-		$form->addElement('hidden', 'text2voice_mode', 'google');
-		$form->addElement('hidden', 'document_id', $document_id);
-		$form->addElement('text', 'title', get_lang('Title'));
-		$form->addElement('select', 'lang', get_lang('Language'), $options);    
-		$form->addElement('textarea', 'text', get_lang('InsertText2Audio'), array('id' => 'textarea_google', 'class' =>'span6' ));
-		//echo Display :: return_icon('info3.gif', get_lang('HelpGoogleAudio'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
-		$form->addElement('style_submit_button', 'submit', get_lang('SaveMP3'), 'class="save"');
-		$defaults = array();
-		$defaults['lang'] = $selected_language;   
-		$form->setDefaults($defaults);        
-		$form->display();
-
-		echo '</div>';
-	}
-	
-	if(Security::remove_XSS($_GET['dt2a'])=='pediaphon'){
-		//lang default is a default message
-		$selected_language = "defaultmessage";
-		
-		$options['defaultmessage'] = get_lang('FirstSelectALanguage'); 
-		echo '<div>';
-		
-		$form = new FormValidator('form2', 'post', null, '', array('id' => 'form2'));
-		$form->addElement('hidden', 'text2voice_mode','pediaphon');
-		$form->addElement('hidden', 'document_id', $document_id);
-		$form->addElement('text', 'title', get_lang('Title'));
-		$form->addElement('select', 'lang', get_lang('Language'), $options_pedia, array('onclick' => 'update_voices(this.selectedIndex);'));
-		$form->addElement('select', 'voices', get_lang('Voice'), array(get_lang('FirstSelectALanguage')), array());            
-		$speed_options = array();
-		$speed_options['1']     = get_lang('Normal');
-		$speed_options['0.75']  = get_lang('GoFaster');
-		$speed_options['0.8']   = get_lang('Fast');
-		$speed_options['1.2']   = get_lang('Slow');
-		$speed_options['1.6']   = get_lang('SlowDown');
-		
-		$form->addElement('select', 'speed', get_lang('Speed'), $speed_options, array());        
-		$form->addElement('textarea', 'text', get_lang('InsertText2Audio'), array('id' => 'textarea_pediaphon', 'class' =>'span6'));
-		//echo Display :: return_icon('info3.gif', get_lang('HelpPediaphon'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
-		    
-		$form->addElement('style_submit_button', 'submit', get_lang('SaveMP3'), 'class="save"');
-		$defaults = array();
-		$defaults['lang'] = $selected_language;    
-		$form->setDefaults($defaults);        
-		$form->display();
-		echo '</div>';
-		
-		?>
-		
-		<!-- javascript form name form2 update voices -->
-		<script type="text/javascript">      
-		var langslist=document.form2.lang
-		var voiceslist=document.form2.voices     
-		var voices=new Array()
-		
-		<!--Default message -->
-		voices[0]=["<?php echo get_lang('FirstSelectALanguage'); ?>"]
-		
-		<!--German -->
-		voices[1]=["<?php echo get_lang('Female').' (de1)'; ?>|de1", "<?php echo get_lang('Male').' (de2)'; ?>|de2", "<?php echo get_lang('Female').' (de3)'; ?>|de3", "<?php echo get_lang('Male').' (de4)'; ?>|de4", "<?php echo get_lang('Female').' (de5)'; ?>|de5", "<?php echo get_lang('Male').' (de6)'; ?>|de6", "<?php echo get_lang('Female').' (de7)'; ?>|de7", "<?php echo get_lang('Female').' (de8 HQ)'; ?>|de8"]
-		
-		<!--English -->
-		voices[2]=["<?php echo get_lang('Male').' (en1)'; ?>|en1", "<?php echo get_lang('Male').' (en2 HQ)'; ?>|en2", "<?php echo get_lang('Female').' (us1)'; ?>| us1", "<?php echo get_lang('Male').' (us2)'; ?>|us2", "<?php echo get_lang('Male').' (us3)'; ?>|us3", "<?php echo get_lang('Female').'(us4 HQ)'; ?>|us4"]	
-		
-		<!--Spanish -->
-		voices[3]=["<?php echo get_lang('Male').' (es5 HQ)'; ?>|es5"]
-		
-		<!--French -->
-		voices[4]=["<?php echo get_lang('Female').' (fr8 HQ)'; ?>|fr8"]
-			
-			 
-		function update_voices(selectedvoicegroup){
-		voiceslist.options.length=0
-		for (i=0; i<voices[selectedvoicegroup].length; i++)
-			voiceslist.options[voiceslist.options.length]=new Option(voices[selectedvoicegroup][i].split("|")[0], voices[selectedvoicegroup][i].split("|")[1])
-		}
-		</script>    
-
-     
-    <?php
-	}//end pediaphon
-	
-	//vozMe services
-		//disabled for a time
-	/*
-	echo '<div>&nbsp;</div><input type="checkbox" value="1" name="checktext2voice" onclick="javascript: if(this.checked){document.getElementById(\'option3\').style.display=\'block\';}else{document.getElementById(\'option3\').style.display=\'none\';}"/>&nbsp;<img src="../img/file_sound.gif" title="'.get_lang('HelpvozMe').'" alt="'.get_lang('vozMe').'"/>&nbsp;'.get_lang('vozMe').'';
-	echo '&nbsp;&nbsp;&nbsp;<span id="msg_error3" style="display:none;color:red"></span>';
-	echo '<div id="option3" style="padding:4px; margin:5px; border:1px dotted; display:none;">';
-	
-	echo '<form id="form3" name="form3" method="post" action="http://vozme.com/text2voice.php" target="mymp3" class="formw">';
-		echo '<br/>';
-		echo '<label>'.get_lang('Language').': ';
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-		$sql_select = "SELECT * FROM $tbl_admin_languages";
-		$result_select = Database::query($sql_select);		
-		echo '<select name="lang" id="select">';
-		while ($row = Database::fetch_array($result_select)) {
-			
-			if (in_array($row['isocode'], array('ca', 'en', 'es', 'hi', 'it', 'pt'))){
-			
-				if (api_get_setting('platformLanguage')==$row['english_name']){
-					echo '<option value="'.$row['isocode'].'" selected="selected">'.$row['original_name'].' ('.$row['english_name'].')</option>';
-				}
-				else{					
-					echo '<option value="'.$row['isocode'].'">'.$row['original_name'].' ('.$row['english_name'].')</option>';
-				}
-			}
-		}
-		echo '</select>';
-		echo '</label>';
-		echo '<label>&nbsp;&nbsp;'.get_lang('Voice').': ';
-		echo '<select name="gn" id="select1">';
-		echo '<option value="ml">'.get_lang('Male').'</option>';
-		echo '<option value="fm">'.get_lang('Female').'</option>';
-		echo '</select>';
-		echo '</label>';
-		echo '<br/><br/>';
-		echo '<div>'.get_lang('InsertText2Audio').'</div>';
-		echo '<br/>';
-		echo '<label>';
-		echo '<textarea name="text" id="textarea" cols="70" rows="10"></textarea>';
-		echo '</label>';  
-		echo '<br/><br/>';  
-		echo '<button class="save" type="submit" name="SendText2Audio">'.get_lang('BuildMP3').'</button>';
-		echo '<br/>';
-	echo '</form>';
-	echo '</div>';
-	*/
+    echo '</select>';
+    echo '</label>';
+    echo '<label>&nbsp;&nbsp;'.get_lang('Voice').': ';
+    echo '<select name="gn" id="select1">';
+    echo '<option value="ml">'.get_lang('Male').'</option>';
+    echo '<option value="fm">'.get_lang('Female').'</option>';
+    echo '</select>';
+    echo '</label>';
+    echo '<br/><br/>';
+    echo '<div>'.get_lang('InsertText2Audio').'</div>';
+    echo '<br/>';
+    echo '<label>';
+    echo '<textarea name="text" id="textarea" cols="70" rows="10"></textarea>';
+    echo '</label>';
+    echo '<br/><br/>';
+    echo '<button class="save" type="submit" name="SendText2Audio">'.get_lang('BuildMP3').'</button>';
+    echo '<br/>';
+echo '</form>';
+echo '</div>';
+*/
 echo '</div>';
 
 Display :: display_footer();
@@ -361,87 +421,163 @@ Display :: display_footer();
  * @author Juan Carlos Raña Trabado <herodoto@telefonica.net>
  * @version january 2011, chamilo 1.8.8
  */
-function downloadMP3_google($filepath, $dir) {
-	$location='create_audio.php?'.api_get_cidreq().'&id='.Security::remove_XSS($_POST['document_id']).'&dt2a=google';
-
-	//security
-	if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
-		echo '<script>window.location.href="'.$location.'"</script>';
-		return;	
-	}
+function downloadMP3_google($filepath, $dir)
+{
+    $location = 'create_audio.php?'.api_get_cidreq().'&id='.Security::remove_XSS($_POST['document_id']).'&dt2a=google';
+
+    //security
+    if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
+        echo '<script>window.location.href="'.$location.'"</script>';
+
+        return;
+    }
     global $_course, $_user;
-	$clean_title=trim($_POST['title']);
-	$clean_text=trim($_POST['text']);
-	if(empty($clean_title) || empty($clean_text)){ 
-		echo '<script>window.location.href="'.$location.'"</script>';
-		return;
-	}
-	$clean_title=Security::remove_XSS($clean_title);
-	$clean_title=Database::escape_string($clean_title);	
-	$clean_title=str_replace(' ','_', $clean_title);//compound file names
-	
-	$clean_text=Security::remove_XSS($clean_text);
-	$clean_lang=Security::remove_XSS($_POST['lang']);	
-	
-	$extension='mp3';
-	$audio_filename=$clean_title.'.'.$extension;	
-	$audio_title = str_replace('_',' ',$clean_title);
-	
-	//prevent duplicates
-	if (file_exists($filepath.'/'.$clean_title.'.'.$extension)){ 
-		$i = 1;		
-		while (file_exists($filepath.'/'.$clean_title.'_'.$i.'.'.$extension)) $i++;
-		$audio_filename = $clean_title . '_' . $i . '.'.$extension;
-		$audio_title = $clean_title . '_' . $i . '.'.$extension;
-		$audio_title = str_replace('_',' ',$audio_title);
-	}
-
-	$documentPath = $filepath.'/'.$audio_filename;
-	
-	
-	//prev for a fine unicode, borrowed from main api TODO:clean
-	// Safe replacements for some non-letter characters (whitout blank spaces)
-	$search  = array("\0", "\t", "\n", "\r", "\x0B", '/', "\\", '"', "'", '?', '*', '>', '<', '|', ':', '$', '(', ')', '^', '[', ']', '#', '+', '&', '%');
-	$replace = array('',  '_',  '_',  '_',  '_',    '-', '-',  '-', '_', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-');	
-	$filename=$clean_text;
-	// Encoding detection.
-	$encoding = api_detect_encoding($filename);
-	// Converting html-entities into encoded characters.
-	$filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
-	// Transliteration to ASCII letters, they are not dangerous for filesystems.
-	$filename = api_transliterate($filename, 'x', $encoding);
+    $clean_title = trim($_POST['title']);
+    $clean_text = trim($_POST['text']);
+    if (empty($clean_title) || empty($clean_text)) {
+        echo '<script>window.location.href="'.$location.'"</script>';
+
+        return;
+    }
+    $clean_title = Security::remove_XSS($clean_title);
+    $clean_title = Database::escape_string($clean_title);
+    $clean_title = str_replace(' ', '_', $clean_title); //compound file names
+
+    $clean_text = Security::remove_XSS($clean_text);
+    $clean_lang = Security::remove_XSS($_POST['lang']);
+
+    $extension = 'mp3';
+    $audio_filename = $clean_title.'.'.$extension;
+    $audio_title = str_replace('_', ' ', $clean_title);
+
+    //prevent duplicates
+    if (file_exists($filepath.'/'.$clean_title.'.'.$extension)) {
+        $i = 1;
+        while (file_exists($filepath.'/'.$clean_title.'_'.$i.'.'.$extension)) {
+            $i++;
+        }
+        $audio_filename = $clean_title.'_'.$i.'.'.$extension;
+        $audio_title = $clean_title.'_'.$i.'.'.$extension;
+        $audio_title = str_replace('_', ' ', $audio_title);
+    }
+
+    $documentPath = $filepath.'/'.$audio_filename;
+
+
+    //prev for a fine unicode, borrowed from main api TODO:clean
+    // Safe replacements for some non-letter characters (whitout blank spaces)
+    $search = array(
+        "\0",
+        "\t",
+        "\n",
+        "\r",
+        "\x0B",
+        '/',
+        "\\",
+        '"',
+        "'",
+        '?',
+        '*',
+        '>',
+        '<',
+        '|',
+        ':',
+        '$',
+        '(',
+        ')',
+        '^',
+        '[',
+        ']',
+        '#',
+        '+',
+        '&',
+        '%'
+    );
+    $replace = array(
+        '',
+        '_',
+        '_',
+        '_',
+        '_',
+        '-',
+        '-',
+        '-',
+        '_',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-'
+    );
+    $filename = $clean_text;
+    // Encoding detection.
+    $encoding = api_detect_encoding($filename);
+    // Converting html-entities into encoded characters.
+    $filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
+    // Transliteration to ASCII letters, they are not dangerous for filesystems.
+    $filename = api_transliterate($filename, 'x', $encoding);
     // Replacing remaining dangerous non-letter characters.
     $clean_text = str_replace($search, $replace, $filename);
-	
-	$returntext2voice=file_get_contents("http://translate.google.com/translate_tts?tl=".$clean_lang."&q=".urlencode($clean_text)."");
-	
-	//make a temporal file for get the file size
-		$tmpfname = tempnam("/tmp", "CTF");
-		$handle = fopen($tmpfname, "w");
-		fwrite($handle, $returntext2voice);
-		fclose($handle);
-		// Check if there is enough space in the course to save the file
-		if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
-			unlink($tmpfname);
-			die(get_lang('UplNotEnoughSpace'));
-		}
-		//erase temporal file
-		unlink($tmpfname);
-		
-	
-	//adding the file
-		//add new file to disk
-		file_put_contents($documentPath, $returntext2voice);
-		//add document to database
-		$current_session_id = api_get_session_id();
-		$groupId=$_SESSION['_gid'];
-		$file_size = filesize($documentPath);
-		$relativeUrlPath=$dir;
-		$doc_id = add_document($_course, $relativeUrlPath.$audio_filename, 'file', filesize($documentPath), $audio_title);
-		api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
-        Display::display_confirmation_message(get_lang('DocumentCreated'));
-	//return to location
-	echo '<script>window.location.href="'.$location.'"</script>';
+
+    $returntext2voice = file_get_contents(
+        "http://translate.google.com/translate_tts?tl=".$clean_lang."&q=".urlencode($clean_text).""
+    );
+
+    //make a temporal file for get the file size
+    $tmpfname = tempnam("/tmp", "CTF");
+    $handle = fopen($tmpfname, "w");
+    fwrite($handle, $returntext2voice);
+    fclose($handle);
+    // Check if there is enough space in the course to save the file
+    if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
+        unlink($tmpfname);
+        die(get_lang('UplNotEnoughSpace'));
+    }
+    //erase temporal file
+    unlink($tmpfname);
+
+
+    //adding the file
+    //add new file to disk
+    file_put_contents($documentPath, $returntext2voice);
+    //add document to database
+    $current_session_id = api_get_session_id();
+    $groupId = $_SESSION['_gid'];
+    $file_size = filesize($documentPath);
+    $relativeUrlPath = $dir;
+    $doc_id = FileManager::add_document(
+        $_course,
+        $relativeUrlPath.$audio_filename,
+        'file',
+        filesize($documentPath),
+        $audio_title
+    );
+    api_item_property_update(
+        $_course,
+        TOOL_DOCUMENT,
+        $doc_id,
+        'DocumentAdded',
+        $_user['user_id'],
+        $groupId,
+        null,
+        null,
+        null,
+        $current_session_id
+    );
+    Display::display_confirmation_message(get_lang('DocumentCreated'));
+    //return to location
+    echo '<script>window.location.href="'.$location.'"</script>';
 }
 
 /**
@@ -452,115 +588,189 @@ function downloadMP3_google($filepath, $dir) {
  * @author Juan Carlos Raña Trabado <herodoto@telefonica.net>
  * @version january 2011, chamilo 1.8.8
  */
-function downloadMP3_pediaphon($filepath, $dir){
-	$location='create_audio.php?'.api_get_cidreq().'&id='.Security::remove_XSS($_POST['document_id']).'&dt2a=pediaphon';
-	//security
-	if(!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
-		echo '<script>window.location.href="'.$location.'"</script>';
-		return;	
-	}
+function downloadMP3_pediaphon($filepath, $dir)
+{
+    $location = 'create_audio.php?'.api_get_cidreq().'&id='.Security::remove_XSS(
+        $_POST['document_id']
+    ).'&dt2a=pediaphon';
+    //security
+    if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
+        echo '<script>window.location.href="'.$location.'"</script>';
+
+        return;
+    }
     global $_course, $_user;
-	$clean_title=trim($_POST['title']);
-	$clean_title= Database::escape_string($clean_title);
-	$clean_text=trim($_POST['text']);
-	$clean_voices=Security::remove_XSS($_POST['voices']);
-	if(empty($clean_title) || empty($clean_text) || empty($clean_voices)){
-		echo '<script>window.location.href="'.$location.'"</script>';
-		return;
-	}
-	$clean_title=Security::remove_XSS($clean_title);
-	$clean_title=Database::escape_string($clean_title);	
-	$clean_title=str_replace(' ','_', $clean_title);//compound file names
-	$clean_text=Security::remove_XSS($clean_text);
-	$clean_lang=Security::remove_XSS($_POST['lang']);
-	$clean_speed=Security::remove_XSS($_POST['speed']);
-	
-	$extension='mp3';
-	$audio_filename=$clean_title.'.'.$extension;
-	$audio_title = str_replace('_',' ',$clean_title);
-	
-	//prevent duplicates
-	if (file_exists($filepath.'/'.$clean_title.'.'.$extension)){ 
-		$i = 1;		
-		while (file_exists($filepath.'/'.$clean_title.'_'.$i.'.'.$extension)) $i++;
-		$audio_filename = $clean_title . '_' . $i . '.'.$extension;
-		$audio_title = $clean_title . '_' . $i . '.'.$extension;
-		$audio_title = str_replace('_',' ',$audio_title);
-	}
-
-	$documentPath = $filepath.'/'.$audio_filename;
-	
-
-
-
-	//prev for a fine unicode, borrowed from main api TODO:clean
-	// Safe replacements for some non-letter characters (whitout blank spaces)
-	$search  = array("\0", "\t", "\n", "\r", "\x0B", '/', "\\", '"', "'", '?', '*', '>', '<', '|', ':', '$', '(', ')', '^', '[', ']', '#', '+', '&', '%');
-	$replace = array('',  '_',  '_',  '_',  '_',    '-', '-',  '-', '_', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-');	
-	$filename=$clean_text;
-	// Encoding detection.
-	$encoding = api_detect_encoding($filename);
-	// Converting html-entities into encoded characters.
-	$filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
-	// Transliteration to ASCII letters, they are not dangerous for filesystems.
-	$filename = api_transliterate($filename, 'x', $encoding);
+    $clean_title = trim($_POST['title']);
+    $clean_title = Database::escape_string($clean_title);
+    $clean_text = trim($_POST['text']);
+    $clean_voices = Security::remove_XSS($_POST['voices']);
+    if (empty($clean_title) || empty($clean_text) || empty($clean_voices)) {
+        echo '<script>window.location.href="'.$location.'"</script>';
+
+        return;
+    }
+    $clean_title = Security::remove_XSS($clean_title);
+    $clean_title = Database::escape_string($clean_title);
+    $clean_title = str_replace(' ', '_', $clean_title); //compound file names
+    $clean_text = Security::remove_XSS($clean_text);
+    $clean_lang = Security::remove_XSS($_POST['lang']);
+    $clean_speed = Security::remove_XSS($_POST['speed']);
+
+    $extension = 'mp3';
+    $audio_filename = $clean_title.'.'.$extension;
+    $audio_title = str_replace('_', ' ', $clean_title);
+
+    //prevent duplicates
+    if (file_exists($filepath.'/'.$clean_title.'.'.$extension)) {
+        $i = 1;
+        while (file_exists($filepath.'/'.$clean_title.'_'.$i.'.'.$extension)) {
+            $i++;
+        }
+        $audio_filename = $clean_title.'_'.$i.'.'.$extension;
+        $audio_title = $clean_title.'_'.$i.'.'.$extension;
+        $audio_title = str_replace('_', ' ', $audio_title);
+    }
+
+    $documentPath = $filepath.'/'.$audio_filename;
+
+
+    //prev for a fine unicode, borrowed from main api TODO:clean
+    // Safe replacements for some non-letter characters (whitout blank spaces)
+    $search = array(
+        "\0",
+        "\t",
+        "\n",
+        "\r",
+        "\x0B",
+        '/',
+        "\\",
+        '"',
+        "'",
+        '?',
+        '*',
+        '>',
+        '<',
+        '|',
+        ':',
+        '$',
+        '(',
+        ')',
+        '^',
+        '[',
+        ']',
+        '#',
+        '+',
+        '&',
+        '%'
+    );
+    $replace = array(
+        '',
+        '_',
+        '_',
+        '_',
+        '_',
+        '-',
+        '-',
+        '-',
+        '_',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-',
+        '-'
+    );
+    $filename = $clean_text;
+    // Encoding detection.
+    $encoding = api_detect_encoding($filename);
+    // Converting html-entities into encoded characters.
+    $filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
+    // Transliteration to ASCII letters, they are not dangerous for filesystems.
+    $filename = api_transliterate($filename, 'x', $encoding);
     // Replacing remaining dangerous non-letter characters.
     $clean_text = str_replace($search, $replace, $filename);
-	
-	//adding the file
-	
-		
-		if($clean_lang=='de'){
-			$url_pediaphon='http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice.cgi';
-			$find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/(.*)\.mp3\"/';
-		}		
-		else{
-			$url_pediaphon='http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice_'.$clean_lang.'.cgi';//en, es, fr
-			$find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/'.$clean_lang.'\/(.*)\.mp3\"/';
-		}
-
-		$data="stimme=".$clean_voices."&inputtext=".$clean_text."&speed=".$clean_speed."&go=go";
-		$opts = array('http' =>
-			array(
-			 'method'  => 'POST',
-			 'header'  =>"Content-Type: application/x-www-form-urlencoded\r\n",
-			 "Content-Length: " . strlen($data) . "\r\n",
-			 'content' => $data
-			)
-		);                   
-		$context  = stream_context_create($opts);
-		$previous_returntext2voice = file_get_contents($url_pediaphon,false,$context);
-		
-		//clean file contents
-		
-		$search_source=preg_match($find_t2v, $previous_returntext2voice, $hits);
-		$souce_end=substr($hits[0], 0,-1);
-		$returntext2voice = file_get_contents($souce_end);
-		
-		//make a temporal file for get the file size
-			$tmpfname = tempnam("/tmp", "CTF");
-			$handle = fopen($tmpfname, "w");
-			fwrite($handle, $returntext2voice);
-			fclose($handle);
-			// Check if there is enough space in the course to save the file
-			if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
-				unlink($tmpfname);
-				die(get_lang('UplNotEnoughSpace'));
-			}
-			//erase temporal file
-			unlink($tmpfname);
-		
-		//save file
-		file_put_contents($documentPath, $returntext2voice);
-		
-		//add document to database
-		$current_session_id = api_get_session_id();
-		$groupId=$_SESSION['_gid'];
-		$file_size = filesize($documentPath);
-		$relativeUrlPath=$dir;
-		$doc_id = add_document($_course, $relativeUrlPath.$audio_filename, 'file', filesize($documentPath), $audio_title);
-		api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
-        Display::display_confirmation_message(get_lang('DocumentCreated'));
-	//return to location
-	echo '<script>window.location.href="'.$location.'"</script>';
+
+    //adding the file
+
+
+    if ($clean_lang == 'de') {
+        $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice.cgi';
+        $find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/(.*)\.mp3\"/';
+    } else {
+        $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice_'.$clean_lang.'.cgi'; //en, es, fr
+        $find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/'.$clean_lang.'\/(.*)\.mp3\"/';
+    }
+
+    $data = "stimme=".$clean_voices."&inputtext=".$clean_text."&speed=".$clean_speed."&go=go";
+    $opts = array(
+        'http' =>
+        array(
+            'method' => 'POST',
+            'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
+            "Content-Length: ".strlen($data)."\r\n",
+            'content' => $data
+        )
+    );
+    $context = stream_context_create($opts);
+    $previous_returntext2voice = file_get_contents($url_pediaphon, false, $context);
+
+    //clean file contents
+
+    $search_source = preg_match($find_t2v, $previous_returntext2voice, $hits);
+    $souce_end = substr($hits[0], 0, -1);
+    $returntext2voice = file_get_contents($souce_end);
+
+    //make a temporal file for get the file size
+    $tmpfname = tempnam("/tmp", "CTF");
+    $handle = fopen($tmpfname, "w");
+    fwrite($handle, $returntext2voice);
+    fclose($handle);
+    // Check if there is enough space in the course to save the file
+    if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
+        unlink($tmpfname);
+        die(get_lang('UplNotEnoughSpace'));
+    }
+    //erase temporal file
+    unlink($tmpfname);
+
+    //save file
+    file_put_contents($documentPath, $returntext2voice);
+
+    //add document to database
+    $current_session_id = api_get_session_id();
+    $groupId = $_SESSION['_gid'];
+    $file_size = filesize($documentPath);
+    $relativeUrlPath = $dir;
+    $doc_id = FileManager::add_document(
+        $_course,
+        $relativeUrlPath.$audio_filename,
+        'file',
+        filesize($documentPath),
+        $audio_title
+    );
+    api_item_property_update(
+        $_course,
+        TOOL_DOCUMENT,
+        $doc_id,
+        'DocumentAdded',
+        $_user['user_id'],
+        $groupId,
+        null,
+        null,
+        null,
+        $current_session_id
+    );
+    Display::display_confirmation_message(get_lang('DocumentCreated'));
+    //return to location
+    echo '<script>window.location.href="'.$location.'"</script>';
 }

+ 394 - 256
main/document/create_document.php

@@ -1,9 +1,9 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- *	This file allows creating new html documents with an online WYSIWYG html editor.
+ *    This file allows creating new html documents with an online WYSIWYG html editor.
  *
- *	@package chamilo.document
+ * @package chamilo.document
  */
 /**
  * Code
@@ -76,11 +76,13 @@ function InnerDialogLoaded() {
 
 	var temp=false;
 	var temp2=false;
-	var load_default_template = '. ((isset($_POST['submit']) || empty($_SERVER['QUERY_STRING'])) ? 'false' : 'true' ) .';
+	var load_default_template = '.((isset($_POST['submit']) || empty($_SERVER['QUERY_STRING'])) ? 'false' : 'true').';
 
 	function FCKeditor_OnComplete( editorInstance ) {
 		editorInstance.Events.AttachEvent( \'OnSelectionChange\', check_for_title ) ;
-		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 \'>";
+		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 \'>";
 	}
 
 	function check_for_title() {
@@ -153,20 +155,19 @@ function InnerDialogLoaded() {
     });
 </script>';
 
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'document/document.inc.php';
 
 //I'm in the certification module?
 $is_certificate_mode = false;
 
 if (isset($_REQUEST['certificate']) && $_REQUEST['certificate'] == 'true') {
-	$is_certificate_mode = true;
+    $is_certificate_mode = true;
 }
 
 if ($is_certificate_mode) {
-	$nameTools = get_lang('CreateCertificate');
+    $nameTools = get_lang('CreateCertificate');
 } else {
-	$nameTools = get_lang('CreateDocument');
+    $nameTools = get_lang('CreateDocument');
 }
 
 /*	Constants and variables */
@@ -177,121 +178,132 @@ $course_id = api_get_course_int_id();
 $document_data = DocumentManager::get_document_data_by_id($_REQUEST['id'], api_get_course_id(), true);
 if (empty($document_data)) {
     if (api_is_in_group()) {
-        $group_properties   = GroupManager::get_group_properties(api_get_group_id());
-        $document_id        = DocumentManager::get_document_id(api_get_course_info(), $group_properties['directory']);
-        $document_data      = DocumentManager::get_document_data_by_id($document_id, api_get_course_id());
+        $group_properties = GroupManager::get_group_properties(api_get_group_id());
+        $document_id = DocumentManager::get_document_id(api_get_course_info(), $group_properties['directory']);
+        $document_data = DocumentManager::get_document_data_by_id($document_id, api_get_course_id());
 
-        $dir                = $document_data['path'];
-        $folder_id          = $document_data['id'];
+        $dir = $document_data['path'];
+        $folder_id = $document_data['id'];
     } else {
         $dir = '/';
         $folder_id = 0;
     }
 } else {
     $folder_id = $document_data['id'];
-    $dir       = $document_data['path'];
+    $dir = $document_data['path'];
 }
 
 /*	MAIN CODE */
 
 // Please, do not modify this dirname formatting
 if (strstr($dir, '..')) {
-	$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 .= '/';
+    $dir .= '/';
 }
 
 if ($is_certificate_mode) {
-	$document_id 	= DocumentManager::get_document_id(api_get_course_info(), '/certificates');
-	$document_data 	= DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), true);
-	$folder_id = $document_data['id'];
-	$dir = '/certificates/';
+    $document_id = DocumentManager::get_document_id(api_get_course_info(), '/certificates');
+    $document_data = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), true);
+    $folder_id = $document_data['id'];
+    $dir = '/certificates/';
 }
 
 // Configuration for the FCKEDITOR
-$doc_tree  = explode('/', $dir);
-$count_dir = count($doc_tree) -2; // "2" because at the begin and end there are 2 "/"
+$doc_tree = explode('/', $dir);
+$count_dir = count($doc_tree) - 2; // "2" because at the begin and end there are 2 "/"
 
 if (api_is_in_group()) {
     $group_properties = GroupManager::get_group_properties(api_get_group_id());
 
     // Level correction for group documents.
     if (!empty($group_properties['directory'])) {
-    	$count_dir = $count_dir > 0 ? $count_dir - 1 : 0;
+        $count_dir = $count_dir > 0 ? $count_dir - 1 : 0;
     }
 }
 $relative_url = '';
 for ($i = 0; $i < ($count_dir); $i++) {
-	$relative_url .= '../';
+    $relative_url .= '../';
 }
 
 // We do this in order to avoid the condition in html_editor.php ==> if ($this -> fck_editor->Config['CreateDocumentWebDir']=='' || $this -> fck_editor->Config['CreateDocumentDir']== '')
-if ($relative_url== '') {
-	$relative_url = '/';
+if ($relative_url == '') {
+    $relative_url = '/';
 }
 
 $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
 
 $html_editor_config = array(
-	'ToolbarSet'           => ($is_allowed_to_edit ? 'Documents' :'DocumentsStudent'),
-	'Width'                => '100%',
-	'Height'               => '500',
-	'FullPage'             => true,
-	'InDocument'           => true,
-	'CreateDocumentDir'    => $relative_url,
-	'CreateDocumentWebDir' => (empty($group_properties['directory']))
-                        		? api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/'
-                        		: api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/',
-	'BaseHref'             => api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir
+    'ToolbarSet' => ($is_allowed_to_edit ? 'Documents' : 'DocumentsStudent'),
+    'Width' => '100%',
+    'Height' => '500',
+    'FullPage' => true,
+    'InDocument' => true,
+    'CreateDocumentDir' => $relative_url,
+    'CreateDocumentWebDir' => (empty($group_properties['directory']))
+        ? api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/'
+        : api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/',
+    'BaseHref' => api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir
 );
 
 if ($is_certificate_mode) {
-    $html_editor_config['CreateDocumentDir']    = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/';
+    $html_editor_config['CreateDocumentDir'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/';
     $html_editor_config['CreateDocumentWebDir'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/';
-    $html_editor_config['BaseHref']             = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir;
+    $html_editor_config['BaseHref'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$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 = '/';
 }
 
 $to_group_id = 0;
 
 if (!$is_certificate_mode) {
     $req_gid = null;
-	if (api_is_in_group()) {
-		$req_gid = '&amp;gidReq='.api_get_group_id();
-		$interbreadcrumb[] = array ("url" => "../group/group_space.php?gidReq=".api_get_group_id(), "name" => get_lang('GroupSpace'));
-		$noPHP_SELF = true;
-		$to_group_id = api_get_group_id();
-		$path = explode('/', $dir);
-		if ('/'.$path[1] != $group_properties['directory']) {
-			api_not_allowed(true);
-		}
-	}
-	$interbreadcrumb[] = array ("url" => "./document.php?curdirpath=".urlencode($dir).$req_gid, "name" => get_lang('Documents'));
+    if (api_is_in_group()) {
+        $req_gid = '&amp;gidReq='.api_get_group_id();
+        $interbreadcrumb[] = array(
+            "url" => "../group/group_space.php?gidReq=".api_get_group_id(),
+            "name" => get_lang('GroupSpace')
+        );
+        $noPHP_SELF = true;
+        $to_group_id = api_get_group_id();
+        $path = explode('/', $dir);
+        if ('/'.$path[1] != $group_properties['directory']) {
+            api_not_allowed(true);
+        }
+    }
+    $interbreadcrumb[] = array(
+        "url" => "./document.php?curdirpath=".urlencode($dir).$req_gid,
+        "name" => get_lang('Documents')
+    );
 } else {
-	$interbreadcrumb[]= array (	'url' => '../gradebook/'.$_SESSION['gradebook_dest'], 'name' => get_lang('Gradebook'));
+    $interbreadcrumb[] = array('url' => '../gradebook/'.$_SESSION['gradebook_dest'], 'name' => get_lang('Gradebook'));
 }
 
 if (!$is_allowed_in_course) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
-if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || is_my_shared_folder($_user['user_id'], Security::remove_XSS($dir),api_get_session_id()))) {
-	api_not_allowed(true);
+if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || is_my_shared_folder(
+    $_user['user_id'],
+    Security::remove_XSS($dir),
+    api_get_session_id()
+))
+) {
+    api_not_allowed(true);
 }
 
 /*	Header */
@@ -300,24 +312,27 @@ event_access_tool(TOOL_DOCUMENT);
 
 $display_dir = $dir;
 if (isset ($group_properties)) {
-	$display_dir = explode('/', $dir);
-	unset ($display_dir[0]);
-	unset ($display_dir[1]);
-	$display_dir = implode('/', $display_dir);
+    $display_dir = explode('/', $dir);
+    unset ($display_dir[0]);
+    unset ($display_dir[1]);
+    $display_dir = implode('/', $display_dir);
 }
 
 $select_cat = isset($_GET['selectcat']) ? intval($_GET['selectcat']) : null;
 
 // Create a new form
-$form = new FormValidator('create_document','post',api_get_self().'?'.api_get_cidreq().'&dir='.Security::remove_XSS(urlencode($dir)).'&selectcat='.$select_cat, null, array('class' =>'form-vertical'));
+$form = new FormValidator('create_document', 'post', api_get_self().'?'.api_get_cidreq().'&dir='.Security::remove_XSS(
+    urlencode($dir)
+).'&selectcat='.$select_cat, null, array('class' => 'form-vertical'));
 
 // form title
 $form->addElement('header', $nameTools);
 
-if ($is_certificate_mode) {//added condition for certicate in gradebook
-	$form->addElement('hidden','certificate','true',array('id'=>'certificate'));
-	if (isset($_GET['selectcat']))
-		$form->addElement('hidden','selectcat', $select_cat);
+if ($is_certificate_mode) { //added condition for certicate in gradebook
+    $form->addElement('hidden', 'certificate', 'true', array('id' => 'certificate'));
+    if (isset($_GET['selectcat'])) {
+        $form->addElement('hidden', 'selectcat', $select_cat);
+    }
 
 }
 // Hidden element with current directory
@@ -331,31 +346,33 @@ $form->addElement('hidden', 'title_edited', 'false', 'id="title_edited"');
 /**
  * Check if a document width the choosen filename allready exists
  */
-function document_exists($filename) {
-	global $filepath;
-	$filename = addslashes(trim($filename));
-	$filename = Security::remove_XSS($filename);
-	$filename = replace_dangerous_char($filename);
-	$filename = disable_dangerous_file($filename);
-	return !file_exists($filepath.$filename.'.html');
+function document_exists($filename)
+{
+    global $filepath;
+    $filename = addslashes(trim($filename));
+    $filename = Security::remove_XSS($filename);
+    $filename = replace_dangerous_char($filename);
+    $filename = FileManager::disable_dangerous_file($filename);
+
+    return !file_exists($filepath.$filename.'.html');
 }
 
 // Add group to the form
 if ($is_certificate_mode) {
     $form->addElement('text', 'title', get_lang('CertificateName'), 'class="span4" id="document_title"');
 } else {
-	$form->addElement('text', 'title', get_lang('Title'), 'class="span4" id="document_title"');
+    $form->addElement('text', 'title', get_lang('Title'), 'class="span4" id="document_title"');
 }
 
 // Show read-only box only in groups
 if (!empty($_SESSION['_gid'])) {
-	$group[]= $form->createElement('checkbox', 'readonly', '', get_lang('ReadOnly'));
+    $group[] = $form->createElement('checkbox', 'readonly', '', get_lang('ReadOnly'));
 }
 $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('title', get_lang('FileExists'), 'callback', 'document_exists');
 
 $current_session_id = api_get_session_id();
-$form->add_html_editor('content','', false, false, $html_editor_config);
+$form->add_html_editor('content', '', false, false, $html_editor_config);
 
 // Comment-field
 $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit);
@@ -364,30 +381,40 @@ $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is
 // new document created
 
 if (!$is_certificate_mode && !is_my_shared_folder($_user['user_id'], $dir, $current_session_id)) {
-	$folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit);
+    $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit);
 
-	$parent_select = $form->addElement('select', 'curdirpath', array(null, get_lang('DestinationDirectory')));
+    $parent_select = $form->addElement('select', 'curdirpath', array(null, get_lang('DestinationDirectory')));
 
-	// Following two conditions copied from document.inc.php::build_directory_selector()
-	$folder_titles = array();
+    // Following two conditions copied from document.inc.php::build_directory_selector()
+    $folder_titles = array();
 
     if (is_array($folders)) {
         $escaped_folders = array();
         foreach ($folders as $key => & $val) {
             //Hide some folders
-            if ($val=='/HotPotatoes_files' || $val=='/certificates' || basename($val)=='css'){
+            if ($val == '/HotPotatoes_files' || $val == '/certificates' || basename($val) == 'css') {
                 continue;
             }
             //Admin setting for Hide/Show the folders of all users
-            if (api_get_setting('show_users_folders') == 'false' && (strstr($val, '/shared_folder') || strstr($val, 'shared_folder_session_'))){
+            if (api_get_setting('show_users_folders') == 'false' && (strstr($val, '/shared_folder') || strstr(
+                $val,
+                'shared_folder_session_'
+            ))
+            ) {
                 continue;
             }
             //Admin setting for Hide/Show Default folders to all users
-            if (api_get_setting('show_default_folders') == 'false' && ($val=='/images' || $val=='/flash' || $val=='/audio' || $val=='/video' || strstr($val, '/images/gallery') || $val=='/video/flv')){
+            if (api_get_setting(
+                'show_default_folders'
+            ) == 'false' && ($val == '/images' || $val == '/flash' || $val == '/audio' || $val == '/video' || strstr(
+                $val,
+                '/images/gallery'
+            ) || $val == '/video/flv')
+            ) {
                 continue;
             }
             //Admin setting for Hide/Show chat history folder
-            if (api_get_setting('show_chat_folder') == 'false' && $val=='/chat_files'){
+            if (api_get_setting('show_chat_folder') == 'false' && $val == '/chat_files') {
                 continue;
             }
 
@@ -403,211 +430,322 @@ if (!$is_certificate_mode && !is_my_shared_folder($_user['user_id'], $dir, $curr
         }
     }
 
-	if (empty($group_dir)) {
-		$parent_select -> addOption(get_lang('HomeDirectory'), '/');
-		if (is_array($folders)) {
-			foreach ($folders as & $folder) {
-				//Hide some folders
-				if ($folder=='/HotPotatoes_files' || $folder=='/certificates' || basename($folder)=='css'){
-				 continue;
-				}
-				//Admin setting for Hide/Show the folders of all users
-				if (api_get_setting('show_users_folders') == 'false' && (strstr($folder, '/shared_folder') || strstr($folder, 'shared_folder_session_'))){
-					continue;
-				}
-				//Admin setting for Hide/Show Default folders to all users
-				if (api_get_setting('show_default_folders') == 'false' && ($folder=='/images' || $folder=='/flash' || $folder=='/audio' || $folder=='/video' || strstr($folder, '/images/gallery') || $folder=='/video/flv')){
-					continue;
-				}
-				//Admin setting for Hide/Show chat history folder
-				if (api_get_setting('show_chat_folder') == 'false' && $folder=='/chat_files'){
-					continue;
-				}
+    if (empty($group_dir)) {
+        $parent_select->addOption(get_lang('HomeDirectory'), '/');
+        if (is_array($folders)) {
+            foreach ($folders as & $folder) {
+                //Hide some folders
+                if ($folder == '/HotPotatoes_files' || $folder == '/certificates' || basename($folder) == 'css') {
+                    continue;
+                }
+                //Admin setting for Hide/Show the folders of all users
+                if (api_get_setting('show_users_folders') == 'false' && (strstr($folder, '/shared_folder') || strstr(
+                    $folder,
+                    'shared_folder_session_'
+                ))
+                ) {
+                    continue;
+                }
+                //Admin setting for Hide/Show Default folders to all users
+                if (api_get_setting(
+                    'show_default_folders'
+                ) == 'false' && ($folder == '/images' || $folder == '/flash' || $folder == '/audio' || $folder == '/video' || strstr(
+                    $folder,
+                    '/images/gallery'
+                ) || $folder == '/video/flv')
+                ) {
+                    continue;
+                }
+                //Admin setting for Hide/Show chat history folder
+                if (api_get_setting('show_chat_folder') == 'false' && $folder == '/chat_files') {
+                    continue;
+                }
 
-				$selected = (substr($dir,0,-1) == $folder) ? ' selected="selected"' : '';
-				$path_parts = explode('/', $folder);
-				$folder_titles[$folder] = cut($folder_titles[$folder], 80);
-                $space_counter =count($path_parts) - 2;
+                $selected = (substr($dir, 0, -1) == $folder) ? ' selected="selected"' : '';
+                $path_parts = explode('/', $folder);
+                $folder_titles[$folder] = cut($folder_titles[$folder], 80);
+                $space_counter = count($path_parts) - 2;
                 if ($space_counter > 0) {
                     $label = str_repeat('&nbsp;&nbsp;&nbsp;', $space_counter).' &mdash; '.$folder_titles[$folder];
                 } else {
                     $label = ' &mdash; '.$folder_titles[$folder];
                 }
-				$parent_select -> addOption($label, $folder);
-				if ($selected != '') {
-					$parent_select->setSelected($folder);
-				}
-			}
-		}
-	} else {
-		foreach ($folders as & $folder) {
-			$selected = (substr($dir,0,-1)==$folder) ? ' selected="selected"' : '';
-			$label = $folder_titles[$folder];
-			if ($folder == $group_dir) {
-				$label = '/ ('.get_lang('HomeDirectory').')';
-			} else {
-				$path_parts = explode('/', str_replace($group_dir, '', $folder));
-				$label = cut($label, 80);
-				$label = str_repeat('&nbsp;&nbsp;&nbsp;', count($path_parts) - 2).' &mdash; '.$label;
-			}
-			$parent_select -> addOption($label, $folder);
-			if ($selected != '') {
-				$parent_select->setSelected($folder);
-			}
-		}
-	}
+                $parent_select->addOption($label, $folder);
+                if ($selected != '') {
+                    $parent_select->setSelected($folder);
+                }
+            }
+        }
+    } else {
+        foreach ($folders as & $folder) {
+            $selected = (substr($dir, 0, -1) == $folder) ? ' selected="selected"' : '';
+            $label = $folder_titles[$folder];
+            if ($folder == $group_dir) {
+                $label = '/ ('.get_lang('HomeDirectory').')';
+            } else {
+                $path_parts = explode('/', str_replace($group_dir, '', $folder));
+                $label = cut($label, 80);
+                $label = str_repeat('&nbsp;&nbsp;&nbsp;', count($path_parts) - 2).' &mdash; '.$label;
+            }
+            $parent_select->addOption($label, $folder);
+            if ($selected != '') {
+                $parent_select->setSelected($folder);
+            }
+        }
+    }
 }
 
-if ($is_certificate_mode)
-	$form->addElement('style_submit_button', 'submit', get_lang('CreateCertificate'), 'class="save"');
-else
-	$form->addElement('style_submit_button', 'submit', get_lang('CreateDoc'), 'class="save"');
+if ($is_certificate_mode) {
+    $form->addElement('style_submit_button', 'submit', get_lang('CreateCertificate'), 'class="save"');
+} else {
+    $form->addElement('style_submit_button', 'submit', get_lang('CreateDoc'), 'class="save"');
+}
 
 $form->setDefaults($defaults);
 
 // If form validates -> save the new document
 if ($form->validate()) {
-	$values = $form->exportValues();
-	$readonly = isset($values['readonly']) ? 1 : 0;
+    $values = $form->exportValues();
+    $readonly = isset($values['readonly']) ? 1 : 0;
 
-	$values['title'] = trim($values['title']);
+    $values['title'] = trim($values['title']);
 
-	if (!empty($values['curdirpath'])) {
-		$dir = $values['curdirpath'];
-	}
+    if (!empty($values['curdirpath'])) {
+        $dir = $values['curdirpath'];
+    }
 
-	if ($dir[strlen($dir) - 1] != '/') {
-		$dir .= '/';
-	}
+    if ($dir[strlen($dir) - 1] != '/') {
+        $dir .= '/';
+    }
 
     //Setting the filename
-	$filename = $values['title'];
-	$filename = addslashes(trim($filename));
-	$filename = Security::remove_XSS($filename);
-	$filename = replace_dangerous_char($filename);
-	$filename = disable_dangerous_file($filename);
+    $filename = $values['title'];
+    $filename = addslashes(trim($filename));
+    $filename = Security::remove_XSS($filename);
+    $filename = replace_dangerous_char($filename);
+    $filename = FileManager::disable_dangerous_file($filename);
 
     //Setting the title
-	$title 		= $values['title'];
+    $title = $values['title'];
 
     //Setting the extension
-	$extension = 'html';
-
-	$content = Security::remove_XSS($values['content'], COURSEMANAGERLOWSECURITY);
+    $extension = 'html';
 
-	if (strpos($content, '/css/frames.css') === false) {
-		$content = str_replace('</head>', '<style> body{margin:10px;}</style><link rel="stylesheet" href="./css/frames.css" type="text/css" /></head>', $content);
-	}
-	if ($fp = @fopen($filepath.$filename.'.'.$extension, 'w')) {
-		$content = str_replace(api_get_path(WEB_COURSE_PATH), $_configuration['url_append'].'/courses/', $content);
-
-		// change the path of mp3 to absolute
-		// first regexp deals with ../../../ urls
-		// Disabled by Ivan Tcholakov.
-		//$content = preg_replace("|(flashvars=\"file=)(\.+/)+|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',$content);
-		//second regexp deals with audio/ urls
-		// Disabled by Ivan Tcholakov.
-		//$content = preg_replace("|(flashvars=\"file=)([^/]+)/|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',$content);
-		fputs($fp, $content);
-		fclose($fp);
-		chmod($filepath.$filename.'.'.$extension, api_get_permissions_for_new_files());
-		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);
-		}
+    $content = Security::remove_XSS($values['content'], COURSEMANAGERLOWSECURITY);
 
-		if (!is_file($filepath.'css/frames.css')) {
-			// Make a copy of the current css for the new document
-			copy(api_get_path(SYS_CODE_PATH).'css/'.api_get_setting('stylesheets').'/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);
-		}
+    if (strpos($content, '/css/frames.css') === false) {
+        $content = str_replace(
+            '</head>',
+            '<style> body{margin:10px;}</style><link rel="stylesheet" href="./css/frames.css" type="text/css" /></head>',
+            $content
+        );
+    }
+    if ($fp = @fopen($filepath.$filename.'.'.$extension, 'w')) {
+        $content = str_replace(api_get_path(WEB_COURSE_PATH), $_configuration['url_append'].'/courses/', $content);
+
+        // change the path of mp3 to absolute
+        // first regexp deals with ../../../ urls
+        // Disabled by Ivan Tcholakov.
+        //$content = preg_replace("|(flashvars=\"file=)(\.+/)+|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',$content);
+        //second regexp deals with audio/ urls
+        // Disabled by Ivan Tcholakov.
+        //$content = preg_replace("|(flashvars=\"file=)([^/]+)/|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',$content);
+        fputs($fp, $content);
+        fclose($fp);
+        chmod($filepath.$filename.'.'.$extension, api_get_permissions_for_new_files());
+        if (!is_dir($filepath.'css')) {
+            mkdir($filepath.'css', api_get_permissions_for_new_directories());
+            $doc_id = FileManager::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
+            );
+        }
 
-		$file_size = filesize($filepath.$filename.'.'.$extension);
-		$save_file_path = $dir.$filename.'.'.$extension;
+        if (!is_file($filepath.'css/frames.css')) {
+            // Make a copy of the current css for the new document
+            copy(
+                api_get_path(SYS_CODE_PATH).'css/'.api_get_setting('stylesheets').'/frames.css',
+                $filepath.'css/frames.css'
+            );
+            $doc_id = FileManager::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
+            );
+        }
 
-		$document_id = add_document($_course, $save_file_path, 'file', $file_size, $title, null, $readonly);
-		if ($document_id) {
-			api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_user['user_id'], $to_group_id, null, null, null, $current_session_id);
-			// Update parent folders
-			item_property_update_on_folder($_course, $dir, $_user['user_id']);
-			$new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
+        $file_size = filesize($filepath.$filename.'.'.$extension);
+        $save_file_path = $dir.$filename.'.'.$extension;
+
+        $document_id = FileManager::add_document(
+            $_course,
+            $save_file_path,
+            'file',
+            $file_size,
+            $title,
+            null,
+            $readonly
+        );
+        if ($document_id) {
+            api_item_property_update(
+                $_course,
+                TOOL_DOCUMENT,
+                $document_id,
+                'DocumentAdded',
+                $_user['user_id'],
+                $to_group_id,
+                null,
+                null,
+                null,
+                $current_session_id
+            );
+            // Update parent folders
+            FileManager::item_property_update_on_folder($_course, $dir, $_user['user_id']);
+            $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
             $new_comment = Database::escape_string($new_comment);
-			$new_title = isset($_POST['title']) ? trim($_POST['title']) : '';
+            $new_title = isset($_POST['title']) ? trim($_POST['title']) : '';
             $new_title = htmlspecialchars($new_title);
             $new_title = Database::escape_string($new_title);
-			if ($new_comment || $new_title) {
-				$ct = '';
-				if ($new_comment)
-					$ct .= ", comment='$new_comment'";
-				if ($new_title)
-					$ct .= ", title='$new_title'";
-				Database::query("UPDATE $doc_table SET".substr($ct, 1)." WHERE c_id = $course_id AND id = '$document_id'");
-			}
-			$dir= substr($dir,0,-1);
-			$selectcat = '';
-			if (isset($_REQUEST['selectcat']))
-				$selectcat = "&selectcat=".Security::remove_XSS($_REQUEST['selectcat']);
-			$certificate_condition = '';
-			if ($is_certificate_mode) {
-				$df = DocumentManager::get_default_certificate_id($_course['code']);
+            if ($new_comment || $new_title) {
+                $ct = '';
+                if ($new_comment) {
+                    $ct .= ", comment='$new_comment'";
+                }
+                if ($new_title) {
+                    $ct .= ", title='$new_title'";
+                }
+                Database::query(
+                    "UPDATE $doc_table SET".substr($ct, 1)." WHERE c_id = $course_id AND id = '$document_id'"
+                );
+            }
+            $dir = substr($dir, 0, -1);
+            $selectcat = '';
+            if (isset($_REQUEST['selectcat'])) {
+                $selectcat = "&selectcat=".Security::remove_XSS($_REQUEST['selectcat']);
+            }
+            $certificate_condition = '';
+            if ($is_certificate_mode) {
+                $df = DocumentManager::get_default_certificate_id($_course['code']);
                 if (!isset($df)) {
-                    DocumentManager::attach_gradebook_certificate ($_course['code'],$document_id);
-				}
-				$certificate_condition = '&certificate=true';
-			}
-			header('Location: document.php?'.api_get_cidreq().'&id='.$folder_id.$selectcat.$certificate_condition);
-			exit();
-		} else {
-			Display :: display_header($nameTools, 'Doc');
-			Display :: display_error_message(get_lang('Impossible'));
-			Display :: display_footer();
-		}
-	} else {
-		Display :: display_header($nameTools, 'Doc');
-		Display :: display_error_message(get_lang('Impossible'));
-		Display :: display_footer();
-	}
+                    DocumentManager::attach_gradebook_certificate($_course['code'], $document_id);
+                }
+                $certificate_condition = '&certificate=true';
+            }
+            header('Location: document.php?'.api_get_cidreq().'&id='.$folder_id.$selectcat.$certificate_condition);
+            exit();
+        } else {
+            Display :: display_header($nameTools, 'Doc');
+            Display :: display_error_message(get_lang('Impossible'));
+            Display :: display_footer();
+        }
+    } else {
+        Display :: display_header($nameTools, 'Doc');
+        Display :: display_error_message(get_lang('Impossible'));
+        Display :: display_footer();
+    }
 } else {
-	// Interbreadcrumb for the current directory root path
-	// Copied from document.php
-	$dir_array = explode('/', $dir);
-	$array_len = count($dir_array);
-
-	// Interbreadcrumb for the current directory root path
-	if (empty($document_data['parents'])) {
-		$interbreadcrumb[] = array('url' => '#', 'name' => $document_data['title']);
-	} else {
-		foreach($document_data['parents'] as $document_sub_data) {
-			$interbreadcrumb[] = array('url' => $document_sub_data['document_url'], 'name' => $document_sub_data['title']);
-		}
-	}
-
-	Display :: display_header($nameTools, "Doc");
-	//api_display_tool_title($nameTools);
-	// actions
-	echo '<div class="actions">';
+    // Interbreadcrumb for the current directory root path
+    // Copied from document.php
+    $dir_array = explode('/', $dir);
+    $array_len = count($dir_array);
+
+    // Interbreadcrumb for the current directory root path
+    if (empty($document_data['parents'])) {
+        $interbreadcrumb[] = array('url' => '#', 'name' => $document_data['title']);
+    } else {
+        foreach ($document_data['parents'] as $document_sub_data) {
+            $interbreadcrumb[] = array(
+                'url' => $document_sub_data['document_url'],
+                'name' => $document_sub_data['title']
+            );
+        }
+    }
 
-	// link back to the documents overview
-	if ($is_certificate_mode)
-		echo '<a href="document.php?certificate=true&id='.$folder_id.'&selectcat=' . Security::remove_XSS($_GET['selectcat']).'">'.Display::return_icon('back.png',get_lang('Back').' '.get_lang('To').' '.get_lang('CertificateOverview'),'',ICON_SIZE_MEDIUM).'</a>';
-	else
-		echo '<a href="document.php?curdirpath='.Security::remove_XSS($dir).'">'.Display::return_icon('back.png',get_lang('Back').' '.get_lang('To').' '.get_lang('DocumentsOverview'),'',ICON_SIZE_MEDIUM).'</a>';
-	echo '</div>';
+    Display :: display_header($nameTools, "Doc");
+    //api_display_tool_title($nameTools);
+    // actions
+    echo '<div class="actions">';
+
+    // link back to the documents overview
+    if ($is_certificate_mode) {
+        echo '<a href="document.php?certificate=true&id='.$folder_id.'&selectcat='.Security::remove_XSS(
+            $_GET['selectcat']
+        ).'">'.Display::return_icon(
+            'back.png',
+            get_lang('Back').' '.get_lang('To').' '.get_lang('CertificateOverview'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+    } else {
+        echo '<a href="document.php?curdirpath='.Security::remove_XSS($dir).'">'.Display::return_icon(
+            'back.png',
+            get_lang('Back').' '.get_lang('To').' '.get_lang('DocumentsOverview'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+    }
+    echo '</div>';
 
-	if ($is_certificate_mode) {
-		$all_information_by_create_certificate = DocumentManager::get_all_info_to_certificate(api_get_user_id(), api_get_course_id());
+    if ($is_certificate_mode) {
+        $all_information_by_create_certificate = DocumentManager::get_all_info_to_certificate(
+            api_get_user_id(),
+            api_get_course_id()
+        );
 
-		$str_info = '';
-		foreach ($all_information_by_create_certificate[0] as $info_value) {
-			$str_info.=$info_value.'<br/>';
-		}
-		$create_certificate = get_lang('CreateCertificateWithTags');
-		Display::display_normal_message($create_certificate.': <br /><br/>'.$str_info,false);
-	}
+        $str_info = '';
+        foreach ($all_information_by_create_certificate[0] as $info_value) {
+            $str_info .= $info_value.'<br/>';
+        }
+        $create_certificate = get_lang('CreateCertificateWithTags');
+        Display::display_normal_message($create_certificate.': <br /><br/>'.$str_info, false);
+    }
     // HTML-editor
     echo '<div class="row-fluid" style="overflow:hidden">
             <div id="template_col" class="span2" style="width:162px">
@@ -618,5 +756,5 @@ if ($form->validate()) {
                     '.$form->return_form().'
             </div>
           </div>';
-	Display :: display_footer();
+    Display :: display_footer();
 }

+ 440 - 90
main/document/document.inc.php

@@ -9,10 +9,10 @@
  * Builds the form thats enables the user to
  * select a directory to browse/upload in
  *
- * @param array 	An array containing the folders we want to be able to select
- * @param string	The current folder (path inside of the "document" directory, including the prefix "/")
- * @param string	Group directory, if empty, prevents documents to be uploaded (because group documents cannot be uploaded in root)
- * @param	boolean	Whether to change the renderer (this will add a template <span> to the QuickForm object displaying the form)
+ * @param array     An array containing the folders we want to be able to select
+ * @param string    The current folder (path inside of the "document" directory, including the prefix "/")
+ * @param string    Group directory, if empty, prevents documents to be uploaded (because group documents cannot be uploaded in root)
+ * @param    boolean    Whether to change the renderer (this will add a template <span> to the QuickForm object displaying the form)
  * @todo this funcionality is really bad : jmontoya
  * @return string html form
  */
@@ -40,7 +40,13 @@ function build_directory_selector($folders, $document_id, $group_dir = '', $chan
 
     $form = new FormValidator('selector', 'GET', api_get_self().'?'.api_get_cidreq());
     $form->addElement('hidden', 'cidReq', api_get_course_id());
-    $parent_select = $form->addElement('select', 'id', get_lang('CurrentDirectory'), '', 'onchange="javascript: document.selector.submit();"');
+    $parent_select = $form->addElement(
+        'select',
+        'id',
+        get_lang('CurrentDirectory'),
+        '',
+        'onchange="javascript: document.selector.submit();"'
+    );
 
     if ($change_renderer) {
         $renderer = $form->defaultRenderer();
@@ -88,6 +94,7 @@ function build_directory_selector($folders, $document_id, $group_dir = '', $chan
         }
     }
     $html = $form->toHtml();
+
     return $html;
 }
 
@@ -121,7 +128,10 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
     }
 
     $filetype = $document_data['filetype'];
-    $size = $filetype == 'folder' ? FileManager::get_total_folder_size($document_data['path'], api_is_allowed_to_edit(null, true)) : $document_data['size'];
+    $size = $filetype == 'folder' ? FileManager::get_total_folder_size(
+        $document_data['path'],
+        api_is_allowed_to_edit(null, true)
+    ) : $document_data['size'];
     $path = $document_data['path'];
 
     $url_path = urlencode($document_data['path']);
@@ -131,7 +141,9 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
 
     if (!$show_as_icon) {
         // Build download link (icon)
-        $forcedownload_link = ($filetype == 'folder') ? api_get_self().'?'.api_get_cidreq().'&action=downloadfolder&id='.$document_data['id'] : api_get_self().'?'.api_get_cidreq().'&amp;action=download&amp;id='.$document_data['id'];
+        $forcedownload_link = ($filetype == 'folder') ? api_get_self().'?'.api_get_cidreq(
+        ).'&action=downloadfolder&id='.$document_data['id'] : api_get_self().'?'.api_get_cidreq(
+        ).'&amp;action=download&amp;id='.$document_data['id'];
         // Folder download or file download?
         $forcedownload_icon = ($filetype == 'folder') ? 'save_pack.png' : 'save.png';
         // Prevent multiple clicks on zipped folder download
@@ -188,7 +200,10 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
         $tooltip_title_alt = get_lang('UserFolders').' ('.api_get_session_name(api_get_session_id()).')';
     } elseif (strstr($tooltip_title, 'sf_user_')) {
         $userinfo = Database::get_user_info_from_id(substr($tooltip_title, 8));
-        $tooltip_title_alt = get_lang('UserFolder').' '.api_get_person_name($userinfo['firstname'], $userinfo['lastname']);
+        $tooltip_title_alt = get_lang('UserFolder').' '.api_get_person_name(
+            $userinfo['firstname'],
+            $userinfo['lastname']
+        );
     } elseif ($path == '/chat_files') {
         $tooltip_title_alt = get_lang('ChatFiles');
     } elseif ($path == '/learning_path') {
@@ -212,26 +227,62 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
 
     if (!$show_as_icon) {
         if ($filetype == 'folder') {
-            if (api_is_allowed_to_edit() || api_is_platform_admin() || api_get_setting('students_download_folders') == 'true') {
+            if (api_is_allowed_to_edit() || api_is_platform_admin() || api_get_setting(
+                'students_download_folders'
+            ) == 'true'
+            ) {
                 //filter when I am into shared folder, I can show for donwload only my shared folder
                 if (is_shared_folder($curdirpath, $current_session_id)) {
-                    if (preg_match('/shared_folder\/sf_user_'.api_get_user_id().'$/', urldecode($forcedownload_link)) || preg_match('/shared_folder_session_'.$current_session_id.'\/sf_user_'.api_get_user_id().'$/', urldecode($forcedownload_link)) || api_is_allowed_to_edit() || api_is_platform_admin()) {
-                        $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.Display::return_icon($forcedownload_icon, get_lang('Download'), array(), ICON_SIZE_SMALL).'</a>';
+                    if (preg_match(
+                        '/shared_folder\/sf_user_'.api_get_user_id().'$/',
+                        urldecode($forcedownload_link)
+                    ) || preg_match(
+                        '/shared_folder_session_'.$current_session_id.'\/sf_user_'.api_get_user_id().'$/',
+                        urldecode($forcedownload_link)
+                    ) || api_is_allowed_to_edit() || api_is_platform_admin()
+                    ) {
+                        $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.Display::return_icon(
+                            $forcedownload_icon,
+                            get_lang('Download'),
+                            array(),
+                            ICON_SIZE_SMALL
+                        ).'</a>';
                     }
-                } elseif (!preg_match('/shared_folder/', urldecode($forcedownload_link)) || api_is_allowed_to_edit() || api_is_platform_admin()) {
-                    $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.Display::return_icon($forcedownload_icon, get_lang('Download'), array(), ICON_SIZE_SMALL).'</a>';
+                } elseif (!preg_match('/shared_folder/', urldecode($forcedownload_link)) || api_is_allowed_to_edit(
+                ) || api_is_platform_admin()
+                ) {
+                    $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.Display::return_icon(
+                        $forcedownload_icon,
+                        get_lang('Download'),
+                        array(),
+                        ICON_SIZE_SMALL
+                    ).'</a>';
                 }
             }
         } else {
-            $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.Display::return_icon($forcedownload_icon, get_lang('Download'), array(), ICON_SIZE_SMALL).'</a>';
+            $force_download_html = ($size == 0) ? '' : '<a href="'.$forcedownload_link.'" style="float:right"'.$prevent_multiple_click.'>'.Display::return_icon(
+                $forcedownload_icon,
+                get_lang('Download'),
+                array(),
+                ICON_SIZE_SMALL
+            ).'</a>';
         }
 
         //Copy files to users myfiles
-        if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('users_copy_files') == 'true' && !api_is_anonymous()) {
-            $copy_myfiles_link = ($filetype == 'file') ? api_get_self().'?'.api_get_cidreq().'&action=copytomyfiles&id='.$document_data['id'].$req_gid : api_get_self().'?'.api_get_cidreq();
+        if (api_get_setting('allow_social_tool') == 'true' && api_get_setting(
+            'users_copy_files'
+        ) == 'true' && !api_is_anonymous()
+        ) {
+            $copy_myfiles_link = ($filetype == 'file') ? api_get_self().'?'.api_get_cidreq(
+            ).'&action=copytomyfiles&id='.$document_data['id'].$req_gid : api_get_self().'?'.api_get_cidreq();
 
             if ($filetype == 'file') {
-                $copy_to_myfiles = '<a href="'.$copy_myfiles_link.'" style="float:right"'.$prevent_multiple_click.'>'.Display::return_icon('briefcase.png', get_lang('CopyToMyFiles'), array(), ICON_SIZE_SMALL).'&nbsp;&nbsp;</a>';
+                $copy_to_myfiles = '<a href="'.$copy_myfiles_link.'" style="float:right"'.$prevent_multiple_click.'>'.Display::return_icon(
+                    'briefcase.png',
+                    get_lang('CopyToMyFiles'),
+                    array(),
+                    ICON_SIZE_SMALL
+                ).'&nbsp;&nbsp;</a>';
             }
             $send_to = '';
             if ($filetype == 'file') {
@@ -241,24 +292,40 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
 
         $pdf_icon = '';
         $extension = pathinfo($path, PATHINFO_EXTENSION);
-        if (!api_is_allowed_to_edit() && api_get_setting('students_export2pdf') == 'true' && $filetype == 'file' && in_array($extension, array('html', 'htm'))) {
-            $pdf_icon = ' <a style="float:right".'.$prevent_multiple_click.' href="'.api_get_self().'?'.api_get_cidreq().'&action=export_to_pdf&id='.$document_data['id'].'">'.Display::return_icon('pdf.png', get_lang('Export2PDF'), array(), ICON_SIZE_SMALL).'</a> ';
+        if (!api_is_allowed_to_edit() && api_get_setting(
+            'students_export2pdf'
+        ) == 'true' && $filetype == 'file' && in_array($extension, array('html', 'htm'))
+        ) {
+            $pdf_icon = ' <a style="float:right".'.$prevent_multiple_click.' href="'.api_get_self().'?'.api_get_cidreq(
+            ).'&action=export_to_pdf&id='.$document_data['id'].'">'.Display::return_icon(
+                'pdf.png',
+                get_lang('Export2PDF'),
+                array(),
+                ICON_SIZE_SMALL
+            ).'</a> ';
         }
 
         if ($is_browser_viewable_file) {
-            $open_in_new_window_link = '<a href="'.$www.str_replace('%2F', '/', $url_path).'?'.api_get_cidreq().'" style="float:right"'.$prevent_multiple_click.' target="_blank">'.Display::return_icon('open_in_new_window.png', get_lang('OpenInANewWindow'), array(), ICON_SIZE_SMALL).'&nbsp;&nbsp;</a>';
+            $open_in_new_window_link = '<a href="'.$www.str_replace('%2F', '/', $url_path).'?'.api_get_cidreq(
+            ).'" style="float:right"'.$prevent_multiple_click.' target="_blank">'.Display::return_icon(
+                'open_in_new_window.png',
+                get_lang('OpenInANewWindow'),
+                array(),
+                ICON_SIZE_SMALL
+            ).'&nbsp;&nbsp;</a>';
         }
         //target="'.$target.'"
         if ($filetype == 'file') {
             //Sound preview with jplayer
             if (preg_match('/mp3$/i', urldecode($url)) ||
                 (preg_match('/wav$/i', urldecode($url)) && !preg_match('/_chnano_.wav$/i', urldecode($url))) ||
-                preg_match('/ogg$/i', urldecode($url))) {
+                preg_match('/ogg$/i', urldecode($url))
+            ) {
                 return '<span style="float:left" '.$visibility_class.'>'.$title.'</span>'.$force_download_html.$send_to.$copy_to_myfiles.$open_in_new_window_link.$pdf_icon;
             } elseif (
-            //Show preview
-            //preg_match('/html$/i', urldecode($url))  ||
-            //preg_match('/htm$/i',  urldecode($url))  ||
+                //Show preview
+                //preg_match('/html$/i', urldecode($url))  ||
+                //preg_match('/htm$/i',  urldecode($url))  ||
                 preg_match('/swf$/i', urldecode($url)) ||
                 preg_match('/png$/i', urldecode($url)) ||
                 preg_match('/gif$/i', urldecode($url)) ||
@@ -266,19 +333,25 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
                 preg_match('/jpeg$/i', urldecode($url)) ||
                 preg_match('/bmp$/i', urldecode($url)) ||
                 preg_match('/svg$/i', urldecode($url)) ||
-                (preg_match('/wav$/i', urldecode($url)) && preg_match('/_chnano_.wav$/i', urldecode($url)) && api_get_setting('enable_nanogong') == 'true')
+                (preg_match('/wav$/i', urldecode($url)) && preg_match(
+                    '/_chnano_.wav$/i',
+                    urldecode($url)
+                ) && api_get_setting('enable_nanogong') == 'true')
             ) {
                 //yox view
                 //$url = 'showinframesmin.php?'.api_get_cidreq().'&id='.$document_data['id'].$req_gid;
                 //Simpler version of showinframesmin.php with no headers
-                $url = 'show_content.php?'.api_get_cidreq().'&id='.$document_data['id'].$req_gid.'&width=700&height=500';
+                $url = 'show_content.php?'.api_get_cidreq(
+                ).'&id='.$document_data['id'].$req_gid.'&width=700&height=500';
                 $class = 'ajax';
                 if ($visibility == false) {
                     $class = "ajax invisible";
                 }
+
                 return '<a href="'.$url.'" class="'.$class.'" title="'.$tooltip_title_alt.'" style="float:left">'.$title.'</a>'.$force_download_html.$send_to.$copy_to_myfiles.$open_in_new_window_link.$pdf_icon;
             } else {
                 $url = 'showinframes.php?'.api_get_cidreq().'&id='.$document_data['id'].$req_gid;
+
                 //No plugin just the old and good showinframes.php page
                 return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" style="float:left" '.$visibility_class.' >'.$title.'</a>'.$force_download_html.$send_to.$copy_to_myfiles.$open_in_new_window_link.$pdf_icon;
             }
@@ -288,18 +361,24 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
         //end copy files to users myfiles
     } else {
         //Icon column
-        if (preg_match('/shared_folder/', urldecode($url)) && preg_match('/shared_folder$/', urldecode($url)) == false && preg_match('/shared_folder_session_'.$current_session_id.'$/', urldecode($url)) == false) {
+        if (preg_match('/shared_folder/', urldecode($url)) && preg_match(
+            '/shared_folder$/',
+            urldecode($url)
+        ) == false && preg_match('/shared_folder_session_'.$current_session_id.'$/', urldecode($url)) == false
+        ) {
             if ($filetype == 'file') {
                 //Sound preview with jplayer
                 if (preg_match('/mp3$/i', urldecode($url)) ||
                     (preg_match('/wav$/i', urldecode($url)) && !preg_match('/_chnano_.wav$/i', urldecode($url))) ||
-                    preg_match('/ogg$/i', urldecode($url))) {
+                    preg_match('/ogg$/i', urldecode($url))
+                ) {
                     $sound_preview = DocumentManager::generate_media_preview($counter);
+
                     return $sound_preview;
                 } elseif (
-                //Show preview
-                //preg_match('/html$/i', urldecode($url))  ||
-                //preg_match('/htm$/i',  urldecode($url))  ||
+                    //Show preview
+                    //preg_match('/html$/i', urldecode($url))  ||
+                    //preg_match('/htm$/i',  urldecode($url))  ||
                     preg_match('/swf$/i', urldecode($url)) ||
                     preg_match('/png$/i', urldecode($url)) ||
                     preg_match('/gif$/i', urldecode($url)) ||
@@ -307,26 +386,41 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
                     preg_match('/jpeg$/i', urldecode($url)) ||
                     preg_match('/bmp$/i', urldecode($url)) ||
                     preg_match('/svg$/i', urldecode($url)) ||
-                    (preg_match('/wav$/i', urldecode($url)) && preg_match('/_chnano_.wav$/i', urldecode($url)) && api_get_setting('enable_nanogong') == 'true')
+                    (preg_match('/wav$/i', urldecode($url)) && preg_match(
+                        '/_chnano_.wav$/i',
+                        urldecode($url)
+                    ) && api_get_setting('enable_nanogong') == 'true')
                 ) {
                     $url = 'showinframes.php?'.api_get_cidreq().'&id='.$document_data['id'].$req_gid;
-                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.build_document_icon_tag($filetype, $path).Display::return_icon('shared.png', get_lang('ResourceShared'), array()).'</a>';
+
+                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.build_document_icon_tag(
+                        $filetype,
+                        $path
+                    ).Display::return_icon('shared.png', get_lang('ResourceShared'), array()).'</a>';
                 } else {
-                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.build_document_icon_tag($filetype, $path).Display::return_icon('shared.png', get_lang('ResourceShared'), array()).'</a>';
+                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.build_document_icon_tag(
+                        $filetype,
+                        $path
+                    ).Display::return_icon('shared.png', get_lang('ResourceShared'), array()).'</a>';
                 }
             } else {
-                return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" target="'.$target.'"'.$visibility_class.' style="float:left">'.build_document_icon_tag($filetype, $path).Display::return_icon('shared.png', get_lang('ResourceShared'), array()).'</a>';
+                return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" target="'.$target.'"'.$visibility_class.' style="float:left">'.build_document_icon_tag(
+                    $filetype,
+                    $path
+                ).Display::return_icon('shared.png', get_lang('ResourceShared'), array()).'</a>';
             }
         } else {
             if ($filetype == 'file') {
                 //Sound preview with jplayer
                 if (preg_match('/mp3$/i', urldecode($url)) ||
                     (preg_match('/wav$/i', urldecode($url)) && !preg_match('/_chnano_.wav$/i', urldecode($url))) ||
-                    preg_match('/ogg$/i', urldecode($url))) {
+                    preg_match('/ogg$/i', urldecode($url))
+                ) {
                     $sound_preview = DocumentManager::generate_media_preview($counter);
+
                     return $sound_preview;
                 } elseif (
-                //Show preview
+                    //Show preview
                     preg_match('/html$/i', urldecode($url)) ||
                     preg_match('/htm$/i', urldecode($url)) ||
                     preg_match('/swf$/i', urldecode($url)) ||
@@ -336,15 +430,27 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
                     preg_match('/jpeg$/i', urldecode($url)) ||
                     preg_match('/bmp$/i', urldecode($url)) ||
                     preg_match('/svg$/i', urldecode($url)) ||
-                    (preg_match('/wav$/i', urldecode($url)) && preg_match('/_chnano_.wav$/i', urldecode($url)) && api_get_setting('enable_nanogong') == 'true')
+                    (preg_match('/wav$/i', urldecode($url)) && preg_match(
+                        '/_chnano_.wav$/i',
+                        urldecode($url)
+                    ) && api_get_setting('enable_nanogong') == 'true')
                 ) {
                     $url = 'showinframes.php?'.api_get_cidreq().'&id='.$document_data['id'].$req_gid; //without preview
-                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.build_document_icon_tag($filetype, $path).'</a>';
+                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.build_document_icon_tag(
+                        $filetype,
+                        $path
+                    ).'</a>';
                 } else {
-                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.build_document_icon_tag($filetype, $path).'</a>';
+                    return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" '.$visibility_class.' style="float:left">'.build_document_icon_tag(
+                        $filetype,
+                        $path
+                    ).'</a>';
                 }
             } else {
-                return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" target="'.$target.'"'.$visibility_class.' style="float:left">'.build_document_icon_tag($filetype, $path).'</a>';
+                return '<a href="'.$url.'" title="'.$tooltip_title_alt.'" target="'.$target.'"'.$visibility_class.' style="float:left">'.build_document_icon_tag(
+                    $filetype,
+                    $path
+                ).'</a>';
             }
         }
     }
@@ -510,18 +616,44 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
     if ($is_read_only /* or ($session_id!=api_get_session_id()) */) {
         if (api_is_course_admin() || api_is_platform_admin()) {
             if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
-                $modify_icons = '<a href="edit_draw.php?'.api_get_cidreq().'&id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
-            } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
-                $modify_icons = '<a href="edit_paint.php?'.api_get_cidreq().'&id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
+                $modify_icons = '<a href="edit_draw.php?'.api_get_cidreq(
+                ).'&id='.$document_id.$req_gid.'">'.Display::return_icon(
+                    'edit.png',
+                    get_lang('Modify'),
+                    '',
+                    ICON_SIZE_SMALL
+                ).'</a>';
+            } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting(
+                'enabled_support_pixlr'
+            ) == 'true'
+            ) {
+                $modify_icons = '<a href="edit_paint.php?'.api_get_cidreq(
+                ).'&id='.$document_id.$req_gid.'">'.Display::return_icon(
+                    'edit.png',
+                    get_lang('Modify'),
+                    '',
+                    ICON_SIZE_SMALL
+                ).'</a>';
             } else {
-                $modify_icons = '<a href="edit_document.php?'.api_get_cidreq().'&id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
+                $modify_icons = '<a href="edit_document.php?'.api_get_cidreq(
+                ).'&id='.$document_id.$req_gid.'">'.Display::return_icon(
+                    'edit.png',
+                    get_lang('Modify'),
+                    '',
+                    ICON_SIZE_SMALL
+                ).'</a>';
             }
         } else {
             $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
         }
         $modify_icons .= '&nbsp;'.Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL);
         if (api_is_allowed_to_edit() || api_is_platform_admin()) {
-            $modify_icons .= '&nbsp;'.Display::return_icon($visibility_icon.'.png', get_lang('VisibilityCannotBeChanged'), '', ICON_SIZE_SMALL);
+            $modify_icons .= '&nbsp;'.Display::return_icon(
+                $visibility_icon.'.png',
+                get_lang('VisibilityCannotBeChanged'),
+                '',
+                ICON_SIZE_SMALL
+            );
         }
         $modify_icons .= '&nbsp;'.Display::return_icon('delete_na.png', get_lang('Delete'), array(), ICON_SIZE_SMALL);
     } else {
@@ -530,49 +662,135 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
             $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
         } elseif ($is_certificate_mode) {
             // gradebook category doesn't seem to be taken into account
-            $modify_icons = '<a href="edit_document.php?'.api_get_cidreq().'&amp;id='.$document_id.$req_gid.'&curdirpath=/certificates">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
+            $modify_icons = '<a href="edit_document.php?'.api_get_cidreq(
+            ).'&amp;id='.$document_id.$req_gid.'&curdirpath=/certificates">'.Display::return_icon(
+                'edit.png',
+                get_lang('Modify'),
+                '',
+                ICON_SIZE_SMALL
+            ).'</a>';
         } else {
             if (api_get_session_id()) {
                 if ($document_data['session_id'] == api_get_session_id()) {
-                    if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
-                        $modify_icons = '<a href="edit_draw.php?'.api_get_cidreq().'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
-                    } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
-                        $modify_icons = '<a href="edit_paint.php?'.api_get_cidreq().'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
+                    if ($extension == 'svg' && api_browser_support('svg') && api_get_setting(
+                        'enabled_support_svg'
+                    ) == 'true'
+                    ) {
+                        $modify_icons = '<a href="edit_draw.php?'.api_get_cidreq(
+                        ).'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon(
+                            'edit.png',
+                            get_lang('Modify'),
+                            '',
+                            ICON_SIZE_SMALL
+                        ).'</a>';
+                    } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting(
+                        'enabled_support_pixlr'
+                    ) == 'true'
+                    ) {
+                        $modify_icons = '<a href="edit_paint.php?'.api_get_cidreq(
+                        ).'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon(
+                            'edit.png',
+                            get_lang('Modify'),
+                            '',
+                            ICON_SIZE_SMALL
+                        ).'</a>';
                     } else {
-                        $modify_icons = '<a href="edit_document.php?'.api_get_cidreq().'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
+                        $modify_icons = '<a href="edit_document.php?'.api_get_cidreq(
+                        ).'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon(
+                            'edit.png',
+                            get_lang('Modify'),
+                            '',
+                            ICON_SIZE_SMALL
+                        ).'</a>';
                     }
                 } else {
-                    $modify_icons .= '&nbsp;'.Display::return_icon('edit_na.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>';
+                    $modify_icons .= '&nbsp;'.Display::return_icon(
+                        'edit_na.png',
+                        get_lang('Edit'),
+                        array(),
+                        ICON_SIZE_SMALL
+                    ).'</a>';
                 }
             } else {
-                if ($extension == 'svg' && api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
-                    $modify_icons = '<a href="edit_draw.php?'.api_get_cidreq().'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
-                } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting('enabled_support_pixlr') == 'true') {
-                    $modify_icons = '<a href="edit_paint.php?'.api_get_cidreq().'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
+                if ($extension == 'svg' && api_browser_support('svg') && api_get_setting(
+                    'enabled_support_svg'
+                ) == 'true'
+                ) {
+                    $modify_icons = '<a href="edit_draw.php?'.api_get_cidreq(
+                    ).'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon(
+                        'edit.png',
+                        get_lang('Modify'),
+                        '',
+                        ICON_SIZE_SMALL
+                    ).'</a>';
+                } elseif ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'bmp' || $extension == 'gif' || $extension == 'pxd' && api_get_setting(
+                    'enabled_support_pixlr'
+                ) == 'true'
+                ) {
+                    $modify_icons = '<a href="edit_paint.php?'.api_get_cidreq(
+                    ).'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon(
+                        'edit.png',
+                        get_lang('Modify'),
+                        '',
+                        ICON_SIZE_SMALL
+                    ).'</a>';
                 } else {
-                    $modify_icons = '<a href="edit_document.php?'.api_get_cidreq().'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL).'</a>';
+                    $modify_icons = '<a href="edit_document.php?'.api_get_cidreq(
+                    ).'&amp;id='.$document_id.$req_gid.'">'.Display::return_icon(
+                        'edit.png',
+                        get_lang('Modify'),
+                        '',
+                        ICON_SIZE_SMALL
+                    ).'</a>';
                 }
             }
         }
 
         //Move button
         if ($is_certificate_mode || in_array($path, DocumentManager::get_system_folders())) {
-            $modify_icons .= '&nbsp;'.Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL).'</a>';
+            $modify_icons .= '&nbsp;'.Display::return_icon(
+                'move_na.png',
+                get_lang('Move'),
+                array(),
+                ICON_SIZE_SMALL
+            ).'</a>';
         } else {
             if (api_get_session_id()) {
                 if ($document_data['session_id'] == api_get_session_id()) {
-                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;id='.$parent_id.'&amp;move='.$document_id.$req_gid.'">'.Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL).'</a>';
+                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                    ).'&amp;id='.$parent_id.'&amp;move='.$document_id.$req_gid.'">'.Display::return_icon(
+                        'move.png',
+                        get_lang('Move'),
+                        array(),
+                        ICON_SIZE_SMALL
+                    ).'</a>';
                 } else {
-                    $modify_icons .= '&nbsp;'.Display::return_icon('move_na.png', get_lang('Move'), array(), ICON_SIZE_SMALL).'</a>';
+                    $modify_icons .= '&nbsp;'.Display::return_icon(
+                        'move_na.png',
+                        get_lang('Move'),
+                        array(),
+                        ICON_SIZE_SMALL
+                    ).'</a>';
                 }
             } else {
-                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;id='.$parent_id.'&amp;move='.$document_id.$req_gid.'">'.Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL).'</a>';
+                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                ).'&amp;id='.$parent_id.'&amp;move='.$document_id.$req_gid.'">'.Display::return_icon(
+                    'move.png',
+                    get_lang('Move'),
+                    array(),
+                    ICON_SIZE_SMALL
+                ).'</a>';
             }
         }
 
         //Visibility button
         if ($is_certificate_mode) {
-            $modify_icons .= '&nbsp;'.Display::return_icon($visibility_icon.'.png', get_lang('VisibilityCannotBeChanged'), array(), ICON_SIZE_SMALL).'</a>';
+            $modify_icons .= '&nbsp;'.Display::return_icon(
+                $visibility_icon.'.png',
+                get_lang('VisibilityCannotBeChanged'),
+                array(),
+                ICON_SIZE_SMALL
+            ).'</a>';
         } else {
             if (api_is_allowed_to_edit() || api_is_platform_admin()) {
                 if ($visibility_icon == 'invisible') {
@@ -580,28 +798,77 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
                 } else {
                     $tip_visibility = get_lang('Hide');
                 }
-                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;id='.$parent_id.'&amp;'.$visibility_command.'='.$id.$req_gid.'&amp;'.$sort_params.'">'.Display::return_icon($visibility_icon.'.png', $tip_visibility, '', ICON_SIZE_SMALL).'</a>';
+                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                ).'&amp;id='.$parent_id.'&amp;'.$visibility_command.'='.$id.$req_gid.'&amp;'.$sort_params.'">'.Display::return_icon(
+                    $visibility_icon.'.png',
+                    $tip_visibility,
+                    '',
+                    ICON_SIZE_SMALL
+                ).'</a>';
             }
         }
 
         //Delete button
         if (in_array($path, DocumentManager::get_system_folders())) {
-            $modify_icons .= '&nbsp;'.Display::return_icon('delete_na.png', get_lang('ThisFolderCannotBeDeleted'), array(), ICON_SIZE_SMALL);
+            $modify_icons .= '&nbsp;'.Display::return_icon(
+                'delete_na.png',
+                get_lang('ThisFolderCannotBeDeleted'),
+                array(),
+                ICON_SIZE_SMALL
+            );
         } else {
-            if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates' && DocumentManager::get_default_certificate_id(api_get_course_id()) == $id) {
-                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.$curdirpath.'&amp;delete='.urlencode($path).$req_gid.'&amp;'.$sort_params.'delete_certificate_id='.$id.'" onclick="return confirmation(\''.basename($path).'\');">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
+            if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates' && DocumentManager::get_default_certificate_id(
+                api_get_course_id()
+            ) == $id
+            ) {
+                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                ).'&amp;curdirpath='.$curdirpath.'&amp;delete='.urlencode(
+                    $path
+                ).$req_gid.'&amp;'.$sort_params.'delete_certificate_id='.$id.'" onclick="return confirmation(\''.basename(
+                    $path
+                ).'\');">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
             } else {
                 if ($is_certificate_mode) {
-                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.$curdirpath.'&amp;delete='.urlencode($path).$req_gid.'&amp;'.$sort_params.'" onclick="return confirmation(\''.basename($path).'\');">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
+                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                    ).'&amp;curdirpath='.$curdirpath.'&amp;delete='.urlencode(
+                        $path
+                    ).$req_gid.'&amp;'.$sort_params.'" onclick="return confirmation(\''.basename(
+                        $path
+                    ).'\');">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
                 } else {
                     if (api_get_session_id()) {
                         if ($document_data['session_id'] == api_get_session_id()) {
-                            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.$curdirpath.'&amp;delete='.urlencode($path).$req_gid.'&amp;'.$sort_params.'" onclick="return confirmation(\''.basename($path).'\');">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
+                            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                            ).'&amp;curdirpath='.$curdirpath.'&amp;delete='.urlencode(
+                                $path
+                            ).$req_gid.'&amp;'.$sort_params.'" onclick="return confirmation(\''.basename(
+                                $path
+                            ).'\');">'.Display::return_icon(
+                                'delete.png',
+                                get_lang('Delete'),
+                                array(),
+                                ICON_SIZE_SMALL
+                            ).'</a>';
                         } else {
-                            $modify_icons .= '&nbsp;'.Display::return_icon('delete_na.png', get_lang('ThisFolderCannotBeDeleted'), array(), ICON_SIZE_SMALL);
+                            $modify_icons .= '&nbsp;'.Display::return_icon(
+                                'delete_na.png',
+                                get_lang('ThisFolderCannotBeDeleted'),
+                                array(),
+                                ICON_SIZE_SMALL
+                            );
                         }
                     } else {
-                        $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.$curdirpath.'&amp;delete='.urlencode($path).$req_gid.'&amp;'.$sort_params.'" onclick="return confirmation(\''.basename($path).'\');">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
+                        $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                        ).'&amp;curdirpath='.$curdirpath.'&amp;delete='.urlencode(
+                            $path
+                        ).$req_gid.'&amp;'.$sort_params.'" onclick="return confirmation(\''.basename(
+                            $path
+                        ).'\');">'.Display::return_icon(
+                            'delete.png',
+                            get_lang('Delete'),
+                            array(),
+                            ICON_SIZE_SMALL
+                        ).'</a>';
                     }
                 }
             }
@@ -611,9 +878,15 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
     if ($type == 'file' && ($extension == 'html' || $extension == 'htm')) {
         if ($is_template == 0) {
             if ((isset($_GET['curdirpath']) && $_GET['curdirpath'] != '/certificates') || !isset($_GET['curdirpath'])) {
-                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.$curdirpath.'&amp;add_as_template='.$id.$req_gid.'&amp;'.$sort_params.'">'.Display::return_icon('wizard.png', get_lang('AddAsTemplate'), array(), ICON_SIZE_SMALL).'</a>';
+                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                ).'&amp;curdirpath='.$curdirpath.'&amp;add_as_template='.$id.$req_gid.'&amp;'.$sort_params.'">'.Display::return_icon(
+                    'wizard.png',
+                    get_lang('AddAsTemplate'),
+                    array(),
+                    ICON_SIZE_SMALL
+                ).'</a>';
             }
-            if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates') {//allow attach certificate to course
+            if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates') { //allow attach certificate to course
                 $visibility_icon_certificate = 'nocertificate';
                 if (DocumentManager::get_default_certificate_id(api_get_course_id()) == $id) {
                     $visibility_icon_certificate = 'certificate';
@@ -625,19 +898,31 @@ function build_edit_icons($document_data, $id, $is_template, $is_read_only = 0,
                     $certificate = get_lang('NoDefaultCertificate');
                 }
                 if (isset($_GET['selectcat'])) {
-                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.$curdirpath.'&amp;selectcat='.Security::remove_XSS($_GET['selectcat']).'&amp;set_certificate='.$id.$req_gid.'&amp;'.$sort_params.'"><img src="../img/'.$visibility_icon_certificate.'.png" border="0" title="'.$certificate.'" alt="" /></a>';
+                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+                    ).'&amp;curdirpath='.$curdirpath.'&amp;selectcat='.Security::remove_XSS(
+                        $_GET['selectcat']
+                    ).'&amp;set_certificate='.$id.$req_gid.'&amp;'.$sort_params.'"><img src="../img/'.$visibility_icon_certificate.'.png" border="0" title="'.$certificate.'" alt="" /></a>';
                     if ($is_preview) {
-                        $modify_icons .= '&nbsp;<a target="_blank"  href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.$curdirpath.'&amp;set_preview='.$id.$req_gid.'&amp;'.$sort_params.'" >'.
+                        $modify_icons .= '&nbsp;<a target="_blank"  href="'.api_get_self().'?'.api_get_cidreq(
+                        ).'&amp;curdirpath='.$curdirpath.'&amp;set_preview='.$id.$req_gid.'&amp;'.$sort_params.'" >'.
                             Display::return_icon('preview_view.png', $preview, '', ICON_SIZE_SMALL).'</a>';
                     }
                 }
             }
         } else {
-            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&curdirpath='.$curdirpath.'&amp;remove_as_template='.$id.$req_gid.'&amp;'.$sort_params.'">'.
+            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+            ).'&curdirpath='.$curdirpath.'&amp;remove_as_template='.$id.$req_gid.'&amp;'.$sort_params.'">'.
                 Display::return_icon('wizard_na.png', get_lang('RemoveAsTemplate'), '', ICON_SIZE_SMALL).'</a>';
         }
-        $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&action=export_to_pdf&id='.$id.'">'.Display::return_icon('pdf.png', get_lang('Export2PDF'), array(), ICON_SIZE_SMALL).'</a>';
+        $modify_icons .= '&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq(
+        ).'&action=export_to_pdf&id='.$id.'">'.Display::return_icon(
+            'pdf.png',
+            get_lang('Export2PDF'),
+            array(),
+            ICON_SIZE_SMALL
+        ).'</a>';
     }
+
     return $modify_icons;
 }
 
@@ -664,11 +949,21 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
                     continue;
                 }
                 //Admin setting for Hide/Show the folders of all users
-                if (api_get_setting('show_users_folders') == 'false' && (strstr($folder, '/shared_folder') || strstr($folder, 'shared_folder_session_'))) {
+                if (api_get_setting('show_users_folders') == 'false' && (strstr($folder, '/shared_folder') || strstr(
+                    $folder,
+                    'shared_folder_session_'
+                ))
+                ) {
                     continue;
                 }
                 //Admin setting for Hide/Show Default folders to all users
-                if (api_get_setting('show_default_folders') == 'false' && ($folder == '/images' || $folder == '/flash' || $folder == '/audio' || $folder == '/video' || strstr($folder, '/images/gallery') || $folder == '/video/flv')) {
+                if (api_get_setting(
+                    'show_default_folders'
+                ) == 'false' && ($folder == '/images' || $folder == '/flash' || $folder == '/audio' || $folder == '/video' || strstr(
+                    $folder,
+                    '/images/gallery'
+                ) || $folder == '/video/flv')
+                ) {
                     continue;
                 }
                 //Admin setting for Hide/Show chat history folder
@@ -680,7 +975,12 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
                 // 1. current directory
                 // 2. inside the folder you want to move
                 // 3. inside a subfolder of the folder you want to move
-                if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')) {
+                if (($curdirpath != $folder) && ($folder != $move_file) && (substr(
+                    $folder,
+                    0,
+                    strlen($move_file) + 1
+                ) != $move_file.'/')
+                ) {
                     $path_displayed = $folder;
                     // If document title is used, we have to display titles instead of real paths...
                     $path_displayed = get_titles_of_path($folder);
@@ -695,7 +995,12 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
         }
     } else {
         foreach ($folders as $folder) {
-            if (($curdirpath != $folder) && ($folder != $move_file) && (substr($folder, 0, strlen($move_file) + 1) != $move_file.'/')) { // Cannot copy dir into his own subdir
+            if (($curdirpath != $folder) && ($folder != $move_file) && (substr(
+                $folder,
+                0,
+                strlen($move_file) + 1
+            ) != $move_file.'/')
+            ) { // Cannot copy dir into his own subdir
                 $path_displayed = get_titles_of_path($folder);
                 $display_folder = substr($path_displayed, strlen($group_dir));
                 $display_folder = ($display_folder == '') ? get_lang('Documents') : $display_folder;
@@ -706,6 +1011,7 @@ function build_move_to_selector($folders, $curdirpath, $move_file, $group_dir =
     }
     $form->addElement('select', 'move_to', get_lang('MoveTo'), $options);
     $form->addElement('button', 'move_file_submit', get_lang('MoveElement'));
+
     return $form->return_form();
 }
 
@@ -745,6 +1051,7 @@ function get_titles_of_path($path)
             $tmp_folders_titles[$tmp_path] = $tmp_title;
         }
     }
+
     return $path_displayed;
 }
 
@@ -768,7 +1075,7 @@ function display_user_link_document($user_id, $name)
 
 /**
  * Creates form that asks for the directory name.
- * @return string	html-output text for the form
+ * @return string    html-output text for the form
  */
 function create_dir_form($current_dir_id)
 {
@@ -782,6 +1089,7 @@ function create_dir_form($current_dir_id)
     $form->addElement('text', 'dirname', get_lang('NewDir'));
     $form->addElement('style_submit_button', 'submit', get_lang('CreateFolder'), 'class="add"');
     $new_folder_text = $form->return_form();
+
     return $new_folder_text;
 }
 
@@ -857,12 +1165,37 @@ function search_keyword($document_name, $keyword)
 function is_browser_viewable($file_extension)
 {
     static $allowed_extensions = array(
-    'htm', 'html', 'xhtml',
-    'gif', 'jpg', 'jpeg', 'png', 'tif', 'tiff',
-    'pdf', 'svg', 'swf',
-    'txt', 'log',
-    'mp4', 'ogg', 'ogv', 'ogx', 'mpg', 'mpeg', 'mov', 'avi', 'webm', 'wmv',
-    'mp3', 'oga', 'wav', 'au', 'wma', 'mid', 'kar'
+        'htm',
+        'html',
+        'xhtml',
+        'gif',
+        'jpg',
+        'jpeg',
+        'png',
+        'tif',
+        'tiff',
+        'pdf',
+        'svg',
+        'swf',
+        'txt',
+        'log',
+        'mp4',
+        'ogg',
+        'ogv',
+        'ogx',
+        'mpg',
+        'mpeg',
+        'mov',
+        'avi',
+        'webm',
+        'wmv',
+        'mp3',
+        'oga',
+        'wav',
+        'au',
+        'wma',
+        'mid',
+        'kar'
     );
 
     /*
@@ -913,6 +1246,7 @@ function is_browser_viewable($file_extension)
     } elseif ($file_extension == "webm") {
         return api_browser_support('webm');
     }
+
     return $result;
 }
 
@@ -958,12 +1292,28 @@ function check_and_create_resource_directory($repository_path, $resource_directo
                 global $group_properties, $to_group_id;
                 $group_directory = !empty($group_properties['directory']) ? $group_properties['directory'] : '';
 
-                $doc_id = add_document($_course, $group_directory.$resource_directory, 'folder', 0, $resource_directory_name);
-                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'], $to_group_id);
+                $doc_id = FileManager::add_document(
+                    $_course,
+                    $group_directory.$resource_directory,
+                    'folder',
+                    0,
+                    $resource_directory_name
+                );
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $doc_id,
+                    'FolderCreated',
+                    $_user['user_id'],
+                    $to_group_id
+                );
             }
+
             return true;
         }
+
         return false;
     }
+
     return true;
 }

Fișier diff suprimat deoarece este prea mare
+ 425 - 162
main/document/document.php


Fișier diff suprimat deoarece este prea mare
+ 445 - 231
main/document/document_lite.php


+ 434 - 303
main/document/edit_document.php

@@ -38,29 +38,29 @@ require_once '../inc/global.inc.php';
 // Template's javascript
 $htmlHeadXtra[] = '
 <script>
-var hide_bar = function() {    
-    $("#template_col").hide(); 
-    $("#doc_form").removeClass("span9"); 
-    $("#doc_form").addClass("span11");   
+var hide_bar = function() {
+    $("#template_col").hide();
+    $("#doc_form").removeClass("span9");
+    $("#doc_form").addClass("span11");
     $("#hide_bar_template").css({"background-image" : \'url("../img/hide2.png")\'})
 }
 
-$(document).ready(function() {   
+$(document).ready(function() {
     if ($(window).width() <= 785 ) {
         hide_bar();
     }
-    
+
     $("#hide_bar_template").toggle(
-        function() { 
+        function() {
             hide_bar();
         },
-        function() { 
-            $("#template_col").show(); 
-            $("#doc_form").removeClass("span11"); 
-            $("#doc_form").addClass("span9"); 
-            $(this).css("background-image", \'url("../img/hide0.png")\'); 
-        }            
-    );    
+        function() {
+            $("#template_col").show();
+            $("#doc_form").removeClass("span11");
+            $("#doc_form").addClass("span9");
+            $(this).css("background-image", \'url("../img/hide0.png")\');
+        }
+    );
 });
 
 function InnerDialogLoaded() {
@@ -92,7 +92,9 @@ function InnerDialogLoaded() {
 };
 
 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 \'>";
+	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>';
 
@@ -100,35 +102,33 @@ $_SESSION['whereami'] = 'document/create';
 $this_section = SECTION_COURSES;
 $lib_path = api_get_path(LIBRARY_PATH);
 
-require_once $lib_path.'fileManage.lib.php';
-require_once $lib_path.'fileUpload.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'document/document.inc.php';
 
 $course_info = api_get_course_info();
 $group_id = api_get_group_id();
 
 if (api_is_in_group()) {
-	$group_properties = GroupManager::get_group_properties($group_id);
+    $group_properties = GroupManager::get_group_properties($group_id);
 }
 
 $dir = '/';
 
 if (isset($_GET['id'])) {
-    $document_data  = DocumentManager::get_document_data_by_id($_GET['id'], api_get_course_id(), true);
-    $document_id    = $document_data['id'];
-    $file           = $document_data['path'];
-    $parent_id      = DocumentManager::get_document_id($course_info, dirname($file));    
-    $dir            = dirname($document_data['path']);    
-    $dir_original   =  $dir;
-    
-    $doc            = basename($file);
+    $document_data = DocumentManager::get_document_data_by_id($_GET['id'], api_get_course_id(), true);
+    $document_id = $document_data['id'];
+    $file = $document_data['path'];
+    $parent_id = DocumentManager::get_document_id($course_info, dirname($file));
+    $dir = dirname($document_data['path']);
+    $dir_original = $dir;
+
+    $doc = basename($file);
     $my_cur_dir_path = Security::remove_XSS($_GET['curdirpath']);
-    $readonly       = $document_data['readonly'];
+    $readonly = $document_data['readonly'];
 }
 
 if (empty($document_data)) {
     api_not_allowed();
-}  
+}
 
 $is_certificate_mode = DocumentManager::is_certificate_mode($dir);
 
@@ -148,33 +148,36 @@ $count_dir = count($doc_tree) - 2; // "2" because at the begin and end there are
 
 // Level correction for group documents.
 if (!empty($group_properties['directory'])) {
-	$count_dir = $count_dir > 0 ? $count_dir - 1 : 0;
+    $count_dir = $count_dir > 0 ? $count_dir - 1 : 0;
 }
 $relative_url = '';
 for ($i = 0; $i < ($count_dir); $i++) {
-	$relative_url .= '../';
+    $relative_url .= '../';
 }
 
 $html_editor_config = array(
-	'ToolbarSet' => (api_is_allowed_to_edit(null, true) ? 'Documents' :'DocumentsStudent'),
-	'Width' => '100%',
-	'Height' => '600',
-	'FullPage' => true,
-	'InDocument' => true,
-	'CreateDocumentDir' => $relative_url,
-	'CreateDocumentWebDir' => (empty($group_properties['directory']))
-		? api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/'
-		: api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/',
-	'BaseHref' =>  api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir
+    'ToolbarSet' => (api_is_allowed_to_edit(null, true) ? 'Documents' : 'DocumentsStudent'),
+    'Width' => '100%',
+    'Height' => '600',
+    'FullPage' => true,
+    'InDocument' => true,
+    'CreateDocumentDir' => $relative_url,
+    'CreateDocumentWebDir' => (empty($group_properties['directory']))
+        ? api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/'
+        : api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/',
+    'BaseHref' => api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir
 );
 
 if ($is_certificate_mode) {
-    $html_editor_config['CreateDocumentDir']    = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/';
+    $html_editor_config['CreateDocumentDir'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/';
     $html_editor_config['CreateDocumentWebDir'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/';
-    $html_editor_config['BaseHref']             = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir;
+    $html_editor_config['BaseHref'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir;
 }
 
-$is_allowed_to_edit = api_is_allowed_to_edit(null, true) || $_SESSION['group_member_with_upload_rights']|| is_my_shared_folder(api_get_user_id(), $dir, $current_session_id);
+$is_allowed_to_edit = api_is_allowed_to_edit(
+    null,
+    true
+) || $_SESSION['group_member_with_upload_rights'] || is_my_shared_folder(api_get_user_id(), $dir, $current_session_id);
 $noPHP_SELF = true;
 
 /*	Other initialization code */
@@ -183,22 +186,29 @@ $dbTable = Database::get_course_table(TABLE_DOCUMENT);
 $course_id = api_get_course_int_id();
 
 if (!empty($group_id)) {
-	$req_gid = '&amp;gidReq='.$group_id;
-	$interbreadcrumb[] = array ('url' => '../group/group_space.php?gidReq='.$group_id, 'name' => get_lang('GroupSpace'));
-	$group_document = true;
-	$noPHP_SELF = true;
+    $req_gid = '&amp;gidReq='.$group_id;
+    $interbreadcrumb[] = array('url' => '../group/group_space.php?gidReq='.$group_id, 'name' => get_lang('GroupSpace'));
+    $group_document = true;
+    $noPHP_SELF = true;
 }
 
-if (!$is_certificate_mode)
-	$interbreadcrumb[]=array("url"=>"./document.php?curdirpath=".urlencode($my_cur_dir_path).$req_gid, "name"=> get_lang('Documents'));
-else
-	$interbreadcrumb[]= array (	'url' => '../gradebook/'.$_SESSION['gradebook_dest'], 'name' => get_lang('Gradebook'));
+if (!$is_certificate_mode) {
+    $interbreadcrumb[] = array(
+        "url" => "./document.php?curdirpath=".urlencode($my_cur_dir_path).$req_gid,
+        "name" => get_lang('Documents')
+    );
+} else {
+    $interbreadcrumb[] = array(
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+        'name' => get_lang('Gradebook')
+    );
+}
 
 // Interbreadcrumb for the current directory root path
 if (empty($document_data['parents'])) {
     $interbreadcrumb[] = array('url' => '#', 'name' => $document_data['title']);
-} else {    
-    foreach($document_data['parents'] as $document_sub_data) {
+} else {
+    foreach ($document_data['parents'] as $document_sub_data) {
         if ($document_data['title'] == $document_sub_data['title']) {
             continue;
         }
@@ -207,16 +217,16 @@ if (empty($document_data['parents'])) {
 }
 
 if (!is_allowed_to_edit) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 event_access_tool(TOOL_DOCUMENT);
 
 //TODO:check the below code and his funcionality
 if (!is_allowed_to_edit()) {
-	if (DocumentManager::check_readonly($course_info, $user_id, $file)) {
-		api_not_allowed();
-	}
+    if (DocumentManager::check_readonly($course_info, $user_id, $file)) {
+        api_not_allowed();
+    }
 }
 
 /* MAIN TOOL CODE */
@@ -224,243 +234,321 @@ if (!is_allowed_to_edit()) {
 /*	Code to change the comment	*/
 
 if (isset($_POST['comment'])) {
-	// Fixing the path if it is wrong	
-	$comment 	     = trim(Database::escape_string($_POST['comment']));
-	$title 		     = trim(Database::escape_string($_POST['title'])); 
+    // Fixing the path if it is wrong
+    $comment = trim(Database::escape_string($_POST['comment']));
+    $title = trim(Database::escape_string($_POST['title']));
     //Just in case see BT#3525
     if (empty($title)) {
-		$title = $documen_data['title'];
-	}
-	if (empty($title)) {
-		$title = get_document_title($_POST['filename']);		
-	}
+        $title = $documen_data['title'];
+    }
+    if (empty($title)) {
+        $title = FileManager::get_document_title($_POST['filename']);
+    }
     if (!empty($document_id)) {
         $query = "UPDATE $dbTable SET comment='".$comment."', title='".$title."' WHERE c_id = $course_id AND id = ".$document_id;
-        Database::query($query);		
-        $info_message     = get_lang('fileModified');
+        Database::query($query);
+        $info_message = get_lang('fileModified');
     }
 }
 
 /*	WYSIWYG HTML EDITOR - Program Logic */
 if ($is_allowed_to_edit) {
-	if ($_POST['formSent'] == 1) {
-        
-		$filename   = stripslashes($_POST['filename']);
-        $extension  = $_POST['extension'];
-        
-		$content    = trim(str_replace(array("\r", "\n"), '', stripslashes($_POST['content'])));
-		$content    = Security::remove_XSS($content, COURSEMANAGERLOWSECURITY);
-
-		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 ($_POST['formSent'] == 1) {
+
+        $filename = stripslashes($_POST['filename']);
+        $extension = $_POST['extension'];
+
+        $content = trim(str_replace(array("\r", "\n"), '', stripslashes($_POST['content'])));
+        $content = Security::remove_XSS($content, COURSEMANAGERLOWSECURITY);
+
+        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 ($dir == '/') {
             $dir = '';
         }
-        
-		$file = $dir.'/'.$filename.'.'.$extension;        
-		$read_only_flag = $_POST['readonly'];
-		$read_only_flag = empty($read_only_flag) ? 0 : 1;
-		
-		if (empty($filename)) {
-			$msgError = get_lang('NoFileName');
-		} else {
-		    		    
-		    $file_size = filesize($document_data['absolute_path']);	    
-		    		    
-			if ($read_only_flag == 0) {
-				if (!empty($content)) {
-					if ($fp = @fopen($document_data['absolute_path'], 'w')) {						
-						// 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.
-						//$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.
-						//$content = preg_replace("|(flashvars=\"file=)([^/]+)/|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',$content);
-
- 						fputs($fp, $content);
-						fclose($fp);
-                        
+
+        $file = $dir.'/'.$filename.'.'.$extension;
+        $read_only_flag = $_POST['readonly'];
+        $read_only_flag = empty($read_only_flag) ? 0 : 1;
+
+        if (empty($filename)) {
+            $msgError = get_lang('NoFileName');
+        } else {
+
+            $file_size = filesize($document_data['absolute_path']);
+
+            if ($read_only_flag == 0) {
+                if (!empty($content)) {
+                    if ($fp = @fopen($document_data['absolute_path'], 'w')) {
+                        // 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.
+                        //$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.
+                        //$content = preg_replace("|(flashvars=\"file=)([^/]+)/|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',$content);
+
+                        fputs($fp, $content);
+                        fclose($fp);
+
                         $filepath = $document_data['absolute_parent_path'];
-                        
-						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', api_get_user_id(), null, null, null, null, $current_session_id);
-							api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_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', api_get_user_id(), null, null, null, null, $current_session_id);
-								api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id(), null, null, null, null, $current_session_id);
-							}
-						}
-
-						// "WHAT'S NEW" notification: update table item_property                        
-						$document_id = DocumentManager::get_document_id($_course, $file);   
-                                                
-						if ($document_id) {				
-							update_existing_document($_course, $document_id, $file_size, $read_only_flag);
-							api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', api_get_user_id(), null, null, null, null, $current_session_id);
-							// Update parent folders
-							item_property_update_on_folder($_course, $dir, api_get_user_id());							                            
-							header('Location: document.php?id='.$document_data['parent_id']);
+
+                        if (!is_dir($filepath.'css')) {
+                            mkdir($filepath.'css', api_get_permissions_for_new_directories());
+                            $doc_id = FileManager::add_document($_course, $dir.'css', 'folder', 0, 'css');
+                            api_item_property_update(
+                                $_course,
+                                TOOL_DOCUMENT,
+                                $doc_id,
+                                'FolderCreated',
+                                api_get_user_id(),
+                                null,
+                                null,
+                                null,
+                                null,
+                                $current_session_id
+                            );
+                            api_item_property_update(
+                                $_course,
+                                TOOL_DOCUMENT,
+                                $doc_id,
+                                'invisible',
+                                api_get_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 = FileManager::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',
+                                    api_get_user_id(),
+                                    null,
+                                    null,
+                                    null,
+                                    null,
+                                    $current_session_id
+                                );
+                                api_item_property_update(
+                                    $_course,
+                                    TOOL_DOCUMENT,
+                                    $doc_id,
+                                    'invisible',
+                                    api_get_user_id(),
+                                    null,
+                                    null,
+                                    null,
+                                    null,
+                                    $current_session_id
+                                );
+                            }
+                        }
+
+                        // "WHAT'S NEW" notification: update table item_property
+                        $document_id = DocumentManager::get_document_id($_course, $file);
+
+                        if ($document_id) {
+                            FileManager::update_existing_document($_course, $document_id, $file_size, $read_only_flag);
+                            api_item_property_update(
+                                $_course,
+                                TOOL_DOCUMENT,
+                                $document_id,
+                                'DocumentUpdated',
+                                api_get_user_id(),
+                                null,
+                                null,
+                                null,
+                                null,
+                                $current_session_id
+                            );
+                            // Update parent folders
+                            FileManager::item_property_update_on_folder($_course, $dir, api_get_user_id());
+                            header('Location: document.php?id='.$document_data['parent_id']);
                             exit;
-						} else {
-							$msgError = get_lang('Impossible');
-						}
-					} else {
-						$msgError = get_lang('Impossible');
-					}
-				} else {					
-					if ($document_id) {
-                        update_existing_document($_course, $document_id, $file_size, $read_only_flag);					
-					}
-				}
-			} else {
+                        } else {
+                            $msgError = get_lang('Impossible');
+                        }
+                    } else {
+                        $msgError = get_lang('Impossible');
+                    }
+                } else {
+                    if ($document_id) {
+                        FileManager::update_existing_document($_course, $document_id, $file_size, $read_only_flag);
+                    }
+                }
+            } else {
                 if ($document_id) {
-                    update_existing_document($_course, $document_id, $file_size, $read_only_flag);
-                }				
-			}
-		}
-	}
+                    FileManager::update_existing_document($_course, $document_id, $file_size, $read_only_flag);
+                }
+            }
+        }
+    }
 }
 
 // Replace relative paths by absolute web paths (e.g. './' => 'http://www.chamilo.org/courses/ABC/document/')
-if (file_exists($document_data['absolute_path'])) {	
+if (file_exists($document_data['absolute_path'])) {
     $path_info = pathinfo($document_data['absolute_path']);
-    $filename = $path_info['filename'];    
+    $filename = $path_info['filename'];
     $extension = $path_info['extension'];
 
-	if (in_array($extension, array('html', 'htm'))) {
-		$content = file($document_data['absolute_path']);
-		$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);
-	}
+    if (in_array($extension, array('html', 'htm'))) {
+        $content = file($document_data['absolute_path']);
+        $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') . ': '.Security::remove_XSS($document_data['title']);
+$nameTools = get_lang('EditDocument').': '.Security::remove_XSS($document_data['title']);
 Display::display_header($nameTools, 'Doc');
 
 if (isset($msgError)) {
-	Display::display_error_message($msgError);
+    Display::display_error_message($msgError);
 }
 
 if (isset($info_message)) {
-	Display::display_confirmation_message($info_message);
-	if (isset($_POST['origin'])) {
-		$slide_id = $_POST['origin_opt'];	
-		$call_from_tool = $_POST['origin'];
-	}
+    Display::display_confirmation_message($info_message);
+    if (isset($_POST['origin'])) {
+        $slide_id = $_POST['origin_opt'];
+        $call_from_tool = $_POST['origin'];
+    }
 }
 
 // Owner
-$document_info  = api_get_item_property_info(api_get_course_int_id(),'document', $document_id);
-$owner_id       = $document_info['insert_user_id'];
+$document_info = api_get_item_property_info(api_get_course_int_id(), 'document', $document_id);
+$owner_id = $document_info['insert_user_id'];
 $last_edit_date = $document_info['lastedit_date'];
 
-if ($owner_id == api_get_user_id() || api_is_platform_admin() || $is_allowed_to_edit || GroupManager :: is_user_in_group(api_get_user_id(), api_get_group_id() )) {	
-	$action = api_get_self().'?id='.$document_data['id'];
-	$form = new FormValidator('formEdit', 'post', $action, null, array('class' => 'form-vertical'));
-
-	// Form title
-	$form->addElement('header', $nameTools);
-	$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 ($owner_id == api_get_user_id() || api_is_platform_admin(
+) || $is_allowed_to_edit || GroupManager :: is_user_in_group(api_get_user_id(), api_get_group_id())
+) {
+    $action = api_get_self().'?id='.$document_data['id'];
+    $form = new FormValidator('formEdit', 'post', $action, null, array('class' => 'form-vertical'));
+
+    // Form title
+    $form->addElement('header', $nameTools);
+    $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->add_textfield('title', get_lang('Title'));
-    
-	$defaults['title'] = $document_data['title'];
-
-	$form->addElement('hidden', 'formSent');
-	$defaults['formSent'] = 1;
-
-	$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['content'] = str_replace('<!--[', '<!-- [', $content);
-
-	//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;
-            $form->add_html_editor('content','', false, false, $html_editor_config);
-			//$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 && !is_my_shared_folder(api_get_user_id(), $my_cur_dir_path, $current_session_id)) {
-		$metadata_link = '<a href="../metadata/index.php?eid='.urlencode('Document.'.$document_data['id']).'">'.get_lang('AddMetadata').'</a>';
+    $defaults['title'] = $document_data['title'];
 
-		//Updated on field
-		$last_edit_date = api_get_local_time($last_edit_date);
-        $display_date = date_to_str_ago($last_edit_date).' <span class="dropbox_date">'.api_format_date($last_edit_date).'</span>';        
-		$form->addElement('static', null, get_lang('Metadata'), $metadata_link);
-		$form->addElement('static', null, get_lang('UpdatedOn'), $display_date);
-	}
+    $form->addElement('hidden', 'formSent');
+    $defaults['formSent'] = 1;
 
-	$form->addElement('textarea', 'comment', get_lang('Comment'), 'rows="3" style="width:300px;"');
-	
-	if ($owner_id == api_get_user_id() || api_is_platform_admin()) {		
-		$checked =& $form->addElement('checkbox', 'readonly', null, get_lang('ReadOnly'));
-		if ($readonly == 1) {
-			$checked->setChecked(true);
-		}
-	}
-	
-	if ($is_certificate_mode)
-		$form->addElement('style_submit_button', 'submit', get_lang('SaveCertificate'), 'class="save"');
-	else
-		$form->addElement('style_submit_button','submit',get_lang('SaveDocument'), 'class="save"');
-
-	$defaults['filename'] = $filename;
-	$defaults['extension'] = $extension;
-	$defaults['file_path'] = Security::remove_XSS($_GET['file']);
-	$defaults['commentPath'] = $file;
-	$defaults['renameTo'] = $file_name;
-	$defaults['comment'] = $document_data['comment'];
-	$defaults['origin'] = Security::remove_XSS($_GET['origin']);
-	$defaults['origin_opt'] = Security::remove_XSS($_GET['origin_opt']);
-
-	$form->setDefaults($defaults);
-	
-	show_return($parent_id, $dir_original, $call_from_tool, $slide_id, $is_certificate_mode);
-	
-	if ($is_certificate_mode) {
-		$all_information_by_create_certificate=DocumentManager::get_all_info_to_certificate(api_get_user_id(), api_get_course_id());
-		$str_info='';
-		foreach ($all_information_by_create_certificate[0] as $info_value) {
-			$str_info.=$info_value.'<br/>';
-		}
-		$create_certificate=get_lang('CreateCertificateWithTags');
-		Display::display_normal_message($create_certificate.': <br /><br />'.$str_info,false);
-	}
-	
-	if ($extension=='svg' && !api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true'){
-		Display::display_warning_message(get_lang('BrowserDontSupportsSVG'));
-	}
-	echo '<div class="row-fluid" style="overflow:hidden">
+    $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['content'] = str_replace('<!--[', '<!-- [', $content);
+
+    //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;
+            $form->add_html_editor('content', '', false, false, $html_editor_config);
+            //$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 && !is_my_shared_folder(api_get_user_id(), $my_cur_dir_path, $current_session_id)) {
+        $metadata_link = '<a href="../metadata/index.php?eid='.urlencode(
+            'Document.'.$document_data['id']
+        ).'">'.get_lang('AddMetadata').'</a>';
+
+        //Updated on field
+        $last_edit_date = api_get_local_time($last_edit_date);
+        $display_date = date_to_str_ago($last_edit_date).' <span class="dropbox_date">'.api_format_date(
+            $last_edit_date
+        ).'</span>';
+        $form->addElement('static', null, get_lang('Metadata'), $metadata_link);
+        $form->addElement('static', null, get_lang('UpdatedOn'), $display_date);
+    }
+
+    $form->addElement('textarea', 'comment', get_lang('Comment'), 'rows="3" style="width:300px;"');
+
+    if ($owner_id == api_get_user_id() || api_is_platform_admin()) {
+        $checked =& $form->addElement('checkbox', 'readonly', null, get_lang('ReadOnly'));
+        if ($readonly == 1) {
+            $checked->setChecked(true);
+        }
+    }
+
+    if ($is_certificate_mode) {
+        $form->addElement('style_submit_button', 'submit', get_lang('SaveCertificate'), 'class="save"');
+    } else {
+        $form->addElement('style_submit_button', 'submit', get_lang('SaveDocument'), 'class="save"');
+    }
+
+    $defaults['filename'] = $filename;
+    $defaults['extension'] = $extension;
+    $defaults['file_path'] = Security::remove_XSS($_GET['file']);
+    $defaults['commentPath'] = $file;
+    $defaults['renameTo'] = $file_name;
+    $defaults['comment'] = $document_data['comment'];
+    $defaults['origin'] = Security::remove_XSS($_GET['origin']);
+    $defaults['origin_opt'] = Security::remove_XSS($_GET['origin_opt']);
+
+    $form->setDefaults($defaults);
+
+    show_return($parent_id, $dir_original, $call_from_tool, $slide_id, $is_certificate_mode);
+
+    if ($is_certificate_mode) {
+        $all_information_by_create_certificate = DocumentManager::get_all_info_to_certificate(
+            api_get_user_id(),
+            api_get_course_id()
+        );
+        $str_info = '';
+        foreach ($all_information_by_create_certificate[0] as $info_value) {
+            $str_info .= $info_value.'<br/>';
+        }
+        $create_certificate = get_lang('CreateCertificateWithTags');
+        Display::display_normal_message($create_certificate.': <br /><br />'.$str_info, false);
+    }
+
+    if ($extension == 'svg' && !api_browser_support('svg') && api_get_setting('enabled_support_svg') == 'true') {
+        Display::display_warning_message(get_lang('BrowserDontSupportsSVG'));
+    }
+    echo '<div class="row-fluid" style="overflow:hidden">
             <div id="template_col" class="span2" style="width:162px">
                 <div id="frmModel" style="overflow: visible;"></div>
             </div>
@@ -484,62 +572,105 @@ Display::display_footer();
 */
 
 /**
-	This function changes the name of a certain file.
-	It needs no global variables, it takes all info from parameters.
-	It returns nothing.
-    @todo check if this function is used
-*/
-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 FileManager::my_rename: params $file_name_for_change, $rename_to");
-    $rename_to = disable_dangerous_file($rename_to); // Avoid renaming to .htaccess file
-	$rename_to = FileManager::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 {
-			$source_file = '/'.$source_file;
-			$new_full_file_name = '/'.$rename_to;
-		}
+This function changes the name of a certain file.
+It needs no global variables, it takes all info from parameters.
+It returns nothing.
+@todo check if this function is used
+ */
+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 FileManager::my_rename: params $file_name_for_change, $rename_to");
+    $rename_to = FileManager::disable_dangerous_file($rename_to); // Avoid renaming to .htaccess file
+    $rename_to = FileManager::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 {
+            $source_file = '/'.$source_file;
+            $new_full_file_name = '/'.$rename_to;
+        }
 
-		FileManager::update_db_info('update', $source_file, $new_full_file_name); // fileManage API
-		$name_changed = get_lang('ElRen');
-		$info_message = get_lang('fileModified');
+        FileManager::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'] = $rename_to;
-		$GLOBALS['doc'] = $rename_to;
+        $GLOBALS['file_name'] = $rename_to;
+        $GLOBALS['doc'] = $rename_to;
 
-		return $info_message;
-	} else {
-		$dialogBox = get_lang('FileExists'); // TODO: This variable is not used.
+        return $info_message;
+    } else {
+        $dialogBox = get_lang('FileExists'); // TODO: This variable is not used.
 
-		/* Return to step 1 */
-		$rename = $source_file;
-		unset($source_file);
-	}
+        /* Return to step 1 */
+        $rename = $source_file;
+        unset($source_file);
+    }
 }
 
 //return button back to
-function show_return($document_id, $path, $call_from_tool='', $slide_id=0, $is_certificate_mode=false) {
-    global $parent_id;	
-	$pathurl = urlencode($path);
-	echo '<div class="actions">';
-	
-	if ($is_certificate_mode) {
-		echo '<a href="document.php?curdirpath='.Security::remove_XSS($_GET['curdirpath']).'&selectcat=' . Security::remove_XSS($_GET['selectcat']).'">'.Display::return_icon('back.png',get_lang('Back').' '.get_lang('To').' '.get_lang('CertificateOverview'),'',ICON_SIZE_MEDIUM).'</a>';
-	} elseif($call_from_tool=='slideshow') {
-		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('slideshow.png', get_lang('BackTo').' '.get_lang('ViewSlideshow'),'',ICON_SIZE_MEDIUM).'</a>';		
-	} elseif($call_from_tool=='editdraw') {
-		echo '<a href="document.php?action=exit_slideshow&id='.$parent_id.'">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('DocumentsOverview'),'',ICON_SIZE_MEDIUM).'</a>';
-		echo '<a href="javascript:history.back(1)">'.Display::return_icon('draw.png', get_lang('BackTo').' '.get_lang('Draw'), array(), 32).'</a>';
-	} elseif($call_from_tool=='editpaint'){
-		echo '<a href="document.php?action=exit_slideshow&id='.$parent_id.'">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('DocumentsOverview'), array(), ICON_SIZE_MEDIUM).'</a>';
-		echo '<a href="javascript:history.back(1)">'.Display::return_icon('paint.png', get_lang('BackTo').' '.get_lang('Paint'), array(), 32).'</a>';		
-	} else {
-		echo '<a href="document.php?action=exit_slideshow&id='.$parent_id.'">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('DocumentsOverview'),'',ICON_SIZE_MEDIUM).'</a>';
-	}
-	echo '</div>';
+function show_return($document_id, $path, $call_from_tool = '', $slide_id = 0, $is_certificate_mode = false)
+{
+    global $parent_id;
+    $pathurl = urlencode($path);
+    echo '<div class="actions">';
+
+    if ($is_certificate_mode) {
+        echo '<a href="document.php?curdirpath='.Security::remove_XSS(
+            $_GET['curdirpath']
+        ).'&selectcat='.Security::remove_XSS($_GET['selectcat']).'">'.Display::return_icon(
+            'back.png',
+            get_lang('Back').' '.get_lang('To').' '.get_lang('CertificateOverview'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+    } elseif ($call_from_tool == 'slideshow') {
+        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(
+            'slideshow.png',
+            get_lang('BackTo').' '.get_lang('ViewSlideshow'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+    } elseif ($call_from_tool == 'editdraw') {
+        echo '<a href="document.php?action=exit_slideshow&id='.$parent_id.'">'.Display::return_icon(
+            'back.png',
+            get_lang('BackTo').' '.get_lang('DocumentsOverview'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+        echo '<a href="javascript:history.back(1)">'.Display::return_icon(
+            'draw.png',
+            get_lang('BackTo').' '.get_lang('Draw'),
+            array(),
+            32
+        ).'</a>';
+    } elseif ($call_from_tool == 'editpaint') {
+        echo '<a href="document.php?action=exit_slideshow&id='.$parent_id.'">'.Display::return_icon(
+            'back.png',
+            get_lang('BackTo').' '.get_lang('DocumentsOverview'),
+            array(),
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+        echo '<a href="javascript:history.back(1)">'.Display::return_icon(
+            'paint.png',
+            get_lang('BackTo').' '.get_lang('Paint'),
+            array(),
+            32
+        ).'</a>';
+    } else {
+        echo '<a href="document.php?action=exit_slideshow&id='.$parent_id.'">'.Display::return_icon(
+            'back.png',
+            get_lang('BackTo').' '.get_lang('DocumentsOverview'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+    }
+    echo '</div>';
 }

+ 139 - 89
main/document/save_pixlr.php

@@ -1,52 +1,53 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- *	This file allows creating new svg and png documents with an online editor.
+ *    This file allows creating new svg and png documents with an online editor.
  *
- *	@package chamilo.document
+ * @package chamilo.document
  *
  * @author Juan Carlos Raña Trabado
  * @since 30/january/2011
-*/
+ */
 /**
  * Code
  */
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 
 api_protect_course_script();
 api_block_anonymous_users();
 
-if ($_user['user_id']!= api_get_user_id() || api_get_user_id()==0 || $_user['user_id']==0) {
-	api_not_allowed();
-	die();
+if ($_user['user_id'] != api_get_user_id() || api_get_user_id() == 0 || $_user['user_id'] == 0) {
+    api_not_allowed();
+    die();
 }
 
-if(!isset($_GET['title']) || !isset($_GET['type']) || !isset($_GET['image'])) {
-	api_not_allowed();
-	die();
+if (!isset($_GET['title']) || !isset($_GET['type']) || !isset($_GET['image'])) {
+    api_not_allowed();
+    die();
 }
 
-if(!isset($_SESSION['paint_dir']) || !isset($_SESSION['whereami']) ){
-	api_not_allowed();
-	die();	
+if (!isset($_SESSION['paint_dir']) || !isset($_SESSION['whereami'])) {
+    api_not_allowed();
+    die();
 }
 
 //pixlr return
 
-$filename=Security::remove_XSS($_GET['title']);//The user preferred file name of the image.
-$extension=Security::remove_XSS($_GET['type']);//The image type, "pdx", "jpg", "bmp" or "png".
-$urlcontents=Security::remove_XSS($_GET['image']);//A URL to the image on Pixlr.com server or the raw file post of the saved image.
+$filename = Security::remove_XSS($_GET['title']); //The user preferred file name of the image.
+$extension = Security::remove_XSS($_GET['type']); //The image type, "pdx", "jpg", "bmp" or "png".
+$urlcontents = Security::remove_XSS(
+    $_GET['image']
+); //A URL to the image on Pixlr.com server or the raw file post of the saved image.
 
 //make variables
 
-$title = Database::escape_string(str_replace('_',' ',$filename));
+$title = Database::escape_string(str_replace('_', ' ', $filename));
 $current_session_id = api_get_session_id();
-$groupId= api_get_group_id();
-$relativeUrlPath=$_SESSION['paint_dir'];
-$currentTool=$_SESSION['whereami'];
+$groupId = api_get_group_id();
+$relativeUrlPath = $_SESSION['paint_dir'];
+$currentTool = $_SESSION['whereami'];
 $dirBaseDocuments = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-$saveDir=$dirBaseDocuments.$_SESSION['paint_dir'];
+$saveDir = $dirBaseDocuments.$_SESSION['paint_dir'];
 
 $contents = file_get_contents($urlcontents);
 
@@ -70,25 +71,25 @@ $contents = file_get_contents($urlcontents_to_save);//replace line 45.
 $filename = addslashes(trim($filename));
 $filename = Security::remove_XSS($filename);
 $filename = replace_dangerous_char($filename, 'strict');
-$filename = disable_dangerous_file($filename);
+$filename = FileManager::disable_dangerous_file($filename);
 
-if (strlen(trim($filename))==0) {
-	 echo "The title is empty";//if title is empty, headers Content-Type = application/octet-stream, then not create a new title here please
-	 exit;
+if (strlen(trim($filename)) == 0) {
+    echo "The title is empty"; //if title is empty, headers Content-Type = application/octet-stream, then not create a new title here please
+    exit;
 }
 
 //check file_get_contents
-if ($contents === false) { 
-	echo "I cannot read: ".$urlcontents;
+if ($contents === false) {
+    echo "I cannot read: ".$urlcontents;
     exit;
 }
 
 // Extension security
-if($extension!= 'jpg' && $extension!= 'png' && $extension!= 'pxd'){
-	die();
+if ($extension != 'jpg' && $extension != 'png' && $extension != 'pxd') {
+    die();
 }
-if($extension=='pxd') {
-	echo "pxd file type does not supported";// not secure because check security headers and finfo() return  Content-Type = application/octet-stream
+if ($extension == 'pxd') {
+    echo "pxd file type does not supported"; // not secure because check security headers and finfo() return  Content-Type = application/octet-stream
     exit;
 }
 
@@ -96,15 +97,15 @@ if($extension=='pxd') {
 $headers = get_headers($urlcontents, 1);
 $content_type = explode("/", $headers['Content-Type']);
 if ($content_type[0] != "image") {
-	echo "Invalid file type";
-	exit;
+    echo "Invalid file type";
+    exit;
 }
 
 //Verify that the file is an image. Fileinfo method
 $finfo = new finfo(FILEINFO_MIME);
-$current_mime=$finfo->buffer($contents);
+$current_mime = $finfo->buffer($contents);
 finfo_close($finfo);
-if(strpos($current_mime, 'image')===false) {
+if (strpos($current_mime, 'image') === false) {
     echo "Invalid mime type file";
     exit;
 }
@@ -118,8 +119,8 @@ fclose($handle);
 
 // Check if there is enough space in the course to save the file
 if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
-	unlink($tmpfname);
-	die(get_lang('UplNotEnoughSpace'));
+    unlink($tmpfname);
+    die(get_lang('UplNotEnoughSpace'));
 }
 
 //erase temporal file
@@ -130,55 +131,102 @@ unlink($tmpfname);
 $paintFileName = $filename.'.'.$extension;
 $title = $title.'.'.$extension;
 
-if($currentTool=='document/createpaint'){		
-	//check save as and prevent rewrite an older file with same name	
-	if (0 != $groupId){
-        $group_properties  = GroupManager :: get_group_properties($groupId);
+if ($currentTool == 'document/createpaint') {
+    //check save as and prevent rewrite an older file with same name
+    if (0 != $groupId) {
+        $group_properties = GroupManager :: get_group_properties($groupId);
         $groupPath = $group_properties['directory'];
-	} else {
-		$groupPath ='';
-	}	
-	
-	if (file_exists($saveDir.'/'.$filename.'.'.$extension)){ 
-		$i = 1;		
-		while (file_exists($saveDir.'/'.$filename.'_'.$i.'.'.$extension)) $i++;
-		$paintFileName = $filename . '_' . $i . '.'.$extension;
-		$title = $filename . '_' . $i . '.'.$extension;
-	}
-	
-	//
-	$documentPath = $saveDir.'/'.$paintFileName;
-	//add new document to disk
-	file_put_contents( $documentPath, $contents );
-	//add document to database
-	$doc_id = add_document($_course, $relativeUrlPath.'/'.$paintFileName, 'file', filesize($documentPath), $title);
-	api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
-
-}elseif($currentTool=='document/editpaint'){
-	
-	$documentPath = $saveDir.'/'.$paintFileName;
-	//add new document to disk
-	file_put_contents( $documentPath, $contents );
-	
-	//check path
-	if(!isset($_SESSION['paint_file'])){
-		api_not_allowed();
-		die();
-	}
-	if($_SESSION['paint_file']==$paintFileName){		   
-		$document_id = DocumentManager::get_document_id($_course, $relativeUrlPath.'/'.$paintFileName);
-		update_existing_document($_course, $document_id, filesize($documentPath), null);
-		api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $_user['user_id'], $groupId, null, null, null, $current_session_id);		
-	}else{
-		//add a new document
-		$doc_id = add_document($_course, $relativeUrlPath.'/'.$paintFileName, 'file', filesize($documentPath), $title);
-		api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
-	}	
+    } else {
+        $groupPath = '';
+    }
+
+    if (file_exists($saveDir.'/'.$filename.'.'.$extension)) {
+        $i = 1;
+        while (file_exists($saveDir.'/'.$filename.'_'.$i.'.'.$extension)) {
+            $i++;
+        }
+        $paintFileName = $filename.'_'.$i.'.'.$extension;
+        $title = $filename.'_'.$i.'.'.$extension;
+    }
+
+    //
+    $documentPath = $saveDir.'/'.$paintFileName;
+    //add new document to disk
+    file_put_contents($documentPath, $contents);
+    //add document to database
+    $doc_id = FileManager::add_document(
+        $_course,
+        $relativeUrlPath.'/'.$paintFileName,
+        'file',
+        filesize($documentPath),
+        $title
+    );
+    api_item_property_update(
+        $_course,
+        TOOL_DOCUMENT,
+        $doc_id,
+        'DocumentAdded',
+        $_user['user_id'],
+        $groupId,
+        null,
+        null,
+        null,
+        $current_session_id
+    );
+
+} elseif ($currentTool == 'document/editpaint') {
+
+    $documentPath = $saveDir.'/'.$paintFileName;
+    //add new document to disk
+    file_put_contents($documentPath, $contents);
+
+    //check path
+    if (!isset($_SESSION['paint_file'])) {
+        api_not_allowed();
+        die();
+    }
+    if ($_SESSION['paint_file'] == $paintFileName) {
+        $document_id = DocumentManager::get_document_id($_course, $relativeUrlPath.'/'.$paintFileName);
+        FileManager::update_existing_document($_course, $document_id, filesize($documentPath), null);
+        api_item_property_update(
+            $_course,
+            TOOL_DOCUMENT,
+            $document_id,
+            'DocumentUpdated',
+            $_user['user_id'],
+            $groupId,
+            null,
+            null,
+            null,
+            $current_session_id
+        );
+    } else {
+        //add a new document
+        $doc_id = FileManager::add_document(
+            $_course,
+            $relativeUrlPath.'/'.$paintFileName,
+            'file',
+            filesize($documentPath),
+            $title
+        );
+        api_item_property_update(
+            $_course,
+            TOOL_DOCUMENT,
+            $doc_id,
+            'DocumentAdded',
+            $_user['user_id'],
+            $groupId,
+            null,
+            null,
+            null,
+            $current_session_id
+        );
+    }
 }
 
 
 //delete temporal file
-$temp_file_2delete=$_SESSION['temp_realpath_image'];
+$temp_file_2delete = $_SESSION['temp_realpath_image'];
 unlink($temp_file_2delete);
 
 //Clean sessions and return to Chamilo file list
@@ -188,12 +236,14 @@ unset($_SESSION['whereami']);
 unset($_SESSION['temp_realpath_image']);
 
 if (!isset($_SESSION['exit_pixlr'])) {
-	$location=api_get_path(WEB_CODE_PATH).'document/document.php';
-	echo '<script>window.parent.location.href="'.$location.'"</script>';					 
-	api_not_allowed(true);
-} else {	
-	echo '<div align="center" style="padding-top:150; font-family:Arial, Helvetica, Sans-serif;font-size:25px;color:#aaa;font-weight:bold;">'.get_lang('PleaseStandBy').'</div>';
-	$location=api_get_path(WEB_CODE_PATH).'document/document.php?id='.Security::remove_XSS($_SESSION['exit_pixlr']);
-	echo '<script>window.parent.location.href="'.$location.'"</script>';
-	unset($_SESSION['exit_pixlr']);
+    $location = api_get_path(WEB_CODE_PATH).'document/document.php';
+    echo '<script>window.parent.location.href="'.$location.'"</script>';
+    api_not_allowed(true);
+} else {
+    echo '<div align="center" style="padding-top:150; font-family:Arial, Helvetica, Sans-serif;font-size:25px;color:#aaa;font-weight:bold;">'.get_lang(
+        'PleaseStandBy'
+    ).'</div>';
+    $location = api_get_path(WEB_CODE_PATH).'document/document.php?id='.Security::remove_XSS($_SESSION['exit_pixlr']);
+    echo '<script>window.parent.location.href="'.$location.'"</script>';
+    unset($_SESSION['exit_pixlr']);
 }

Fișier diff suprimat deoarece este prea mare
+ 489 - 417
main/dropbox/dropbox_functions.inc.php


+ 192 - 168
main/dropbox/dropbox_submit.php

@@ -16,7 +16,6 @@
  * - UPLOAD NEW FILE
  */
 if (isset($_POST['submitWork'])) {
-    require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
     $error = false;
     $errormsg = '';
     /**
@@ -24,37 +23,36 @@ if (isset($_POST['submitWork'])) {
      */
 
     // the author or description field is empty
-    if (!isset($_POST['authors']) || !isset( $_POST['description'])) {
+    if (!isset($_POST['authors']) || !isset($_POST['description'])) {
         $error = true;
         $errormsg = get_lang('BadFormData');
-    } elseif (!isset( $_POST['recipients']) || count( $_POST['recipients']) <= 0) {
+    } elseif (!isset($_POST['recipients']) || count($_POST['recipients']) <= 0) {
         $error = true;
         $errormsg = get_lang('NoUserSelected');
     } else {
         $thisIsAMailing = false;
         $thisIsJustUpload = false;
 
-	    foreach ($_POST['recipients'] as $rec) {
+        foreach ($_POST['recipients'] as $rec) {
             if ($rec == 'mailing') {
-	            $thisIsAMailing = true;
+                $thisIsAMailing = true;
             } elseif ($rec == 'upload') {
-	            $thisIsJustUpload = true;
+                $thisIsJustUpload = true;
             } elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_')))) {
-	        	echo '401';
-	        	die(get_lang('BadFormData').' (code 401)');
-	        } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) {
-	        	echo '402';
-	        	die(get_lang('BadFormData').' (code 402)');
-	        }
+                echo '401';
+                die(get_lang('BadFormData').' (code 401)');
+            } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) {
+                echo '402';
+                die(get_lang('BadFormData').' (code 402)');
+            }
         }
 
-		// we are doing a mailing but an additional recipient is selected
-        if ($thisIsAMailing && ( count($_POST['recipients']) != 1)) {
+        // we are doing a mailing but an additional recipient is selected
+        if ($thisIsAMailing && (count($_POST['recipients']) != 1)) {
             $error = true;
             $errormsg = get_lang('MailingSelectNoOther');
-        }
-        // we are doing a just upload but an additional recipient is selected.
-        elseif ( $thisIsJustUpload && ( count($_POST['recipients']) != 1)) {
+        } // we are doing a just upload but an additional recipient is selected.
+        elseif ($thisIsJustUpload && (count($_POST['recipients']) != 1)) {
             $error = true;
             $errormsg = get_lang('MailingJustUploadSelectNoOther');
         } elseif (empty($_FILES['file']['name'])) {
@@ -63,11 +61,11 @@ if (isset($_POST['submitWork'])) {
         }
     }
 
-	//check if $_POST['cb_overwrite'] is true or false
-	$dropbox_overwrite = false;
-	if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) {
-		$dropbox_overwrite = true;
-	}
+    //check if $_POST['cb_overwrite'] is true or false
+    $dropbox_overwrite = false;
+    if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) {
+        $dropbox_overwrite = true;
+    }
 
     /**
      * FORM SUBMIT : UPLOAD NEW FILE
@@ -81,7 +79,9 @@ if (isset($_POST['submitWork'])) {
         $dropbox_filetmpname = $_FILES['file']['tmp_name'];
 
         if ($dropbox_filesize <= 0 || $dropbox_filesize > dropbox_cnf('maxFilesize')) {
-            $errormsg = get_lang('TooBig'); // TODO: The "too big" message does not fit in the case of uploading zero-sized file.
+            $errormsg = get_lang(
+                'TooBig'
+            ); // TODO: The "too big" message does not fit in the case of uploading zero-sized file.
             $error = true;
         } elseif (!is_uploaded_file($dropbox_filetmpname)) { // check user fraud : no clean error msg.
             die(get_lang('BadFormData').' (code 403)');
@@ -89,93 +89,106 @@ if (isset($_POST['submitWork'])) {
 
         if (!$error) {
             // Try to add an extension to the file if it hasn't got one
-            $dropbox_filename = add_ext_on_mime($dropbox_filename, $dropbox_filetype);
+            $dropbox_filename = FileManager::add_ext_on_mime($dropbox_filename, $dropbox_filetype);
             // Replace dangerous characters
             $dropbox_filename = replace_dangerous_char($dropbox_filename);
             // Transform any .php file in .phps fo security
-            $dropbox_filename = php2phps($dropbox_filename);
-            if (!filter_extension($dropbox_filename)) {
-            	$error = true;
-            	$errormsg = get_lang('UplUnableToSaveFileFilteredExtension');
+            $dropbox_filename = FileManager::php2phps($dropbox_filename);
+            if (!FileManager::filter_extension($dropbox_filename)) {
+                $error = true;
+                $errormsg = get_lang('UplUnableToSaveFileFilteredExtension');
             } else {
-	            // set title
-	            $dropbox_title = $dropbox_filename;
-
-	            // set author
-	            if ($_POST['authors'] == '') {
-	                $_POST['authors'] = getUserNameFromId($_user['user_id']);
-	            }
-
-				if ($dropbox_overwrite) {
-					$dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
-
-					foreach ($dropbox_person->sentWork as $w) {
-						if ($w->title == $dropbox_filename) {
-						    if (($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase')) xor $thisIsAMailing) {
-								$error = true;
-								$errormsg = get_lang('MailingNonMailingError');
-							}
-							if ( ($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
-								$error = true;
-								$errormsg = get_lang('MailingJustUploadSelectNoOther');
-							}
-							$dropbox_filename = $w->filename;
-							$found = true;
-							break;
-						}
-					}
-				} else {
-					// rename file to login_filename_uniqueId format
-					$dropbox_filename = getLoginFromId( $_user['user_id']) . '_' . $dropbox_filename . '_'.uniqid('');
-				}
-
-				if (!is_dir(dropbox_cnf('sysPath'))) {
-					//The dropbox subdir doesn't exist yet so make it and create the .htaccess file
-	                mkdir(dropbox_cnf('sysPath'), api_get_permissions_for_new_directories()) or die(get_lang('ErrorCreatingDir').' (code 404)');
-					$fp = fopen(dropbox_cnf('sysPath').'/.htaccess', 'w') or die(get_lang('ErrorCreatingDir').' (code 405)');
-					fwrite($fp, "AuthName AllowLocalAccess
+                // set title
+                $dropbox_title = $dropbox_filename;
+
+                // set author
+                if ($_POST['authors'] == '') {
+                    $_POST['authors'] = getUserNameFromId($_user['user_id']);
+                }
+
+                if ($dropbox_overwrite) {
+                    $dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
+
+                    foreach ($dropbox_person->sentWork as $w) {
+                        if ($w->title == $dropbox_filename) {
+                            if (($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase')) xor $thisIsAMailing) {
+                                $error = true;
+                                $errormsg = get_lang('MailingNonMailingError');
+                            }
+                            if (($w->recipients[0]['id'] == $_user['user_id']) xor $thisIsJustUpload) {
+                                $error = true;
+                                $errormsg = get_lang('MailingJustUploadSelectNoOther');
+                            }
+                            $dropbox_filename = $w->filename;
+                            $found = true;
+                            break;
+                        }
+                    }
+                } else {
+                    // rename file to login_filename_uniqueId format
+                    $dropbox_filename = getLoginFromId($_user['user_id']).'_'.$dropbox_filename.'_'.uniqid('');
+                }
+
+                if (!is_dir(dropbox_cnf('sysPath'))) {
+                    //The dropbox subdir doesn't exist yet so make it and create the .htaccess file
+                    mkdir(dropbox_cnf('sysPath'), api_get_permissions_for_new_directories()) or die(get_lang(
+                        'ErrorCreatingDir'
+                    ).' (code 404)');
+                    $fp = fopen(dropbox_cnf('sysPath').'/.htaccess', 'w') or die(get_lang(
+                        'ErrorCreatingDir'
+                    ).' (code 405)');
+                    fwrite(
+                        $fp,
+                        "AuthName AllowLocalAccess
 	                             AuthType Basic
 
 	                             order deny,allow
 	                             deny from all
 
-	                             php_flag zlib.output_compression off") or die(get_lang('ErrorCreatingDir').' (code 406)');
-	            }
-
-				if ($error) {}
-				elseif ($thisIsAMailing) {
-				    if (preg_match(dropbox_cnf('mailingZipRegexp'), $dropbox_title)) {
-			            $newWorkRecipients = dropbox_cnf('mailingIdBase');
-					} else {
-				        $error = true;
-				        $errormsg = $dropbox_title . ': ' . get_lang('MailingWrongZipfile');
-					}
-				} elseif ($thisIsJustUpload) {
-		            $newWorkRecipients = array();
-	        	} else {
-				 	// Creating the array that contains all the users who will receive the file
-					$newWorkRecipients = array();
-		            foreach ($_POST['recipients'] as $rec) {
-		            	if (strpos($rec, 'user_') === 0) {
-		            		$newWorkRecipients[] = substr($rec, strlen('user_'));
-		            	} elseif (strpos($rec, 'group_') === 0) {
-		            		$userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_')));
-		            		foreach ($userList as $usr) {
-		            			if (!in_array($usr['user_id'], $newWorkRecipients) && $usr['user_id'] != $_user['user_id']) {
-		            				$newWorkRecipients[] = $usr['user_id'];
-		            			}
-		            		}
-		            	}
-		            }
-	        	}
-
-				// After uploading the file, create the db entries
-
-	        	if (!$error) {
-		            @move_uploaded_file( $dropbox_filetmpname, dropbox_cnf('sysPath') . '/' . $dropbox_filename)
-		            	or die(get_lang('UploadError').' (code 407)');
-		            new Dropbox_SentWork($_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $newWorkRecipients);
-	        	}
+	                             php_flag zlib.output_compression off"
+                    ) or die(get_lang('ErrorCreatingDir').' (code 406)');
+                }
+
+                if ($error) {
+                } elseif ($thisIsAMailing) {
+                    if (preg_match(dropbox_cnf('mailingZipRegexp'), $dropbox_title)) {
+                        $newWorkRecipients = dropbox_cnf('mailingIdBase');
+                    } else {
+                        $error = true;
+                        $errormsg = $dropbox_title.': '.get_lang('MailingWrongZipfile');
+                    }
+                } elseif ($thisIsJustUpload) {
+                    $newWorkRecipients = array();
+                } else {
+                    // Creating the array that contains all the users who will receive the file
+                    $newWorkRecipients = array();
+                    foreach ($_POST['recipients'] as $rec) {
+                        if (strpos($rec, 'user_') === 0) {
+                            $newWorkRecipients[] = substr($rec, strlen('user_'));
+                        } elseif (strpos($rec, 'group_') === 0) {
+                            $userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_')));
+                            foreach ($userList as $usr) {
+                                if (!in_array(
+                                    $usr['user_id'],
+                                    $newWorkRecipients
+                                ) && $usr['user_id'] != $_user['user_id']
+                                ) {
+                                    $newWorkRecipients[] = $usr['user_id'];
+                                }
+                            }
+                        }
+                    }
+                }
+
+                // After uploading the file, create the db entries
+
+                if (!$error) {
+                    @move_uploaded_file($dropbox_filetmpname, dropbox_cnf('sysPath').'/'.$dropbox_filename)
+                        or die(get_lang('UploadError').' (code 407)');
+                    new Dropbox_SentWork($_user['user_id'], $dropbox_title, $_POST['description'], strip_tags(
+                        $_POST['authors']
+                    ), $dropbox_filename, $dropbox_filesize, $newWorkRecipients);
+                }
             }
         }
     } //end if(!$error)
@@ -186,9 +199,9 @@ if (isset($_POST['submitWork'])) {
      */
 
     if (!$error) {
-		$return_message = get_lang('FileUploadSucces');
+        $return_message = get_lang('FileUploadSucces');
     } else {
-		$return_message = $errormsg;
+        $return_message = $errormsg;
     }
 } // end if ( isset( $_POST['submitWork']))
 
@@ -349,20 +362,22 @@ if (isset($_GET['mailingIndex'])) {
 }
 */
 
-function findRecipient($thisFile) {
-	// string result = error message, array result = [user_id, lastname, firstname, status]
-	global $nameParts, $preFix, $preLen, $postFix, $postLen;
+function findRecipient($thisFile)
+{
+    // string result = error message, array result = [user_id, lastname, firstname, status]
+    global $nameParts, $preFix, $preLen, $postFix, $postLen;
     if (preg_match(dropbox_cnf('mailingFileRegexp'), $thisFile, $matches)) {
         $thisName = $matches[1];
         if (api_substr($thisName, 0, $preLen) == $preFix) {
             if ($postLen == 0 || api_substr($thisName, -$postLen) == $postFix) {
-	            $thisRecip = api_substr($thisName, $preLen, api_strlen($thisName) - $preLen - $postLen);
-	            if ($thisRecip) {
-	            	return getUser($thisRecip);
-	            }
-	            return ' <'.get_lang('MailingFileNoRecip', '').'>';
+                $thisRecip = api_substr($thisName, $preLen, api_strlen($thisName) - $preLen - $postLen);
+                if ($thisRecip) {
+                    return getUser($thisRecip);
+                }
+
+                return ' <'.get_lang('MailingFileNoRecip', '').'>';
             } else {
-	            return ' <'.get_lang('MailingFileNoPostfix', '').$postFix.'>';
+                return ' <'.get_lang('MailingFileNoPostfix', '').$postFix.'>';
             }
         } else {
             return ' <'.get_lang('MailingFileNoPrefix', '').$preFix.'>';
@@ -372,25 +387,28 @@ function findRecipient($thisFile) {
     }
 }
 
-function getUser($thisRecip) {
-	// string result = error message, array result = [user_id, lastname, firstname]
+function getUser($thisRecip)
+{
+    // string result = error message, array result = [user_id, lastname, firstname]
 
-	global $var, $sel;
+    global $var, $sel;
     if (isset($students)) {
         unset($students);
     }
 
-    $result = Database::query($sel . $thisRecip . "'");
-    while ( ($res = Database::fetch_array($result))) {$students[] = $res;}
+    $result = Database::query($sel.$thisRecip."'");
+    while (($res = Database::fetch_array($result))) {
+        $students[] = $res;
+    }
     Database::free_result($result);
 
-	if (count($students) == 1) {
-    	return($students[0]);
-	} elseif (count($students) > 1) {
-    	return ' <'.get_lang('MailingFileRecipDup', '').$var."= $thisRecip>";
-	} else {
-    	return ' <'.get_lang('MailingFileRecipNotFound', '').$var."= $thisRecip>";
-	}
+    if (count($students) == 1) {
+        return ($students[0]);
+    } elseif (count($students) > 1) {
+        return ' <'.get_lang('MailingFileRecipDup', '').$var."= $thisRecip>";
+    } else {
+        return ' <'.get_lang('MailingFileRecipNotFound', '').$var."= $thisRecip>";
+    }
 }
 
 
@@ -403,60 +421,64 @@ function getUser($thisRecip) {
  * - EDIT FEEDBACK
  */
 if (isset($_GET['deleteReceived']) || isset($_GET['deleteSent'])
-         || isset( $_GET['showFeedback']) || isset( $_GET['editFeedback'])) {
-	if ($_GET['mailing']) {
-		getUserOwningThisMailing($_GET['mailing'], $_user['user_id'], '408');
-		$dropbox_person = new Dropbox_Person($_GET['mailing'], $is_courseAdmin, $is_courseTutor);
-	} else {
-	    $dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
+    || isset($_GET['showFeedback']) || isset($_GET['editFeedback'])
+) {
+    if ($_GET['mailing']) {
+        getUserOwningThisMailing($_GET['mailing'], $_user['user_id'], '408');
+        $dropbox_person = new Dropbox_Person($_GET['mailing'], $is_courseAdmin, $is_courseTutor);
+    } else {
+        $dropbox_person = new Dropbox_Person($_user['user_id'], $is_courseAdmin, $is_courseTutor);
     }
 
-	if (isset($_SESSION['sentOrder'])) {
-		$dropbox_person->orderSentWork($_SESSION['sentOrder']);
-	}
-	if (isset($_SESSION['receivedOrder'])) {
-		$dropbox_person->orderReceivedWork($_SESSION['receivedOrder']);
-	}
+    if (isset($_SESSION['sentOrder'])) {
+        $dropbox_person->orderSentWork($_SESSION['sentOrder']);
+    }
+    if (isset($_SESSION['receivedOrder'])) {
+        $dropbox_person->orderReceivedWork($_SESSION['receivedOrder']);
+    }
 
-	/*if (!$dropbox_person->isCourseAdmin || ! $dropbox_person->isCourseTutor) {
-	    die(get_lang('GeneralError').' (code 408)');
-	}*/
+    /*if (!$dropbox_person->isCourseAdmin || ! $dropbox_person->isCourseTutor) {
+        die(get_lang('GeneralError').' (code 408)');
+    }*/
 
-	$tellUser = get_lang('FileDeleted');
+    $tellUser = get_lang('FileDeleted');
 
     if (isset($_GET['deleteReceived'])) {
         if ($_GET['deleteReceived'] == 'all') {
             $dropbox_person->deleteAllReceivedWork();
         } elseif (is_numeric($_GET['deleteReceived'])) {
-            $dropbox_person->deleteReceivedWork( $_GET['deleteReceived']);
+            $dropbox_person->deleteReceivedWork($_GET['deleteReceived']);
         } else {
             die(get_lang('GeneralError').' (code 409)');
         }
-    } elseif (isset( $_GET['deleteSent'])) {
+    } elseif (isset($_GET['deleteSent'])) {
         if ($_GET['deleteSent'] == 'all') {
-            $dropbox_person->deleteAllSentWork( );
+            $dropbox_person->deleteAllSentWork();
         } elseif (is_numeric($_GET['deleteSent'])) {
             $dropbox_person->deleteSentWork($_GET['deleteSent']);
         } else {
             die(get_lang('GeneralError').' (code 410)');
         }
     } elseif (isset($_GET['showFeedback'])) {
-		$w = new Dropbox_SentWork($id = $_GET['showFeedback']);
+        $w = new Dropbox_SentWork($id = $_GET['showFeedback']);
 
-		if ($w->uploader_id != $_user['user_id']) {
-		    getUserOwningThisMailing($w->uploader_id, $_user['user_id'], '411');
-		}
+        if ($w->uploader_id != $_user['user_id']) {
+            getUserOwningThisMailing($w->uploader_id, $_user['user_id'], '411');
+        }
 
-    	foreach ($w -> recipients as $r) {
-    		if (($fb = $r['feedback'])) {
-    			$fbarray[$r['feedback_date'].$r['name']] = $r['name'].' '.get_lang('SentOn', '').' '.$r['feedback_date'].":\n".$fb;
-    		}
-    	}
+        foreach ($w->recipients as $r) {
+            if (($fb = $r['feedback'])) {
+                $fbarray[$r['feedback_date'].$r['name']] = $r['name'].' '.get_lang(
+                    'SentOn',
+                    ''
+                ).' '.$r['feedback_date'].":\n".$fb;
+            }
+        }
 
-    	if ($fbarray) {
-        	krsort($fbarray);
+        if ($fbarray) {
+            krsort($fbarray);
             echo '<textarea class="dropbox_feedbacks">',
-                    htmlspecialchars(implode("\n\n", $fbarray), ENT_QUOTES, api_get_system_encoding()), '</textarea>', "\n";
+            htmlspecialchars(implode("\n\n", $fbarray), ENT_QUOTES, api_get_system_encoding()), '</textarea>', "\n";
         } else {
             echo '<textarea class="dropbox_feedbacks">&nbsp;</textarea>', "\n";
         }
@@ -466,21 +488,23 @@ if (isset($_GET['deleteReceived']) || isset($_GET['deleteSent'])
     } else { // if ( isset( $_GET['editFeedback'])) {
         $id = $_GET['editFeedback'];
         $found = false;
-		foreach ($dropbox_person->receivedWork as $w) {
-			if ($w->id == $id) {
-			   $found = true;
-			   break;
-			}
-		}
-		if (!$found) die(get_lang('GeneralError').' (code 415)');
+        foreach ($dropbox_person->receivedWork as $w) {
+            if ($w->id == $id) {
+                $found = true;
+                break;
+            }
+        }
+        if (!$found) {
+            die(get_lang('GeneralError').' (code 415)');
+        }
 
         echo '<form method="post" action="index.php">', "\n",
-            '<input type="hidden" name="feedbackid" value="',
-                $id, '"/>', "\n",
-            '<textarea name="feedbacktext" class="dropbox_feedbacks">',
-                htmlspecialchars($w->feedback, ENT_QUOTES, api_get_system_encoding()), '</textarea>', "<br />\n",
-            '<input type="submit" name="feedbacksubmit" value="', get_lang('Ok', ''), '"/>', "\n",
-            '</form>', "\n";
+        '<input type="hidden" name="feedbackid" value="',
+        $id, '"/>', "\n",
+        '<textarea name="feedbacktext" class="dropbox_feedbacks">',
+        htmlspecialchars($w->feedback, ENT_QUOTES, api_get_system_encoding()), '</textarea>', "<br />\n",
+        '<input type="submit" name="feedbacksubmit" value="', get_lang('Ok', ''), '"/>', "\n",
+        '</form>', "\n";
         $tellUser = get_lang('GiveFeedback');
     }
 

+ 35 - 41
main/exercice/GC.php

@@ -1,10 +1,10 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- *	Code library for HotPotatoes integration.
- *	@package chamilo.exercise
- * 	@author Istvan Mandak
- * 	@version $Id: GC.php 20451 2009-05-10 12:02:22Z ivantcholakov $
+ *    Code library for HotPotatoes integration.
+ * @package chamilo.exercise
+ * @author Istvan Mandak
+ * @version $Id: GC.php 20451 2009-05-10 12:02:22Z ivantcholakov $
  */
 /**
  * Code
@@ -13,51 +13,45 @@
 // working recursively, flag[0,1] print or delete the HotPotatoes temp files (.t.html)
 
 echo "Garbage Collector<BR>";
-HotPotGC($_configuration['root_sys'],1,1);
+HotPotGC($_configuration['root_sys'], 1, 1);
 /**
  * Garbage collector caller function
  */
-function HotPotGC($root_sys,$flag,$userID) {
-	// flag[0,1] - print or delete the HotPotatoes temp files (.t.html)
-	$documentPath = $root_sys."courses";
-	require_once(api_get_path(LIBRARY_PATH)."fileManage.lib.php");
-	HotPotGCt($documentPath,$flag,$userID);
+function HotPotGC($root_sys, $flag, $userID)
+{
+    // flag[0,1] - print or delete the HotPotatoes temp files (.t.html)
+    $documentPath = $root_sys."courses";
+    HotPotGCt($documentPath, $flag, $userID);
 }
+
 /**
  * Garbage collector
  */
-function HotPotGCt($folder,$flag,$userID) { // Garbage Collector
-	$filelist = array();
-	    if ($dir = @opendir($folder)) {
+function HotPotGCt($folder, $flag, $userID)
+{ // Garbage Collector
+    $filelist = array();
+    if ($dir = @opendir($folder)) {
         while (($file = readdir($dir)) !== false) {
-            if ( $file != ".") {
-            	if ($file != "..")
-      		{
-            	 $full_name = $folder."/".$file;
-        	  if (is_dir($full_name))
-							{
-								HotPotGCt($folder."/".$file,$flag);
-							}
-						else
-						 {
-                $filelist[] = $file;
-                 }
-               }
+            if ($file != ".") {
+                if ($file != "..") {
+                    $full_name = $folder."/".$file;
+                    if (is_dir($full_name)) {
+                        HotPotGCt($folder."/".$file, $flag);
+                    } else {
+                        $filelist[] = $file;
+                    }
+                }
+            }
+        }
+        closedir($dir);
+    }
+    while (list ($key, $val) = each($filelist)) {
+        if (stristr($val, $userID.".t.html")) {
+            if ($flag == 1) {
+                FileManager::my_delete($folder."/".$val);
+            } else {
+                echo $folder."/".$val."<br />";
             }
         }
-      	closedir($dir);
-    	}
-	while (list ($key, $val) = each ($filelist))
-	{
-		 if (stristr($val,$userID.".t.html"))
-		 { if ($flag == 1)
-		 		{
-						FileManager::my_delete($folder."/".$val);
-				}
-			 else
-			  {
-			  	echo $folder."/".$val."<br />";
-			  }
-		 }
-	}
+    }
 }

+ 107 - 99
main/exercice/Hpdownload.php

@@ -1,62 +1,82 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*	This script shows the list of exercises for administrators and students.
-*	@package chamilo.exercise
-* 	@author Istvan Mandak
-* 	@version $Id: Hpdownload.php 22201 2009-07-17 19:57:03Z cfasanando $
-*/
+ *    This script shows the list of exercises for administrators and students.
+ * @package chamilo.exercise
+ * @author Istvan Mandak
+ * @version $Id: Hpdownload.php 22201 2009-07-17 19:57:03Z cfasanando $
+ */
 /**
  * Code
  */
 session_cache_limiter('public');
 
 require_once '../inc/global.inc.php';
-$this_section=SECTION_COURSES;
+$this_section = SECTION_COURSES;
 
 $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
 
-$doc_url=str_replace(array('../','\\..','\\0','..\\'),array('','','',''),urldecode($_GET['doc_url']));
-$filename=basename($doc_url);
+$doc_url = str_replace(array('../', '\\..', '\\0', '..\\'), array('', '', '', ''), urldecode($_GET['doc_url']));
+$filename = basename($doc_url);
 
 // launch event
 //event_download($doc_url);
 if (isset($_course['path'])) {
     $course_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-	$full_file_name = $course_path.Security::remove_XSS($doc_url);
+    $full_file_name = $course_path.Security::remove_XSS($doc_url);
 } else {
     $course_path = api_get_path(SYS_COURSE_PATH).$cid.'/document';
-	$full_file_name = $course_path.Security::remove_XSS($doc_url);
+    $full_file_name = $course_path.Security::remove_XSS($doc_url);
 }
 
-if(!is_file($full_file_name)) {
-	exit;
+if (!is_file($full_file_name)) {
+    exit;
 }
 
 if (!Security::check_abs_path($full_file_name, $course_path.'/')) {
-    exit;   
+    exit;
 }
 
-$extension=explode('.',$filename);
-$extension=strtolower($extension[sizeof($extension)-1]);
-
-switch($extension) {
-	case 'gz':		$content_type='application/x-gzip';			break;
-	case 'zip':		$content_type='application/zip';			break;
-	case 'pdf':		$content_type='application/pdf';			break;
-	case 'png':		$content_type='image/png';					break;
-	case 'gif':		$content_type='image/gif';					break;
-	case 'jpg':		$content_type='image/jpeg';					break;
-	case 'txt':		$content_type='text/plain';					break;
-	case 'htm':		$content_type='text/html';					break;
-	case 'html':	$content_type='text/html';					break;
-	default:		$content_type='application/octet-stream';	break;
+$extension = explode('.', $filename);
+$extension = strtolower($extension[sizeof($extension) - 1]);
+
+switch ($extension) {
+    case 'gz':
+        $content_type = 'application/x-gzip';
+        break;
+    case 'zip':
+        $content_type = 'application/zip';
+        break;
+    case 'pdf':
+        $content_type = 'application/pdf';
+        break;
+    case 'png':
+        $content_type = 'image/png';
+        break;
+    case 'gif':
+        $content_type = 'image/gif';
+        break;
+    case 'jpg':
+        $content_type = 'image/jpeg';
+        break;
+    case 'txt':
+        $content_type = 'text/plain';
+        break;
+    case 'htm':
+        $content_type = 'text/html';
+        break;
+    case 'html':
+        $content_type = 'text/html';
+        break;
+    default:
+        $content_type = 'application/octet-stream';
+        break;
 }
 
 header('Content-disposition: filename='.$filename);
 header('Content-Type: '.$content_type);
-header('Expires: '.gmdate('D, d M Y H:i:s',time()+10).' GMT');
-header('Last-Modified: '.gmdate('D, d M Y H:i:s',time()+10).' GMT');
+header('Expires: '.gmdate('D, d M Y H:i:s', time() + 10).' GMT');
+header('Last-Modified: '.gmdate('D, d M Y H:i:s', time() + 10).' GMT');
 
 /*
 	Dynamic parsing section
@@ -68,86 +88,74 @@ header('Last-Modified: '.gmdate('D, d M Y H:i:s',time()+10).' GMT');
 */
 
 if ($content_type == 'text/html') {
-	require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-	$directory_name = dirname($full_file_name);
-
-	$dir=str_replace(array('\\',$_configuration['root_sys']."courses/".$_course['path'].'/document'),array('/',''),$directory_name);
-
-	if($dir[strlen($dir)-1] != '/') {
-		$dir.='/';
-	}
-
+    $directory_name = dirname($full_file_name);
 
-	//Parse whole file at one
-	$fp = fopen($full_file_name, "r");
-	$file_content = fread ($fp, filesize ($full_file_name));
-	fclose($fp);
-	//$file_content = api_replace_parameter($dir, $file_content, "src");
-	//$file_content = api_replace_parameter($dir, $file_content, "href");
+    $dir = str_replace(
+        array('\\', $_configuration['root_sys']."courses/".$_course['path'].'/document'),
+        array('/', ''),
+        $directory_name
+    );
 
-	/*
-	//parse line per line
-	$file_content_array = file($full_file_name);
+    if ($dir[strlen($dir) - 1] != '/') {
+        $dir .= '/';
+    }
 
-	foreach($file_content_array as $line)
-	{
-		$line = api_replace_parameter($dir, $line, "src");
-		$line = api_replace_parameter($dir, $line, "href");
-		$file_content .= $line;
-	}
-	*/
 
+    //Parse whole file at one
+    $fp = fopen($full_file_name, "r");
+    $file_content = fread($fp, filesize($full_file_name));
+    fclose($fp);
 
     $exercicePath = api_get_self();
-  	$exfile = explode('/',$exercicePath);
-  	$exfile = $exfile[sizeof($exfile)-1];
-  	$exercicePath = substr($exercicePath,0,strpos($exercicePath,$exfile));
-  	$exercicePath = $exercicePath;
-
-		$content = $file_content;
-		$mit = "function Finish(){";
-
-		$js_content = "var SaveScoreVariable = 0; // This variable included by Dokeos System\n".
-		"function mySaveScore() // This function included by Dokeos System\n".
-"{\n".
-"   if (SaveScoreVariable==0)\n".
-"		{\n".
-"			SaveScoreVariable = 1;\n".
-"			if (C.ie)\n".
-"			{\n".
-"				document.location.href = \"".$exercicePath."savescores.php?origin=$origin&time=$time&test=".$doc_url."&uid=".$_user['user_id']."&cid=".$cid."&score=\"+Score;\n".
-"				//window.alert(Score);\n".
-"			}\n".
-"			else\n".
-"			{\n".
-"			}\n".
-"		}\n".
-"}\n".
-"// Must be included \n".
-"function Finish(){\n".
-" mySaveScore();";
-		$newcontent = str_replace($mit,$js_content,$content);
-
-		$prehref="javascript:void(0);";
-		$posthref=$_configuration['root_web']."main/exercice/Hpdownload.php?doc_url=".$doc_url."&cid=".$cid."&uid=".$uid;
-		$newcontent = str_replace($prehref,$posthref,$newcontent);
-
-
-		$prehref="class=\"GridNum\" onclick=";
-		$posthref="class=\"GridNum\" onMouseover=";
-		$newcontent = str_replace($prehref,$posthref,$newcontent);
-
-
-		header('Content-length: '.strlen($newcontent));
-		// Dipsp.
-		echo $newcontent;
-
-	exit();
+    $exfile = explode('/', $exercicePath);
+    $exfile = $exfile[sizeof($exfile) - 1];
+    $exercicePath = substr($exercicePath, 0, strpos($exercicePath, $exfile));
+    $exercicePath = $exercicePath;
+
+    $content = $file_content;
+    $mit = "function Finish(){";
+
+    $js_content = "var SaveScoreVariable = 0; // This variable included by Dokeos System\n".
+        "function mySaveScore() // This function included by Dokeos System\n".
+        "{\n".
+        "   if (SaveScoreVariable==0)\n".
+        "		{\n".
+        "			SaveScoreVariable = 1;\n".
+        "			if (C.ie)\n".
+        "			{\n".
+        "				document.location.href = \"".$exercicePath."savescores.php?origin=$origin&time=$time&test=".$doc_url."&uid=".$_user['user_id']."&cid=".$cid."&score=\"+Score;\n".
+        "				//window.alert(Score);\n".
+        "			}\n".
+        "			else\n".
+        "			{\n".
+        "			}\n".
+        "		}\n".
+        "}\n".
+        "// Must be included \n".
+        "function Finish(){\n".
+        " mySaveScore();";
+    $newcontent = str_replace($mit, $js_content, $content);
+
+    $prehref = "javascript:void(0);";
+    $posthref = $_configuration['root_web']."main/exercice/Hpdownload.php?doc_url=".$doc_url."&cid=".$cid."&uid=".$uid;
+    $newcontent = str_replace($prehref, $posthref, $newcontent);
+
+
+    $prehref = "class=\"GridNum\" onclick=";
+    $posthref = "class=\"GridNum\" onMouseover=";
+    $newcontent = str_replace($prehref, $posthref, $newcontent);
+
+
+    header('Content-length: '.strlen($newcontent));
+    // Dipsp.
+    echo $newcontent;
+
+    exit();
 }
 
 //normal case, all non-html files
 //header('Content-length: '.filesize($full_file_name));
-$fp=fopen($full_file_name,'rb');
+$fp = fopen($full_file_name, 'rb');
 fpassthru($fp);
 fclose($fp);
 ?>

+ 128 - 72
main/exercice/admin.php

@@ -2,47 +2,47 @@
 
 /* For licensing terms, see /license.txt */
 /**
- * 	Exercise administration
- * 	This script allows to manage (create, modify) an exercise and its questions
+ *     Exercise administration
+ *     This script allows to manage (create, modify) an exercise and its questions
  *
- * 	 Following scripts are includes for a best code understanding :
+ *      Following scripts are includes for a best code understanding :
  *
- * 	- exercise.class.php : for the creation of an Exercise object
- * 	- question.class.php : for the creation of a Question object
- * 	- answer.class.php : for the creation of an Answer object
- * 	- exercise.lib.php : functions used in the exercise tool
- * 	- exercise_admin.inc.php : management of the exercise
- * 	- question_admin.inc.php : management of a question (statement & answers)
- * 	- statement_admin.inc.php : management of a statement
- * 	- answer_admin.inc.php : management of answers
- * 	- question_list_admin.inc.php : management of the question list
+ *     - exercise.class.php : for the creation of an Exercise object
+ *     - question.class.php : for the creation of a Question object
+ *     - answer.class.php : for the creation of an Answer object
+ *     - exercise.lib.php : functions used in the exercise tool
+ *     - exercise_admin.inc.php : management of the exercise
+ *     - question_admin.inc.php : management of a question (statement & answers)
+ *     - statement_admin.inc.php : management of a statement
+ *     - answer_admin.inc.php : management of answers
+ *     - question_list_admin.inc.php : management of the question list
  *
- * 	Main variables used in this script :
+ *     Main variables used in this script :
  *
- * 	- $is_allowedToEdit : set to 1 if the user is allowed to manage the exercise
- * 	- $objExercise : exercise object
- * 	- $objQuestion : question object
- * 	- $objAnswer : answer object
- * 	- $aType : array with answer types
- * 	- $exerciseId : the exercise ID
- * 	- $picturePath : the path of question pictures
- * 	- $newQuestion : ask to create a new question
- * 	- $modifyQuestion : ID of the question to modify
- * 	- $editQuestion : ID of the question to edit
- * 	- $submitQuestion : ask to save question modifications
- * 	- $cancelQuestion : ask to cancel question modifications
- * 	- $deleteQuestion : ID of the question to delete
- * 	- $moveUp : ID of the question to move up
- * 	- $moveDown : ID of the question to move down
- * 	- $modifyExercise : ID of the exercise to modify
- * 	- $submitExercise : ask to save exercise modifications
- * 	- $cancelExercise : ask to cancel exercise modifications
- * 	- $modifyAnswers : ID of the question which we want to modify answers for
- * 	- $cancelAnswers : ask to cancel answer modifications
- * 	- $buttonBack : ask to go back to the previous page in answers of type "Fill in blanks"
+ *     - $is_allowedToEdit : set to 1 if the user is allowed to manage the exercise
+ *     - $objExercise : exercise object
+ *     - $objQuestion : question object
+ *     - $objAnswer : answer object
+ *     - $aType : array with answer types
+ *     - $exerciseId : the exercise ID
+ *     - $picturePath : the path of question pictures
+ *     - $newQuestion : ask to create a new question
+ *     - $modifyQuestion : ID of the question to modify
+ *     - $editQuestion : ID of the question to edit
+ *     - $submitQuestion : ask to save question modifications
+ *     - $cancelQuestion : ask to cancel question modifications
+ *     - $deleteQuestion : ID of the question to delete
+ *     - $moveUp : ID of the question to move up
+ *     - $moveDown : ID of the question to move down
+ *     - $modifyExercise : ID of the exercise to modify
+ *     - $submitExercise : ask to save exercise modifications
+ *     - $cancelExercise : ask to cancel exercise modifications
+ *     - $modifyAnswers : ID of the question which we want to modify answers for
+ *     - $cancelAnswers : ask to cancel answer modifications
+ *     - $buttonBack : ask to go back to the previous page in answers of type "Fill in blanks"
  *
- * 	@package chamilo.exercise
- * 	@author Olivier Brouckaert
+ * @package chamilo.exercise
+ * @author Olivier Brouckaert
  * Modified by Hubert Borderiou 21-10-2011 Question by category
  */
 
@@ -72,8 +72,7 @@ if (!$is_allowedToEdit) {
     api_not_allowed(true);
 }
 
-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).'document.lib.php';
 
 /*  stripslashes POST data  */
 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
@@ -128,33 +127,41 @@ $objQuestion = $_SESSION['objQuestion'];
 $objAnswer = $_SESSION['objAnswer'];
 
 // document path
-$documentPath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document';
+$documentPath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
 
 // picture path
-$picturePath = $documentPath . '/images';
+$picturePath = $documentPath.'/images';
 
 // audio path
-$audioPath = $documentPath . '/audio';
+$audioPath = $documentPath.'/audio';
 
 // the 5 types of answers
-$aType = array(get_lang('UniqueSelect'), get_lang('MultipleSelect'), get_lang('FillBlanks'), get_lang('Matching'), get_lang('FreeAnswer'));
+$aType = array(
+    get_lang('UniqueSelect'),
+    get_lang('MultipleSelect'),
+    get_lang('FillBlanks'),
+    get_lang('Matching'),
+    get_lang('FreeAnswer')
+);
 
 // tables used in the exercise tool
 
 if ($_GET['action'] == 'exportqti2' && !empty($_GET['questionId'])) {
     require_once 'export/qti2/qti2_export.php';
     $export = export_question($_GET['questionId'], true);
-    $qid = (int) $_GET['questionId'];
+    $qid = (int)$_GET['questionId'];
     $archive_path = api_get_path(SYS_ARCHIVE_PATH);
     $temp_dir_short = uniqid();
-    $temp_zip_dir = $archive_path . "/" . $temp_dir_short;
-	if(!is_dir($temp_zip_dir)) mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
-    $temp_zip_file = $temp_zip_dir . "/" . api_get_unique_id() . ".zip";
-    $temp_xml_file = $temp_zip_dir . "/qti2export_" . $qid . '.xml';
+    $temp_zip_dir = $archive_path."/".$temp_dir_short;
+    if (!is_dir($temp_zip_dir)) {
+        mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
+    }
+    $temp_zip_file = $temp_zip_dir."/".api_get_unique_id().".zip";
+    $temp_xml_file = $temp_zip_dir."/qti2export_".$qid.'.xml';
     file_put_contents($temp_xml_file, $export);
     $zip_folder = new PclZip($temp_zip_file);
     $zip_folder->add($temp_xml_file, PCLZIP_OPT_REMOVE_ALL_PATH);
-    $name = 'qti2_export_' . $qid . '.zip';
+    $name = 'qti2_export_'.$qid.'.zip';
 
     DocumentManager::file_send_for_download($temp_zip_file, true, $name);
     unlink($temp_zip_file);
@@ -238,7 +245,7 @@ if ($cancelQuestion) {
 
 if (isset($clone_question) && !empty($objExercise->id)) {
     $old_question_obj = Question::read($clone_question);
-    $old_question_obj->question = $old_question_obj->question . ' - ' . get_lang('Copy');
+    $old_question_obj->question = $old_question_obj->question.' - '.get_lang('Copy');
 
     $new_id = $old_question_obj->duplicate();
     $new_question_obj = Question::read($new_id);
@@ -252,7 +259,7 @@ if (isset($clone_question) && !empty($objExercise->id)) {
     //Reloading tne $objExercise obj
     $objExercise->read($objExercise->id);
 
-    header('Location: admin.php?' . api_get_cidreq() . '&exerciseId=' . $objExercise->id);
+    header('Location: admin.php?'.api_get_cidreq().'&exerciseId='.$objExercise->id);
     exit;
 }
 
@@ -274,21 +281,24 @@ if (isset($_SESSION['gradebook'])) {
 
 if (!empty($gradebook) && $gradebook == 'view') {
     $interbreadcrumb[] = array(
-        'url' => '../gradebook/' . $_SESSION['gradebook_dest'],
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
         'name' => get_lang('ToolGradebook')
     );
 }
 
 $interbreadcrumb[] = array("url" => "exercice.php", "name" => get_lang('Exercices'));
 if (isset($_GET['newQuestion']) || isset($_GET['editQuestion'])) {
-    $interbreadcrumb[] = array("url" => "admin.php?exerciseId=" . $objExercise->id, "name" => $objExercise->name);
+    $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$objExercise->id, "name" => $objExercise->name);
 } else {
     $interbreadcrumb[] = array("url" => "#", "name" => $objExercise->name);
 }
 
 // shows a link to go back to the question pool
 if (!$exerciseId && $nameTools != get_lang('ExerciseManagement')) {
-    $interbreadcrumb[] = array("url" => "question_pool.php?fromExercise=$fromExercise", "name" => get_lang('QuestionPool'));
+    $interbreadcrumb[] = array(
+        "url" => "question_pool.php?fromExercise=$fromExercise",
+        "name" => get_lang('QuestionPool')
+    );
 }
 
 // if the question is duplicated, disable the link of tool name
@@ -442,20 +452,50 @@ if ($objExercise->exercise_was_added_in_lp) {
 $inATest = isset($exerciseId) && $exerciseId > 0;
 if ($inATest) {
     echo '<div class="actions">';
-    if (isset($_GET['hotspotadmin']) || isset($_GET['newQuestion']) || isset($_GET['myid']))
-        echo '<a href="admin.php?exerciseId=' . $exerciseId . '">' . Display::return_icon('back.png', get_lang('GoBackToQuestionList'), '', ICON_SIZE_MEDIUM) . '</a>';
+    if (isset($_GET['hotspotadmin']) || isset($_GET['newQuestion']) || isset($_GET['myid'])) {
+        echo '<a href="admin.php?exerciseId='.$exerciseId.'">'.Display::return_icon(
+            'back.png',
+            get_lang('GoBackToQuestionList'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+    }
 
     if (!isset($_GET['hotspotadmin']) && !isset($_GET['newQuestion']) && !isset($_GET['myid']) && !isset($_GET['editQuestion'])) {
-        echo '<a href="exercice.php?' . api_get_cidReq() . '">' . Display::return_icon('back.png', get_lang('BackToExercisesList'), '', ICON_SIZE_MEDIUM) . '</a>';
+        echo '<a href="exercice.php?'.api_get_cidReq().'">'.Display::return_icon(
+            'back.png',
+            get_lang('BackToExercisesList'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
     }
-    echo '<a href="overview.php?' . api_get_cidreq() . '&exerciseId=' . $objExercise->id . '&preview=1">' . Display::return_icon('preview_view.png', get_lang('Preview'), '', ICON_SIZE_MEDIUM) . '</a>';
-
-    echo Display::url(Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_MEDIUM), 'exercise_report.php?' . api_get_cidReq() . '&exerciseId=' . $objExercise->id);
+    echo '<a href="overview.php?'.api_get_cidreq().'&exerciseId='.$objExercise->id.'&preview=1">'.Display::return_icon(
+        'preview_view.png',
+        get_lang('Preview'),
+        '',
+        ICON_SIZE_MEDIUM
+    ).'</a>';
+
+    echo Display::url(
+        Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_MEDIUM),
+        'exercise_report.php?'.api_get_cidReq().'&exerciseId='.$objExercise->id
+    );
 
     if ($objExercise->edit_exercise_in_lp == false) {
-        echo '<a href="">' . Display::return_icon('settings_na.png', get_lang('ModifyExercise'), '', ICON_SIZE_MEDIUM) . '</a>';
+        echo '<a href="">'.Display::return_icon(
+            'settings_na.png',
+            get_lang('ModifyExercise'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
     } else {
-        echo '<a href="exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$objExercise->id.'">'.Display::return_icon('settings.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
+        echo '<a href="exercise_admin.php?'.api_get_cidreq(
+        ).'&modifyExercise=yes&exerciseId='.$objExercise->id.'">'.Display::return_icon(
+            'settings.png',
+            get_lang('ModifyExercise'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
     }
 
     $maxScoreAllQuestions = 0;
@@ -467,18 +507,34 @@ if ($inATest) {
             }
         }
     }
-    echo '<span style="float:right">' . sprintf(get_lang('XQuestionsWithTotalScoreY'), $objExercise->selectNbrQuestions(), $maxScoreAllQuestions) . '</span>';
-    echo '</div>';
-} else if (isset($_GET['newQuestion'])) {
-    // we are in create a new question from question pool not in a test
-    echo '<div class="actions">';
-    echo '<a href="admin.php?' . api_get_cidreq() . '">.' . Display::return_icon('back.png', get_lang('GoBackToQuestionList'), '', ICON_SIZE_MEDIUM) . '</a>';
+    echo '<span style="float:right">'.sprintf(
+        get_lang('XQuestionsWithTotalScoreY'),
+        $objExercise->selectNbrQuestions(),
+        $maxScoreAllQuestions
+    ).'</span>';
     echo '</div>';
 } else {
-    // If we are in question_poolbut not in an test, go back to question create in pool
-    echo '<div class="actions">';
-    echo '<a href="question_pool.php">' . Display::return_icon('back.png', get_lang('GoBackToQuestionList'), '', ICON_SIZE_MEDIUM) . '</a>';
-    echo '</div>';
+    if (isset($_GET['newQuestion'])) {
+        // we are in create a new question from question pool not in a test
+        echo '<div class="actions">';
+        echo '<a href="admin.php?'.api_get_cidreq().'">.'.Display::return_icon(
+            'back.png',
+            get_lang('GoBackToQuestionList'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+        echo '</div>';
+    } else {
+        // If we are in question_poolbut not in an test, go back to question create in pool
+        echo '<div class="actions">';
+        echo '<a href="question_pool.php">'.Display::return_icon(
+            'back.png',
+            get_lang('GoBackToQuestionList'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+        echo '</div>';
+    }
 }
 
 if (isset($_GET['message'])) {
@@ -490,7 +546,7 @@ if (isset($_GET['message'])) {
 if ($newQuestion || $editQuestion) {
     // statement management
     $type = Security::remove_XSS($_REQUEST['answerType']);
-    echo '<input type="hidden" name="Type" value="' . $type . '" />';
+    echo '<input type="hidden" name="Type" value="'.$type.'" />';
     require 'question_admin.inc.php';
 }
 

Fișier diff suprimat deoarece este prea mare
+ 638 - 456
main/exercice/exercice.php


Fișier diff suprimat deoarece este prea mare
+ 430 - 109
main/exercice/exercise.class.php


+ 286 - 170
main/exercice/exercise_report.php

@@ -1,12 +1,12 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- *	Exercise list: This script shows the list of exercises for administrators and students.
- *	@package chamilo.exercise
- *	@author Julio Montoya <gugli100@gmail.com> jqgrid integration
+ *    Exercise list: This script shows the list of exercises for administrators and students.
+ * @package chamilo.exercise
+ * @author Julio Montoya <gugli100@gmail.com> jqgrid integration
  *   Modified by hubert.borderiou (question category)
  *
- *  @todo fix excel export
+ * @todo fix excel export
  *
  */
 /**
@@ -32,28 +32,27 @@ require_once 'exercise.class.php';
 require_once 'exercise.lib.php';
 require_once 'question.class.php';
 require_once 'answer.class.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once 'hotpotatoes.lib.php';
 
 // need functions of statsutils lib to display previous exercices scores
-require_once api_get_path(LIBRARY_PATH) . 'statsUtils.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php';
 
 // document path
-$documentPath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . "/document";
+$documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
 
 /*	Constants and variables */
-$is_allowedToEdit           = api_is_allowed_to_edit(null, true) || api_is_drh();
-$is_tutor                   = api_is_allowed_to_edit(true);
+$is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_drh();
+$is_tutor = api_is_allowed_to_edit(true);
 
-$TBL_QUESTIONS              = Database :: get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_TRACK_EXERCICES        = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$TBL_TRACK_ATTEMPT          = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-$TBL_TRACK_ATTEMPT_RECORDING= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
-$TBL_LP_ITEM_VIEW           = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+$TBL_QUESTIONS = Database :: get_course_table(TABLE_QUIZ_QUESTION);
+$TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_ATTEMPT = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+$TBL_TRACK_ATTEMPT_RECORDING = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+$TBL_LP_ITEM_VIEW = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
 
-$course_id      = api_get_course_int_id();
-$exercise_id    = isset($_REQUEST['exerciseId']) ? intval($_REQUEST['exerciseId']) : null;
-$filter_user    = isset($_REQUEST['filter_by_user']) ? intval($_REQUEST['filter_by_user']) : null;
+$course_id = api_get_course_int_id();
+$exercise_id = isset($_REQUEST['exerciseId']) ? intval($_REQUEST['exerciseId']) : null;
+$filter_user = isset($_REQUEST['filter_by_user']) ? intval($_REQUEST['filter_by_user']) : null;
 
 $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE);
 
@@ -65,8 +64,9 @@ if (!$is_allowedToEdit) {
     api_not_allowed(true);
 }
 
-if (!empty($exercise_id))
+if (!empty($exercise_id)) {
     $parameters['exerciseId'] = $exercise_id;
+}
 if (!empty($_GET['path'])) {
     $parameters['path'] = Security::remove_XSS($_GET['path']);
 }
@@ -83,13 +83,27 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
         switch ($_GET['export_format']) {
             case 'xls' :
                 $export = new ExerciseResult();
-                $export->exportCompleteReportXLS($documentPath, null, $load_extra_data, null, $_GET['exerciseId'], $_GET['hotpotato_name']);
+                $export->exportCompleteReportXLS(
+                    $documentPath,
+                    null,
+                    $load_extra_data,
+                    null,
+                    $_GET['exerciseId'],
+                    $_GET['hotpotato_name']
+                );
                 exit;
                 break;
             case 'csv' :
             default :
                 $export = new ExerciseResult();
-                $export->exportCompleteReportCSV($documentPath, null, $load_extra_data, null, $_GET['exerciseId'], $_GET['hotpotato_name']);
+                $export->exportCompleteReportCSV(
+                    $documentPath,
+                    null,
+                    $load_extra_data,
+                    null,
+                    $_GET['exerciseId'],
+                    $_GET['hotpotato_name']
+                );
                 exit;
                 break;
         }
@@ -99,39 +113,48 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
 }
 
 //Send student email @todo move this code in a class, library
-if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid'] == strval(intval($_GET['exeid']))) {
+if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid'] == strval(
+    intval($_GET['exeid'])
+)
+) {
     $id = intval($_GET['exeid']); //filtered by post-condition
     $track_exercise_info = get_exercise_track_exercise_info($id);
     if (empty($track_exercise_info)) {
         api_not_allowed();
     }
-    $test              = $track_exercise_info['title'];
-    $student_id        = $track_exercise_info['exe_user_id'];
-    $session_id        = $track_exercise_info['session_id'];
-    $lp_id             = $track_exercise_info['orig_lp_id'];
+    $test = $track_exercise_info['title'];
+    $student_id = $track_exercise_info['exe_user_id'];
+    $session_id = $track_exercise_info['session_id'];
+    $lp_id = $track_exercise_info['orig_lp_id'];
     //$lp_item_id        = $track_exercise_info['orig_lp_item_id'];
-    $lp_item_view_id   = $track_exercise_info['orig_lp_item_view_id'];
+    $lp_item_view_id = $track_exercise_info['orig_lp_item_view_id'];
 
     $course_info = api_get_course_info();
 
     // Teacher data
-    $teacher_info      = api_get_user_info(api_get_user_id());
-    $from_name         = api_get_person_name($teacher_info['firstname'], $teacher_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
-    $url               = api_get_path(WEB_CODE_PATH) . 'exercice/result.php?id='.$track_exercise_info['exe_id'].'&'.api_get_cidreq().'&show_headers=1&id_session='.$session_id;
+    $teacher_info = api_get_user_info(api_get_user_id());
+    $from_name = api_get_person_name(
+        $teacher_info['firstname'],
+        $teacher_info['lastname'],
+        null,
+        PERSON_NAME_EMAIL_ADDRESS
+    );
+    $url = api_get_path(WEB_CODE_PATH).'exercice/result.php?id='.$track_exercise_info['exe_id'].'&'.api_get_cidreq(
+    ).'&show_headers=1&id_session='.$session_id;
 
-    $my_post_info      = array();
-    $post_content_id   = array();
-    $comments_exist    = false;
+    $my_post_info = array();
+    $post_content_id = array();
+    $comments_exist = false;
 
     foreach ($_POST as $key_index => $key_value) {
-        $my_post_info  = explode('_',$key_index);
-        $post_content_id[]=$my_post_info[1];
-        if ($my_post_info[0]=='comments') {
-            $comments_exist=true;
+        $my_post_info = explode('_', $key_index);
+        $post_content_id[] = $my_post_info[1];
+        if ($my_post_info[0] == 'comments') {
+            $comments_exist = true;
         }
     }
 
-    $loop_in_track = ($comments_exist===true) ? (count($_POST)/2) : count($_POST);
+    $loop_in_track = ($comments_exist === true) ? (count($_POST) / 2) : count($_POST);
 
     $array_content_id_exe = array();
 
@@ -141,30 +164,31 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G
         $array_content_id_exe = $post_content_id;
     }
 
-    for ($i=0; $i < $loop_in_track; $i++) {
-        $my_marks           = Database::escape_string($_POST['marks_'.$array_content_id_exe[$i]]);
-        $contain_comments   = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
+    for ($i = 0; $i < $loop_in_track; $i++) {
+        $my_marks = Database::escape_string($_POST['marks_'.$array_content_id_exe[$i]]);
+        $contain_comments = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
         if (isset($contain_comments)) {
-            $my_comments    = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
+            $my_comments = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
         } else {
-            $my_comments    = '';
+            $my_comments = '';
         }
         $my_questionid = intval($array_content_id_exe[$i]);
         $sql = "SELECT question from $TBL_QUESTIONS WHERE c_id = $course_id AND id = '$my_questionid'";
 
-        $result =Database::query($sql);
-        Database::result($result,0,"question");
+        $result = Database::query($sql);
+        Database::result($result, 0, "question");
 
         $query = "UPDATE $TBL_TRACK_ATTEMPT SET marks = '$my_marks', teacher_comment = '$my_comments' WHERE question_id = ".$my_questionid." AND exe_id=".$id;
         Database::query($query);
 
         //Saving results in the track recording table
         $recording_changes = 'INSERT INTO '.$TBL_TRACK_ATTEMPT_RECORDING.' (exe_id, question_id, marks, insert_date, author, teacher_comment)
-                              VALUES ('."'$id','".$my_questionid."','$my_marks','".api_get_utc_datetime()."','".api_get_user_id()."'".',"'.$my_comments.'")';
+                              VALUES ('."'$id','".$my_questionid."','$my_marks','".api_get_utc_datetime(
+        )."','".api_get_user_id()."'".',"'.$my_comments.'")';
         Database::query($recording_changes);
     }
 
-    $qry = 'SELECT DISTINCT question_id, marks FROM ' . $TBL_TRACK_ATTEMPT . ' WHERE exe_id = '.$id .' GROUP BY question_id';
+    $qry = 'SELECT DISTINCT question_id, marks FROM '.$TBL_TRACK_ATTEMPT.' WHERE exe_id = '.$id.' GROUP BY question_id';
     $res = Database::query($qry);
     $tot = 0;
     while ($row = Database :: fetch_array($res, 'ASSOC')) {
@@ -178,13 +202,13 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G
         //@todo move this somewhere else
         $subject = get_lang('ExamSheetVCC');
 
-        $message  = '<p>'.get_lang('DearStudentEmailIntroduction') . '</p><p>'.get_lang('AttemptVCC');
-        $message .= '<h3>'.get_lang('CourseName'). '</h3><p>'.Security::remove_XSS($course_info['name']).'';
-        $message .= '<h3>'.get_lang('Exercise') . '</h3><p>'.Security::remove_XSS($test);
+        $message = '<p>'.get_lang('DearStudentEmailIntroduction').'</p><p>'.get_lang('AttemptVCC');
+        $message .= '<h3>'.get_lang('CourseName').'</h3><p>'.Security::remove_XSS($course_info['name']).'';
+        $message .= '<h3>'.get_lang('Exercise').'</h3><p>'.Security::remove_XSS($test);
 
         //Only for exercises not in a LP
         if ($lp_id == 0) {
-            $message .= '<p>'.get_lang('ClickLinkToViewComment') . ' <a href="#url#">#url#</a><br />';
+            $message .= '<p>'.get_lang('ClickLinkToViewComment').' <a href="#url#">#url#</a><br />';
         }
 
         $message .= '<p>'.get_lang('Regards').'</p>';
@@ -195,16 +219,20 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G
     }
 
     //Updating LP score here
-    if (in_array($origin, array ('tracking_course','user_course','correct_exercise_in_lp'))) {
-        $sql_update_score = "UPDATE $TBL_LP_ITEM_VIEW SET score = '" . floatval($tot) . "' WHERE c_id = ".$course_id." AND id = " .$lp_item_view_id;
+    if (in_array($origin, array('tracking_course', 'user_course', 'correct_exercise_in_lp'))) {
+        $sql_update_score = "UPDATE $TBL_LP_ITEM_VIEW SET score = '".floatval(
+            $tot
+        )."' WHERE c_id = ".$course_id." AND id = ".$lp_item_view_id;
         Database::query($sql_update_score);
         if ($origin == 'tracking_course') {
             //Redirect to the course detail in lp
-            header('location: exercice.php?course=' . Security :: remove_XSS($_GET['course']));
+            header('location: exercice.php?course='.Security :: remove_XSS($_GET['course']));
             exit;
         } else {
             //Redirect to the reporting
-            header('location: ../mySpace/myStudents.php?origin=' . $origin . '&student=' . $student_id . '&details=true&course=' . $course_id.'&session_id='.$session_id);
+            header(
+                'location: ../mySpace/myStudents.php?origin='.$origin.'&student='.$student_id.'&details=true&course='.$course_id.'&session_id='.$session_id
+            );
             exit;
         }
     }
@@ -214,38 +242,65 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G
 if ($is_allowedToEdit && $origin != 'learnpath') {
     // the form
     if (api_is_platform_admin() || api_is_course_admin() || api_is_course_tutor() || api_is_course_coach()) {
-        $actions .= '<a href="admin.php?exerciseId='.intval($_GET['exerciseId']).'">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
-        $actions .='<a href="live_stats.php?' . api_get_cidreq() . '&exerciseId='.$exercise_id.'">'.Display :: return_icon('activity_monitor.png', get_lang('LiveResults'),'',ICON_SIZE_MEDIUM).'</a>';
-        $actions .='<a href="stats.php?' . api_get_cidreq() . '&exerciseId='.$exercise_id.'">'.Display :: return_icon('statistics.png', get_lang('ReportByQuestion'),'', ICON_SIZE_MEDIUM).'</a>';
-        $actions .= '<a id="export_opener" href="'.api_get_self().'?export_report=1&hotpotato_name='.Security::remove_XSS($_GET['path']).'&exerciseId='.intval($_GET['exerciseId']).'" >'.
-                     Display::return_icon('save.png',   get_lang('Export'),'',ICON_SIZE_MEDIUM).'</a>';
+        $actions .= '<a href="admin.php?exerciseId='.intval($_GET['exerciseId']).'">'.Display :: return_icon(
+            'back.png',
+            get_lang('GoBackToQuestionList'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+        $actions .= '<a href="live_stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.Display :: return_icon(
+            'activity_monitor.png',
+            get_lang('LiveResults'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+        $actions .= '<a href="stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.Display :: return_icon(
+            'statistics.png',
+            get_lang('ReportByQuestion'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+        $actions .= '<a id="export_opener" href="'.api_get_self(
+        ).'?export_report=1&hotpotato_name='.Security::remove_XSS($_GET['path']).'&exerciseId='.intval(
+            $_GET['exerciseId']
+        ).'" >'.
+            Display::return_icon('save.png', get_lang('Export'), '', ICON_SIZE_MEDIUM).'</a>';
     }
 } else {
-    $actions .= '<a href="exercice.php">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
+    $actions .= '<a href="exercice.php">'.Display :: return_icon(
+        'back.png',
+        get_lang('GoBackToQuestionList'),
+        '',
+        ICON_SIZE_MEDIUM
+    ).'</a>';
 }
 
 //Deleting an attempt
-if ( ($is_allowedToEdit || $is_tutor || api_is_coach()) && $_GET['delete'] == 'delete' && !empty ($_GET['did']) && $locked == false) {
+if (($is_allowedToEdit || $is_tutor || api_is_coach(
+)) && $_GET['delete'] == 'delete' && !empty ($_GET['did']) && $locked == false
+) {
     $exe_id = intval($_GET['did']);
     if (!empty($exe_id)) {
         $sql = 'DELETE FROM '.$TBL_TRACK_EXERCICES.' WHERE exe_id = '.$exe_id;
         Database::query($sql);
         $sql = 'DELETE FROM '.$TBL_TRACK_ATTEMPT.' WHERE exe_id = '.$exe_id;
         Database::query($sql);
-        header('Location: exercise_report.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&exerciseId='.$exercise_id);
+        header(
+            'Location: exercise_report.php?cidReq='.Security::remove_XSS($_GET['cidReq']).'&exerciseId='.$exercise_id
+        );
         exit;
     }
 }
 
 if ($is_allowedToEdit || $is_tutor) {
     $nameTools = get_lang('StudentScore');
-    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
+    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook", "name" => get_lang('Exercices'));
     $objExerciseTmp = new Exercise();
     if ($objExerciseTmp->read($exercise_id)) {
         $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$exercise_id, "name" => $objExerciseTmp->name);
     }
 } else {
-    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
+    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook", "name" => get_lang('Exercices'));
     $objExerciseTmp = new Exercise();
     if ($objExerciseTmp->read($exercise_id)) {
         $nameTools = get_lang('Results').': '.$objExerciseTmp->name;
@@ -254,9 +309,9 @@ if ($is_allowedToEdit || $is_tutor) {
 
 Display :: display_header($nameTools);
 
-$actions = Display::div($actions, array('class'=> 'actions'));
+$actions = Display::div($actions, array('class' => 'actions'));
 
-$extra =  '<script>
+$extra = '<script>
     $(document).ready(function() {
 
         $( "#dialog:ui-dialog" ).dialog( "destroy" );
@@ -291,26 +346,50 @@ $extra =  '<script>
 
 $extra .= '<div id="dialog-confirm" title="'.get_lang("ConfirmYourChoice").'">';
 $form = new FormValidator('report', 'post', null, null, array('class' => 'form-vertical'));
-$form->addElement('radio', 'export_format', null, get_lang('ExportAsCSV'), 'csv', array('id' => 'export_format_csv_label'));
-$form->addElement('radio', 'export_format', null, get_lang('ExportAsXLS'), 'xls', array('id' => 'export_format_xls_label'));
-$form->addElement('checkbox', 'load_extra_data', null, get_lang('LoadExtraData'), '0', array('id' => 'export_format_xls_label'));
+$form->addElement(
+    'radio',
+    'export_format',
+    null,
+    get_lang('ExportAsCSV'),
+    'csv',
+    array('id' => 'export_format_csv_label')
+);
+$form->addElement(
+    'radio',
+    'export_format',
+    null,
+    get_lang('ExportAsXLS'),
+    'xls',
+    array('id' => 'export_format_xls_label')
+);
+$form->addElement(
+    'checkbox',
+    'load_extra_data',
+    null,
+    get_lang('LoadExtraData'),
+    '0',
+    array('id' => 'export_format_xls_label')
+);
 $form->setDefaults(array('export_format' => 'csv'));
 $extra .= $form->return_form();
 $extra .= '</div>';
 
-if ($is_allowedToEdit)
+if ($is_allowedToEdit) {
     echo $extra;
+}
 
 echo $actions;
 
-$url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_exercise_results&exerciseId='.$exercise_id.'&filter_by_user='.$filter_user;
+$url = api_get_path(
+    WEB_AJAX_PATH
+).'model.ajax.php?a=get_exercise_results&exerciseId='.$exercise_id.'&filter_by_user='.$filter_user;
 
 $action_links = '';
 
 //Generating group list
 
 $group_list = GroupManager::get_group_list();
-$group_parameters = array('group_all:'.get_lang('All'),'group_none:'.get_lang('None'));
+$group_parameters = array('group_all:'.get_lang('All'), 'group_none:'.get_lang('None'));
 
 foreach ($group_list as $group) {
     $group_parameters[] = $group['id'].':'.$group['name'];
@@ -321,53 +400,87 @@ if (!empty($group_parameters)) {
 
 if ($is_allowedToEdit || $is_tutor) {
 
-	//The order is important you need to check the the $column variable in the model.ajax.php file
-	$columns        = array(get_lang('FirstName'),
-                            get_lang('LastName'),
-                            get_lang('LoginName'),
-                            get_lang('Group'),
-                            get_lang('Duration').' ('.get_lang('MinMinute').')',
-                            get_lang('StartDate'),
-                            get_lang('EndDate'),
-                            get_lang('Score'),
-                            get_lang('Status'),
-                            get_lang('ToolLearnpath'),
-                            get_lang('Actions')
+    //The order is important you need to check the the $column variable in the model.ajax.php file
+    $columns = array(
+        get_lang('FirstName'),
+        get_lang('LastName'),
+        get_lang('LoginName'),
+        get_lang('Group'),
+        get_lang('Duration').' ('.get_lang('MinMinute').')',
+        get_lang('StartDate'),
+        get_lang('EndDate'),
+        get_lang('Score'),
+        get_lang('Status'),
+        get_lang('ToolLearnpath'),
+        get_lang('Actions')
     );
 
 //Column config
-	$column_model   = array(
-                        array('name'=>'firstname',      'index'=>'firstname',		'width'=>'50',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'lastname',		'index'=>'lastname',		'width'=>'50',   'align'=>'left', 'formatter'=>'action_formatter', 'search' => 'true'),
-                        array('name'=>'login',          'index'=>'username',        'width'=>'40',   'align'=>'left', 'search' => 'true', 'hidden'=>'true'),
-                        array('name'=>'group_name',		'index'=>'group_id',        'width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=> 'select',
-                            //for the bottom bar
-                            'searchoptions' => array(
-                                            'defaultValue'  => 'group_all',
-                                            'value'         => $group_parameters),
-                              //for the top bar
-                            'editoptions' => array('value' => $group_parameters)),
-                        array('name'=>'duration',       'index'=>'exe_duration',	'width'=>'30',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'start_date',		'index'=>'start_date',		'width'=>'60',   'align'=>'left', 'search' => 'true'),
-			array('name'=>'exe_date',		'index'=>'exe_date',		'width'=>'60',   'align'=>'left', 'search' => 'true'),
-			array('name'=>'score',			'index'=>'exe_result',	    'width'=>'50',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'status',         'index'=>'revised',			'width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=>'select',
-                              //for the bottom bar
-                              'searchoptions' => array(
-                                                'defaultValue'  => '',
-                                                'value'         => ':'.get_lang('All').';1:'.get_lang('Validated').';0:'.get_lang('NotValidated')),
-
-                              //for the top bar
-                              'editoptions' => array('value' => ':'.get_lang('All').';1:'.get_lang('Validated').';0:'.get_lang('NotValidated'))),
-                        array('name'=>'lp',             'index'=>'lp',              'width'=>'60',  'align'=>'left', 'search' => 'false'),
-						array('name'=>'actions',        'index'=>'actions',         'width'=>'60',  'align'=>'left', 'search' => 'false')
-                       );
+    $column_model = array(
+        array('name' => 'firstname', 'index' => 'firstname', 'width' => '50', 'align' => 'left', 'search' => 'true'),
+        array(
+            'name' => 'lastname',
+            'index' => 'lastname',
+            'width' => '50',
+            'align' => 'left',
+            'formatter' => 'action_formatter',
+            'search' => 'true'
+        ),
+        array(
+            'name' => 'login',
+            'index' => 'username',
+            'width' => '40',
+            'align' => 'left',
+            'search' => 'true',
+            'hidden' => 'true'
+        ),
+        array(
+            'name' => 'group_name',
+            'index' => 'group_id',
+            'width' => '40',
+            'align' => 'left',
+            'search' => 'true',
+            'stype' => 'select',
+            //for the bottom bar
+            'searchoptions' => array(
+                'defaultValue' => 'group_all',
+                'value' => $group_parameters
+            ),
+            //for the top bar
+            'editoptions' => array('value' => $group_parameters)
+        ),
+        array('name' => 'duration', 'index' => 'exe_duration', 'width' => '30', 'align' => 'left', 'search' => 'true'),
+        array('name' => 'start_date', 'index' => 'start_date', 'width' => '60', 'align' => 'left', 'search' => 'true'),
+        array('name' => 'exe_date', 'index' => 'exe_date', 'width' => '60', 'align' => 'left', 'search' => 'true'),
+        array('name' => 'score', 'index' => 'exe_result', 'width' => '50', 'align' => 'left', 'search' => 'true'),
+        array(
+            'name' => 'status',
+            'index' => 'revised',
+            'width' => '40',
+            'align' => 'left',
+            'search' => 'true',
+            'stype' => 'select',
+            //for the bottom bar
+            'searchoptions' => array(
+                'defaultValue' => '',
+                'value' => ':'.get_lang('All').';1:'.get_lang('Validated').';0:'.get_lang('NotValidated')
+            ),
+            //for the top bar
+            'editoptions' => array(
+                'value' => ':'.get_lang('All').';1:'.get_lang('Validated').';0:'.get_lang(
+                    'NotValidated'
+                )
+            )
+        ),
+        array('name' => 'lp', 'index' => 'lp', 'width' => '60', 'align' => 'left', 'search' => 'false'),
+        array('name' => 'actions', 'index' => 'actions', 'width' => '60', 'align' => 'left', 'search' => 'false')
+    );
 
     $action_links = '
     // add username as title in lastname filed - ref 4226
     function action_formatter(cellvalue, options, rowObject) {
         // rowObject is firstname,lastname,login,... get the third word
-        var loginx = "'.api_htmlentities(sprintf(get_lang("LoginX"),":::"), ENT_QUOTES).'";
+        var loginx = "'.api_htmlentities(sprintf(get_lang("LoginX"), ":::"), ENT_QUOTES).'";
         var tabLoginx = loginx.split(/:::/);
         // tabLoginx[0] is before and tabLoginx[1] is after :::
         // may be empty string but is defined
@@ -384,69 +497,72 @@ $extra_params['height'] = 'auto';
 ?>
 <script>
 
-function setSearchSelect(columnName) {
-    $("#results").jqGrid('setColProp', columnName,
-    {
-       searchoptions:{
-            dataInit:function(el){
-                $("option[value='1']",el).attr("selected", "selected");
-                setTimeout(function(){
-                    $(el).trigger('change');
-                },1000);
-            }
-        }
-    });
-}
+    function setSearchSelect(columnName) {
+        $("#results").jqGrid('setColProp', columnName,
+                {
+                    searchoptions:{
+                        dataInit:function (el) {
+                            $("option[value='1']", el).attr("selected", "selected");
+                            setTimeout(function () {
+                                $(el).trigger('change');
+                            }, 1000);
+                        }
+                    }
+                });
+    }
 
-function exportExcel() {
-    var mya=new Array();
-    mya=$("#results").getDataIDs();  // Get All IDs
-    var data=$("#results").getRowData(mya[0]);     // Get First row to get the labels
-    var colNames=new Array();
-    var ii=0;
-    for (var i in data){colNames[ii++]=i;}    // capture col names
-    var html="";
-
-    for(i=0;i<mya.length;i++) {
-        data=$("#results").getRowData(mya[i]); // get each row
-        for(j=0;j<colNames.length;j++) {
-            html=html+data[colNames[j]]+","; // output each column as tab delimited
+    function exportExcel() {
+        var mya = new Array();
+        mya = $("#results").getDataIDs();  // Get All IDs
+        var data = $("#results").getRowData(mya[0]);     // Get First row to get the labels
+        var colNames = new Array();
+        var ii = 0;
+        for (var i in data) {
+            colNames[ii++] = i;
+        }    // capture col names
+        var html = "";
+
+        for (i = 0; i < mya.length; i++) {
+            data = $("#results").getRowData(mya[i]); // get each row
+            for (j = 0; j < colNames.length; j++) {
+                html = html + data[colNames[j]] + ","; // output each column as tab delimited
+            }
+            html = html + "\n";  // output each row with end of line
         }
-        html=html+"\n";  // output each row with end of line
-    }
-    html = html+"\n";  // end of line at the end
+        html = html + "\n";  // end of line at the end
 
-    var form = $("#export_report_form");
+        var form = $("#export_report_form");
 
-    $("#csvBuffer").attr('value', html);
-    form.target='_blank';
-    form.submit();
-}
+        $("#csvBuffer").attr('value', html);
+        form.target = '_blank';
+        form.submit();
+    }
 
-$(function() {
+    $(function () {
     <?php
-        echo Display::grid_js('results', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
+    echo Display::grid_js('results', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
 
-    if ($is_allowedToEdit || $is_tutor) { ?>
+    if ($is_allowedToEdit || $is_tutor) {
+        ?>
 
         //setSearchSelect("status");
         //
         //view:true, del:false, add:false, edit:false, excel:true}
-        $("#results").jqGrid('navGrid','#results_pager', {view:true, edit:false, add:false, del:false, excel:false},
-            {height:280, reloadAfterSubmit:false}, // view options
-            {height:280, reloadAfterSubmit:false}, // edit options
-            {height:280, reloadAfterSubmit:false}, // add options
-            {reloadAfterSubmit: false}, // del options
-            {width:500} // search options
+        $("#results").jqGrid('navGrid', '#results_pager', {view:true, edit:false, add:false, del:false, excel:false},
+                {height:280, reloadAfterSubmit:false}, // view options
+                {height:280, reloadAfterSubmit:false}, // edit options
+                {height:280, reloadAfterSubmit:false}, // add options
+                {reloadAfterSubmit:false}, // del options
+                {width:500} // search options
         );
-                  /*
-        // add custom button to export the data to excel
-        jQuery("#results").jqGrid('navButtonAdd','#results_pager',{
-            caption:"",
-            onClickButton : function () {
-                 //exportExcel();
-            }
-        });*/
+        /*
+// add custom button to export the data to excel
+jQuery("#results").jqGrid('navButtonAdd','#results_pager',{
+  caption:"",
+  onClickButton : function () {
+       //exportExcel();
+  }
+});*/
 
         /*
         jQuery('#sessions').jqGrid('navButtonAdd','#sessions_pager',{id:'pager_csv',caption:'',title:'Export To CSV',onClickButton : function(e)
@@ -461,21 +577,21 @@ $(function() {
 
         //Adding search options
         var options = {
-            'stringResult': true,
-            'autosearch' : true,
+            'stringResult':true,
+            'autosearch':true,
             'searchOnEnter':false
         }
-        jQuery("#results").jqGrid('filterToolbar',options);
+        jQuery("#results").jqGrid('filterToolbar', options);
         var sgrid = $("#results")[0];
         sgrid.triggerToolbar();
 
-    <?php } ?>
-});
+        <?php } ?>
+    });
 </script>
 <form id="export_report_form" method="post" action="exercise_report.php">
-    <input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
-    <input type="hidden" name="export_report" id="export_report" value="1" />
-    <input type="hidden" name="exerciseId" id="exerciseId" value="<?php echo $exercise_id ?>" />
+    <input type="hidden" name="csvBuffer" id="csvBuffer" value=""/>
+    <input type="hidden" name="export_report" id="export_report" value="1"/>
+    <input type="hidden" name="exerciseId" id="exerciseId" value="<?php echo $exercise_id ?>"/>
 </form>
 <?php
 

+ 579 - 527
main/exercice/export/exercise_import.inc.php

@@ -12,247 +12,278 @@
 /**
  * Security check
  */
-if (count(get_included_files()) == 1)
-	die('---');
+if (count(get_included_files()) == 1) {
+    die('---');
+}
 
 /**
  * function to create a temporary directory (SAME AS IN MODULE ADMIN)
  */
 
-function tempdir($dir, $prefix = 'tmp', $mode = 0777) {
-	if (substr($dir, -1) != '/')
-		$dir .= '/';
+function tempdir($dir, $prefix = 'tmp', $mode = 0777)
+{
+    if (substr($dir, -1) != '/') {
+        $dir .= '/';
+    }
 
-	do {
-		$path = $dir . $prefix . mt_rand(0, 9999999);
-	} while (!mkdir($path, $mode));
+    do {
+        $path = $dir.$prefix.mt_rand(0, 9999999);
+    } while (!mkdir($path, $mode));
 
-	return $path;
+    return $path;
 }
 
 /**
  * @return the path of the temporary directory where the exercise was uploaded and unzipped
  */
 
-function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath) {
-	global $_course, $_user;
-	//Check if the file is valid (not to big and exists)
-	if (!isset ($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
-		// upload failed
-		return false;
-	}	
-	if (preg_match('/.zip$/i', $_FILES['userFile']['name']) && handle_uploaded_document($_course, $_FILES['userFile'], $baseWorkDir, $uploadPath, $_user['user_id'], 0, null, 1)) {
-		if (!function_exists('gzopen')) {			
-			//claro_delete_file($uploadPath);
-			return false;
-		}
-		// upload successfull
-		return true;
-	} else {
-		//claro_delete_file($uploadPath);
-		return false;
-	}
+function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)
+{
+    global $_course, $_user;
+    //Check if the file is valid (not to big and exists)
+    if (!isset ($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
+        // upload failed
+        return false;
+    }
+    if (preg_match('/.zip$/i', $_FILES['userFile']['name']) && FileManager::handle_uploaded_document(
+        $_course,
+        $_FILES['userFile'],
+        $baseWorkDir,
+        $uploadPath,
+        $_user['user_id'],
+        0,
+        null,
+        1
+    )
+    ) {
+        if (!function_exists('gzopen')) {
+            //claro_delete_file($uploadPath);
+            return false;
+        }
+
+        // upload successfull
+        return true;
+    } else {
+        //claro_delete_file($uploadPath);
+        return false;
+    }
 }
+
 /**
  * main function to import an exercise,
  *
  * @return an array as a backlog of what was really imported, and error or debug messages to display
  */
 
-function import_exercise($file) {
-	global $exercise_info;
-	global $element_pile;
-	global $non_HTML_tag_to_avoid;
-	global $record_item_body;
-	// used to specify the question directory where files could be found in relation in any question
-	global $questionTempDir;
-
-	$archive_path = api_get_path(SYS_ARCHIVE_PATH) . 'qti2';
-	$baseWorkDir = $archive_path;
-
-	if (!is_dir($baseWorkDir)) {
-		mkdir($baseWorkDir, api_get_permissions_for_new_directories(), true);
-	}
-
-	$uploadPath = '/';
-
-	// set some default values for the new exercise
-	$exercise_info = array ();
-	$exercise_info['name'] = preg_replace('/.zip$/i', '', $file);
-	$exercise_info['question'] = array();
-	$element_pile = array ();
-
-	// create parser and array to retrieve info from manifest
-	$element_pile = array (); //pile to known the depth in which we are
-	//$module_info = array (); //array to store the info we need
-
-	// if file is not a .zip, then we cancel all
-	if (!preg_match('/.zip$/i', $file)) {
-		Display :: display_error_message(get_lang('You must upload a zip file'));
-		return false;
-	}
-
-	// unzip the uploaded file in a tmp directory
-	if (!get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)) {
-		Display :: display_error_message(get_lang('You must upload a zip file'));
-		return false;
-	}
-
-	// find the different manifests for each question and parse them.
-	$exerciseHandle = opendir($baseWorkDir);
-	//$question_number = 0;
-	$file_found = false;
-	$operation = false;
+function import_exercise($file)
+{
+    global $exercise_info;
+    global $element_pile;
+    global $non_HTML_tag_to_avoid;
+    global $record_item_body;
+    // used to specify the question directory where files could be found in relation in any question
+    global $questionTempDir;
+
+    $archive_path = api_get_path(SYS_ARCHIVE_PATH).'qti2';
+    $baseWorkDir = $archive_path;
+
+    if (!is_dir($baseWorkDir)) {
+        mkdir($baseWorkDir, api_get_permissions_for_new_directories(), true);
+    }
+
+    $uploadPath = '/';
+
+    // set some default values for the new exercise
+    $exercise_info = array();
+    $exercise_info['name'] = preg_replace('/.zip$/i', '', $file);
+    $exercise_info['question'] = array();
+    $element_pile = array();
+
+    // create parser and array to retrieve info from manifest
+    $element_pile = array(); //pile to known the depth in which we are
+    //$module_info = array (); //array to store the info we need
+
+    // if file is not a .zip, then we cancel all
+    if (!preg_match('/.zip$/i', $file)) {
+        Display :: display_error_message(get_lang('You must upload a zip file'));
+
+        return false;
+    }
+
+    // unzip the uploaded file in a tmp directory
+    if (!get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)) {
+        Display :: display_error_message(get_lang('You must upload a zip file'));
+
+        return false;
+    }
+
+    // find the different manifests for each question and parse them.
+    $exerciseHandle = opendir($baseWorkDir);
+    //$question_number = 0;
+    $file_found = false;
+    $operation = false;
     $result = false;
-	// parse every subdirectory to search xml question files
-	while (false !== ($file = readdir($exerciseHandle))) {
-		if (is_dir($baseWorkDir . '/' . $file) && $file != "." && $file != "..") {
-			//find each manifest for each question repository found
-			$questionHandle = opendir($baseWorkDir . '/' . $file);
-			while (false !== ($questionFile = readdir($questionHandle))) {
-				if (preg_match('/.xml$/i', $questionFile)) {
-					$result = parse_file($baseWorkDir, $file, $questionFile);
-					$file_found = true;
-				}
-			}
-		} elseif (preg_match('/.xml$/i', $file)) {
-			$result = parse_file($baseWorkDir, '', $file);
-			$file_found = true;
-		} // else ignore file
-	}
-	if (!$file_found) {
-		Display :: display_error_message(get_lang('No XML file found in the zip'));        
-		return false;
-	}
-    if ($result == false ) {        
+    // parse every subdirectory to search xml question files
+    while (false !== ($file = readdir($exerciseHandle))) {
+        if (is_dir($baseWorkDir.'/'.$file) && $file != "." && $file != "..") {
+            //find each manifest for each question repository found
+            $questionHandle = opendir($baseWorkDir.'/'.$file);
+            while (false !== ($questionFile = readdir($questionHandle))) {
+                if (preg_match('/.xml$/i', $questionFile)) {
+                    $result = parse_file($baseWorkDir, $file, $questionFile);
+                    $file_found = true;
+                }
+            }
+        } elseif (preg_match('/.xml$/i', $file)) {
+            $result = parse_file($baseWorkDir, '', $file);
+            $file_found = true;
+        } // else ignore file
+    }
+    if (!$file_found) {
+        Display :: display_error_message(get_lang('No XML file found in the zip'));
+
+        return false;
+    }
+    if ($result == false) {
         return false;
     }
 
-	//add exercise in tool
-
-	//1.create exercise
-	$exercise = new Exercise();
-	$exercise->exercise = $exercise_info['name'];
-    
-	$exercise->save();
-	$last_exercise_id = $exercise->selectId();
-	if (!empty($last_exercise_id)) {
-		//For each question found...
-		foreach ($exercise_info['question'] as $key => $question_array) {
-			//2.create question
-			$question = new Ims2Question();
-			$question->type = $question_array['type'];
-			$question->setAnswer();
-			$question->updateTitle($question_array['title']); // question ...
-			$type = $question->selectType();
-			$question->type = constant($type); // type ...
-			$question->save($last_exercise_id); // save computed grade
-			$last_question_id = $question->selectId();
-			//3.create answer
-			$answer = new Answer($last_question_id);
-			$answer->new_nbrAnswers = count($question_array['answer']);
-			foreach ($question_array['answer'] as $key => $answers) {
-				$split = explode('_', $key);
-				$i = $split[1];
-				$answer->new_answer[$i] = $answers['value']; // answer ...
-				$answer->new_comment[$i] = $answers['feedback']; // comment ...
-				$answer->new_position[$i] = $i; // position ...
-				// correct answers ...
-				if (in_array($key, $question_array['correct_answers'])) {
-					$answer->new_correct[$i] = 1;
-				} else {
-					$answer->new_correct[$i] = 0;
-				}
-				$answer->new_weighting[$i] = $question_array['weighting'][$key];
-			}
-			$answer->save();
-		}
-		// delete the temp dir where the exercise was unzipped
-		FileManager::my_delete($baseWorkDir . $uploadPath);
-		$operation = true;
-	}    
-	return $operation;
+    //add exercise in tool
+
+    //1.create exercise
+    $exercise = new Exercise();
+    $exercise->exercise = $exercise_info['name'];
+
+    $exercise->save();
+    $last_exercise_id = $exercise->selectId();
+    if (!empty($last_exercise_id)) {
+        //For each question found...
+        foreach ($exercise_info['question'] as $key => $question_array) {
+            //2.create question
+            $question = new Ims2Question();
+            $question->type = $question_array['type'];
+            $question->setAnswer();
+            $question->updateTitle($question_array['title']); // question ...
+            $type = $question->selectType();
+            $question->type = constant($type); // type ...
+            $question->save($last_exercise_id); // save computed grade
+            $last_question_id = $question->selectId();
+            //3.create answer
+            $answer = new Answer($last_question_id);
+            $answer->new_nbrAnswers = count($question_array['answer']);
+            foreach ($question_array['answer'] as $key => $answers) {
+                $split = explode('_', $key);
+                $i = $split[1];
+                $answer->new_answer[$i] = $answers['value']; // answer ...
+                $answer->new_comment[$i] = $answers['feedback']; // comment ...
+                $answer->new_position[$i] = $i; // position ...
+                // correct answers ...
+                if (in_array($key, $question_array['correct_answers'])) {
+                    $answer->new_correct[$i] = 1;
+                } else {
+                    $answer->new_correct[$i] = 0;
+                }
+                $answer->new_weighting[$i] = $question_array['weighting'][$key];
+            }
+            $answer->save();
+        }
+        // delete the temp dir where the exercise was unzipped
+        FileManager::my_delete($baseWorkDir.$uploadPath);
+        $operation = true;
+    }
+
+    return $operation;
 }
 
-function parse_file($exercisePath, $file, $questionFile) {
-	global $exercise_info;
-	global $element_pile;
-	global $non_HTML_tag_to_avoid;
-	global $record_item_body;
-	global $questionTempDir;
-
-	$questionTempDir = $exercisePath . '/' . $file . '/';
-	$questionFilePath = $questionTempDir . $questionFile;
-
-	if (!($fp = @ fopen($questionFilePath, 'r'))) {
-		Display :: display_error_message(get_lang('Error opening question\'s XML file'));
-		return false;
-	} else {
-		$data = fread($fp, filesize($questionFilePath));
-	}
-
-	//parse XML question file
-	$data = str_replace(array('<p>', '</p>','<front>','</front>'), '', $data);
-	
-	//used global variable start values declaration :
-
-	$record_item_body = false;
-	$non_HTML_tag_to_avoid = array (
-		"SIMPLECHOICE",
-		"CHOICEINTERACTION",
-		"INLINECHOICEINTERACTION",
-		"INLINECHOICE",
-		"SIMPLEMATCHSET",
-		"SIMPLEASSOCIABLECHOICE",
-		"TEXTENTRYINTERACTION",
-		"FEEDBACKINLINE",
-		"MATCHINTERACTION",
-		"ITEMBODY",
-		"BR",
-		"IMG"
-	);
-
-	//this array to detect tag not supported by claroline import in the xml file to warn the user.
-
-	$non_supported_content_in_question = array (
-		"GAPMATCHINTERACTION",
-		"EXTENDEDTEXTINTERACTION",
-		"HOTTEXTINTERACTION",
-		"HOTSPOTINTERACTION",
-		"SELECTPOINTINTERACTION",
-		"GRAPHICORDERINTERACTION",
-		"GRAPHICASSOCIATIONINTERACTION",
-		"GRAPHICGAPMATCHINTERACTION",
-		"POSITIONOBJECTINTERACTION",
-		"SLIDERINTERACTION",
-		"DRAWINGINTERACTION",
-		"UPLOADINTERACTION",
-		"RESPONSECONDITION",
-		"RESPONSEIF"
-	);
-	$question_format_supported = true;
-
-	$xml_parser = xml_parser_create();
-	xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, false);
-	xml_set_element_handler($xml_parser, 'startElement', 'endElement');
-	xml_set_character_data_handler($xml_parser, 'elementData');
-
-	if (!xml_parse($xml_parser, $data, feof($fp))) {
-		// if reading of the xml file in not successfull :
-		// set errorFound, set error msg, break while statement
-		Display :: display_error_message(get_lang('Error reading XML file'));
-		return false;
-	}
-
-	//close file
-	fclose($fp);
-	if (!$question_format_supported) {
-		Display :: display_error_message(get_lang('Unknown question format in file %file', array (
-			'%file' => $questionFile
-		)));
-		return false;
-	}
-	return true;
+function parse_file($exercisePath, $file, $questionFile)
+{
+    global $exercise_info;
+    global $element_pile;
+    global $non_HTML_tag_to_avoid;
+    global $record_item_body;
+    global $questionTempDir;
+
+    $questionTempDir = $exercisePath.'/'.$file.'/';
+    $questionFilePath = $questionTempDir.$questionFile;
+
+    if (!($fp = @ fopen($questionFilePath, 'r'))) {
+        Display :: display_error_message(get_lang('Error opening question\'s XML file'));
+
+        return false;
+    } else {
+        $data = fread($fp, filesize($questionFilePath));
+    }
+
+    //parse XML question file
+    $data = str_replace(array('<p>', '</p>', '<front>', '</front>'), '', $data);
+
+    //used global variable start values declaration :
+
+    $record_item_body = false;
+    $non_HTML_tag_to_avoid = array(
+        "SIMPLECHOICE",
+        "CHOICEINTERACTION",
+        "INLINECHOICEINTERACTION",
+        "INLINECHOICE",
+        "SIMPLEMATCHSET",
+        "SIMPLEASSOCIABLECHOICE",
+        "TEXTENTRYINTERACTION",
+        "FEEDBACKINLINE",
+        "MATCHINTERACTION",
+        "ITEMBODY",
+        "BR",
+        "IMG"
+    );
+
+    //this array to detect tag not supported by claroline import in the xml file to warn the user.
+
+    $non_supported_content_in_question = array(
+        "GAPMATCHINTERACTION",
+        "EXTENDEDTEXTINTERACTION",
+        "HOTTEXTINTERACTION",
+        "HOTSPOTINTERACTION",
+        "SELECTPOINTINTERACTION",
+        "GRAPHICORDERINTERACTION",
+        "GRAPHICASSOCIATIONINTERACTION",
+        "GRAPHICGAPMATCHINTERACTION",
+        "POSITIONOBJECTINTERACTION",
+        "SLIDERINTERACTION",
+        "DRAWINGINTERACTION",
+        "UPLOADINTERACTION",
+        "RESPONSECONDITION",
+        "RESPONSEIF"
+    );
+    $question_format_supported = true;
+
+    $xml_parser = xml_parser_create();
+    xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, false);
+    xml_set_element_handler($xml_parser, 'startElement', 'endElement');
+    xml_set_character_data_handler($xml_parser, 'elementData');
+
+    if (!xml_parse($xml_parser, $data, feof($fp))) {
+        // if reading of the xml file in not successfull :
+        // set errorFound, set error msg, break while statement
+        Display :: display_error_message(get_lang('Error reading XML file'));
+
+        return false;
+    }
+
+    //close file
+    fclose($fp);
+    if (!$question_format_supported) {
+        Display :: display_error_message(
+            get_lang(
+                'Unknown question format in file %file',
+                array(
+                    '%file' => $questionFile
+                )
+            )
+        );
+
+        return false;
+    }
+
+    return true;
 }
 
 /**
@@ -263,196 +294,199 @@ function parse_file($exercisePath, $file, $questionFile) {
  * @param unknown_type $attributes
  */
 
-function startElement($parser, $name, $attributes) {
-	global $element_pile;
-	global $exercise_info;
-	global $current_question_ident;
-	global $current_answer_id;
-	global $current_match_set;
-	global $currentAssociableChoice;
-	global $current_question_item_body;
-	global $record_item_body;
-	global $non_HTML_tag_to_avoid;
-	global $current_inlinechoice_id;
-	global $cardinality;
-	global $questionTempDir;
-
-	array_push($element_pile, $name);
-	$current_element = end($element_pile);
-	if (sizeof($element_pile) >= 2)
-		$parent_element = $element_pile[sizeof($element_pile) - 2];
-	else
-		$parent_element = "";
-	if (sizeof($element_pile) >= 3)
-		$grant_parent_element = $element_pile[sizeof($element_pile) - 3];
-	else
-		$grant_parent_element = "";
-
-	if ($record_item_body) {
-
-		if ((!in_array($current_element, $non_HTML_tag_to_avoid))) {
-			$current_question_item_body .= "<" . $name;
-
-			foreach ($attributes as $attribute_name => $attribute_value) {
-				$current_question_item_body .= " " . $attribute_name . "=\"" . $attribute_value . "\"";
-			}
-			$current_question_item_body .= ">";
-		} else {
-			//in case of FIB question, we replace the IMS-QTI tag b y the correct answer between "[" "]",
-			//we first save with claroline tags ,then when the answer will be parsed, the claroline tags will be replaced
-
-			if ($current_element == 'INLINECHOICEINTERACTION') {
-
-				$current_question_item_body .= "**claroline_start**" . $attributes['RESPONSEIDENTIFIER'] . "**claroline_end**";
-			}
-			if ($current_element == 'TEXTENTRYINTERACTION') {
-				$correct_answer_value = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
-				$current_question_item_body .= "[" . $correct_answer_value . "]";
-
-			}
-			if ($current_element == 'BR') {
-				$current_question_item_body .= "<BR/>";
-			}
-		}
-
-	}
-
-	switch ($current_element) {
-		case 'ASSESSMENTITEM' :
-			{
-				//retrieve current question
-
-				$current_question_ident = $attributes['IDENTIFIER'];
-				$exercise_info['question'][$current_question_ident] = array ();
-				$exercise_info['question'][$current_question_ident]['answer'] = array ();
-				$exercise_info['question'][$current_question_ident]['correct_answers'] = array ();
-				$exercise_info['question'][$current_question_ident]['title'] = $attributes['TITLE'];
-				$exercise_info['question'][$current_question_ident]['tempdir'] = $questionTempDir;
-			}
-			break;
-
-		case 'SECTION' :
-			{
-				//retrieve exercise name
-
-				$exercise_info['name'] = $attributes['TITLE'];
-
-			}
-			break;
-
-		case 'RESPONSEDECLARATION' :
-			{
-				//retrieve question type
-
-				if ("multiple" == $attributes['CARDINALITY']) {
-					$exercise_info['question'][$current_question_ident]['type'] = 'MCMA';
-					$cardinality = 'multiple';
-				}
-				if ("single" == $attributes['CARDINALITY']) {
-					$exercise_info['question'][$current_question_ident]['type'] = 'MCUA';
-					$cardinality = 'single';
-				}
-
-				//needed for FIB
-
-				$current_answer_id = $attributes['IDENTIFIER'];
-
-			}
-			break;
-
-		case 'INLINECHOICEINTERACTION' :
-			{
-				$exercise_info['question'][$current_question_ident]['type'] = 'FIB';
-				$exercise_info['question'][$current_question_ident]['subtype'] = 'LISTBOX_FILL';
-				$current_answer_id = $attributes['RESPONSEIDENTIFIER'];
-
-			}
-			break;
-
-		case 'INLINECHOICE' :
-			{
-				$current_inlinechoice_id = $attributes['IDENTIFIER'];
-			}
-			break;
-
-		case 'TEXTENTRYINTERACTION' :
-			{
-				$exercise_info['question'][$current_question_ident]['type'] = 'FIB';
-				$exercise_info['question'][$current_question_ident]['subtype'] = 'TEXTFIELD_FILL';
-				$exercise_info['question'][$current_question_ident]['response_text'] = $current_question_item_body;
-
-				//replace claroline tags
-
-			}
-			break;
-
-		case 'MATCHINTERACTION' :
-			{
-				$exercise_info['question'][$current_question_ident]['type'] = 'MATCHING';
-			}
-			break;
-
-		case 'SIMPLEMATCHSET' :
-			{
-				if (!isset ($current_match_set)) {
-					$current_match_set = 1;
-				} else {
-					$current_match_set++;
-				}
-				$exercise_info['question'][$current_question_ident]['answer'][$current_match_set] = array ();
-			}
-			break;
-
-		case 'SIMPLEASSOCIABLECHOICE' :
-			{
-				$currentAssociableChoice = $attributes['IDENTIFIER'];
-			}
-			break;
-
-			//retrieve answers id for MCUA and MCMA questions
-
-		case 'SIMPLECHOICE' :
-			
+function startElement($parser, $name, $attributes)
+{
+    global $element_pile;
+    global $exercise_info;
+    global $current_question_ident;
+    global $current_answer_id;
+    global $current_match_set;
+    global $currentAssociableChoice;
+    global $current_question_item_body;
+    global $record_item_body;
+    global $non_HTML_tag_to_avoid;
+    global $current_inlinechoice_id;
+    global $cardinality;
+    global $questionTempDir;
+
+    array_push($element_pile, $name);
+    $current_element = end($element_pile);
+    if (sizeof($element_pile) >= 2) {
+        $parent_element = $element_pile[sizeof($element_pile) - 2];
+    } else {
+        $parent_element = "";
+    }
+    if (sizeof($element_pile) >= 3) {
+        $grant_parent_element = $element_pile[sizeof($element_pile) - 3];
+    } else {
+        $grant_parent_element = "";
+    }
+
+    if ($record_item_body) {
+
+        if ((!in_array($current_element, $non_HTML_tag_to_avoid))) {
+            $current_question_item_body .= "<".$name;
+
+            foreach ($attributes as $attribute_name => $attribute_value) {
+                $current_question_item_body .= " ".$attribute_name."=\"".$attribute_value."\"";
+            }
+            $current_question_item_body .= ">";
+        } else {
+            //in case of FIB question, we replace the IMS-QTI tag b y the correct answer between "[" "]",
+            //we first save with claroline tags ,then when the answer will be parsed, the claroline tags will be replaced
+
+            if ($current_element == 'INLINECHOICEINTERACTION') {
+
+                $current_question_item_body .= "**claroline_start**".$attributes['RESPONSEIDENTIFIER']."**claroline_end**";
+            }
+            if ($current_element == 'TEXTENTRYINTERACTION') {
+                $correct_answer_value = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
+                $current_question_item_body .= "[".$correct_answer_value."]";
+
+            }
+            if ($current_element == 'BR') {
+                $current_question_item_body .= "<BR/>";
+            }
+        }
+
+    }
+
+    switch ($current_element) {
+        case 'ASSESSMENTITEM' :
+        {
+            //retrieve current question
+
+            $current_question_ident = $attributes['IDENTIFIER'];
+            $exercise_info['question'][$current_question_ident] = array();
+            $exercise_info['question'][$current_question_ident]['answer'] = array();
+            $exercise_info['question'][$current_question_ident]['correct_answers'] = array();
+            $exercise_info['question'][$current_question_ident]['title'] = $attributes['TITLE'];
+            $exercise_info['question'][$current_question_ident]['tempdir'] = $questionTempDir;
+        }
+            break;
+
+        case 'SECTION' :
+        {
+            //retrieve exercise name
+
+            $exercise_info['name'] = $attributes['TITLE'];
+
+        }
+            break;
+
+        case 'RESPONSEDECLARATION' :
+        {
+            //retrieve question type
+
+            if ("multiple" == $attributes['CARDINALITY']) {
+                $exercise_info['question'][$current_question_ident]['type'] = 'MCMA';
+                $cardinality = 'multiple';
+            }
+            if ("single" == $attributes['CARDINALITY']) {
+                $exercise_info['question'][$current_question_ident]['type'] = 'MCUA';
+                $cardinality = 'single';
+            }
+
+            //needed for FIB
+
+            $current_answer_id = $attributes['IDENTIFIER'];
+
+        }
+            break;
+
+        case 'INLINECHOICEINTERACTION' :
+        {
+            $exercise_info['question'][$current_question_ident]['type'] = 'FIB';
+            $exercise_info['question'][$current_question_ident]['subtype'] = 'LISTBOX_FILL';
+            $current_answer_id = $attributes['RESPONSEIDENTIFIER'];
+
+        }
+            break;
+
+        case 'INLINECHOICE' :
+        {
+            $current_inlinechoice_id = $attributes['IDENTIFIER'];
+        }
+            break;
+
+        case 'TEXTENTRYINTERACTION' :
+        {
+            $exercise_info['question'][$current_question_ident]['type'] = 'FIB';
+            $exercise_info['question'][$current_question_ident]['subtype'] = 'TEXTFIELD_FILL';
+            $exercise_info['question'][$current_question_ident]['response_text'] = $current_question_item_body;
+
+            //replace claroline tags
+
+        }
+            break;
+
+        case 'MATCHINTERACTION' :
+        {
+            $exercise_info['question'][$current_question_ident]['type'] = 'MATCHING';
+        }
+            break;
+
+        case 'SIMPLEMATCHSET' :
+        {
+            if (!isset ($current_match_set)) {
+                $current_match_set = 1;
+            } else {
+                $current_match_set++;
+            }
+            $exercise_info['question'][$current_question_ident]['answer'][$current_match_set] = array();
+        }
+            break;
+
+        case 'SIMPLEASSOCIABLECHOICE' :
+        {
+            $currentAssociableChoice = $attributes['IDENTIFIER'];
+        }
+            break;
+
+        //retrieve answers id for MCUA and MCMA questions
+
+        case 'SIMPLECHOICE' :
+
             $current_answer_id = $attributes['IDENTIFIER'];
             if (!isset($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id])) {
-                $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id] = array ();
+                $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id] = array();
+            }
+
+            break;
+
+        case 'MAPENTRY' :
+        {
+            if ($parent_element == "MAPPING") {
+                $answer_id = $attributes['MAPKEY'];
+
+                if (!isset ($exercise_info['question'][$current_question_ident]['weighting'])) {
+                    $exercise_info['question'][$current_question_ident]['weighting'] = array();
+                }
+                $exercise_info['question'][$current_question_ident]['weighting'][$answer_id] = $attributes['MAPPEDVALUE'];
+            }
+        }
+            break;
+
+        case 'MAPPING' :
+        {
+            if (isset ($attributes['DEFAULTVALUE'])) {
+                $exercise_info['question'][$current_question_ident]['default_weighting'] = $attributes['DEFAULTVALUE'];
             }
-			
-			break;
-
-		case 'MAPENTRY' :
-			{
-				if ($parent_element == "MAPPING") {
-					$answer_id = $attributes['MAPKEY'];
-
-					if (!isset ($exercise_info['question'][$current_question_ident]['weighting'])) {
-						$exercise_info['question'][$current_question_ident]['weighting'] = array ();
-					}
-					$exercise_info['question'][$current_question_ident]['weighting'][$answer_id] = $attributes['MAPPEDVALUE'];
-				}
-			}
-			break;
-
-		case 'MAPPING' :
-			{
-				if (isset ($attributes['DEFAULTVALUE'])) {
-					$exercise_info['question'][$current_question_ident]['default_weighting'] = $attributes['DEFAULTVALUE'];
-				}
-			}
-
-		case 'ITEMBODY' :
-			{
-				$record_item_body = true;
-				$current_question_item_body = '';
-			}
-			break;
-
-		case 'IMG' :
-			{
-				$exercise_info['question'][$current_question_ident]['attached_file_url'] = $attributes['SRC'];
-			}
-			break;
-	}
+        }
+
+        case 'ITEMBODY' :
+        {
+            $record_item_body = true;
+            $current_question_item_body = '';
+        }
+            break;
+
+        case 'IMG' :
+        {
+            $exercise_info['question'][$current_question_ident]['attached_file_url'] = $attributes['SRC'];
+        }
+            break;
+    }
 }
 
 /**
@@ -462,132 +496,150 @@ function startElement($parser, $name, $attributes) {
  * @param $name name of the element
  */
 
-function endElement($parser, $name) {
-	global $element_pile;
-	global $exercise_info;
-	global $current_question_ident;
-	global $record_item_body;
-	global $current_question_item_body;
-	global $non_HTML_tag_to_avoid;
-	global $cardinality;
-
-	$current_element = end($element_pile);
-
-	//treat the record of the full content of itembody tag :
-
-	if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
-		$current_question_item_body .= "</" . $name . ">";
-	}
-
-	switch ($name) {
-		case 'ITEMBODY' :
-			{
-				$record_item_body = false;
-				if ($exercise_info['question'][$current_question_ident]['type'] == 'FIB') {
-					$exercise_info['question'][$current_question_ident]['response_text'] = $current_question_item_body;
-				} else {
-					$exercise_info['question'][$current_question_ident]['statement'] = $current_question_item_body;
-				}
-			}
-			break;
-	}
-	array_pop($element_pile);
+function endElement($parser, $name)
+{
+    global $element_pile;
+    global $exercise_info;
+    global $current_question_ident;
+    global $record_item_body;
+    global $current_question_item_body;
+    global $non_HTML_tag_to_avoid;
+    global $cardinality;
+
+    $current_element = end($element_pile);
+
+    //treat the record of the full content of itembody tag :
+
+    if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
+        $current_question_item_body .= "</".$name.">";
+    }
+
+    switch ($name) {
+        case 'ITEMBODY' :
+        {
+            $record_item_body = false;
+            if ($exercise_info['question'][$current_question_ident]['type'] == 'FIB') {
+                $exercise_info['question'][$current_question_ident]['response_text'] = $current_question_item_body;
+            } else {
+                $exercise_info['question'][$current_question_ident]['statement'] = $current_question_item_body;
+            }
+        }
+            break;
+    }
+    array_pop($element_pile);
 
 }
 
-function elementData($parser, $data) {
-
-	global $element_pile;
-	global $exercise_info;
-	global $current_question_ident;
-	global $current_answer_id;
-	global $current_match_set;
-	global $currentAssociableChoice;
-	global $current_question_item_body;
-	global $record_item_body;
-	global $non_HTML_tag_to_avoid;
-	global $current_inlinechoice_id;
-	global $cardinality;
-
-	$current_element = end($element_pile);
-	if (sizeof($element_pile) >= 2)
-		$parent_element = $element_pile[sizeof($element_pile) - 2];
-	else
-		$parent_element = "";
-	if (sizeof($element_pile) >= 3)
-		$grant_parent_element = $element_pile[sizeof($element_pile) - 3];
-	else
-		$grant_parent_element = "";
-
-	//treat the record of the full content of itembody tag (needed for question statment and/or FIB text:
-
-	if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
-		$current_question_item_body .= $data;
-	}
-    
-	switch ($current_element) {
-		case 'SIMPLECHOICE' :
-			
-				if (!isset ($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'])) {
-					$exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'] = trim($data);
-				} else {
-					$exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'] .= ''.trim($data);
-				}    		
-			break;
-
-		case 'FEEDBACKINLINE' :
-			{
-				if (!isset ($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'])) {
-					$exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'] = trim($data);
-				} else {
-					$exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'] .= ' ' . trim($data);
-				}
-			}
-			break;
-
-		case 'SIMPLEASSOCIABLECHOICE' :
-			{
-				$exercise_info['question'][$current_question_ident]['answer'][$current_match_set][$currentAssociableChoice] = trim($data);
-			}
-			break;
-
-		case 'VALUE' :
-			{
-				if ($parent_element == "CORRECTRESPONSE") {
-					if ($cardinality == "single") {
-						$exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id] = $data;
-					} else {
-						$exercise_info['question'][$current_question_ident]['correct_answers'][] = $data;
-					}
-				}
-			}
-			break;
-
-		case 'ITEMBODY' :
-			{
-				$current_question_item_body .= $data;
-
-			}
-			break;
-
-		case 'INLINECHOICE' :
-			{
-
-				// if this is the right answer, then we must replace the claroline tags in the FIB text bye the answer between "[" and "]" :
-
-				$answer_identifier = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
-
-				if ($current_inlinechoice_id == $answer_identifier) {
-
-					$current_question_item_body = str_replace("**claroline_start**" . $current_answer_id . "**claroline_end**", "[" . $data . "]", $current_question_item_body);
-				} else // save wrong answers in an array
-					{
-					if (!isset ($exercise_info['question'][$current_question_ident]['wrong_answers'])) {
-						$exercise_info['question'][$current_question_ident]['wrong_answers'] = array ();
-					}
-					$exercise_info['question'][$current_question_ident]['wrong_answers'][] = $data;
-				}
-			}
-			break;
-	}
+function elementData($parser, $data)
+{
+
+    global $element_pile;
+    global $exercise_info;
+    global $current_question_ident;
+    global $current_answer_id;
+    global $current_match_set;
+    global $currentAssociableChoice;
+    global $current_question_item_body;
+    global $record_item_body;
+    global $non_HTML_tag_to_avoid;
+    global $current_inlinechoice_id;
+    global $cardinality;
+
+    $current_element = end($element_pile);
+    if (sizeof($element_pile) >= 2) {
+        $parent_element = $element_pile[sizeof($element_pile) - 2];
+    } else {
+        $parent_element = "";
+    }
+    if (sizeof($element_pile) >= 3) {
+        $grant_parent_element = $element_pile[sizeof($element_pile) - 3];
+    } else {
+        $grant_parent_element = "";
+    }
+
+    //treat the record of the full content of itembody tag (needed for question statment and/or FIB text:
+
+    if ($record_item_body && (!in_array($current_element, $non_HTML_tag_to_avoid))) {
+        $current_question_item_body .= $data;
+    }
+
+    switch ($current_element) {
+        case 'SIMPLECHOICE' :
+
+            if (!isset ($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'])) {
+                $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'] = trim(
+                    $data
+                );
+            } else {
+                $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['value'] .= ''.trim(
+                    $data
+                );
+            }
+            break;
+
+        case 'FEEDBACKINLINE' :
+        {
+            if (!isset ($exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'])) {
+                $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'] = trim(
+                    $data
+                );
+            } else {
+                $exercise_info['question'][$current_question_ident]['answer'][$current_answer_id]['feedback'] .= ' '.trim(
+                    $data
+                );
+            }
+        }
+            break;
+
+        case 'SIMPLEASSOCIABLECHOICE' :
+        {
+            $exercise_info['question'][$current_question_ident]['answer'][$current_match_set][$currentAssociableChoice] = trim(
+                $data
+            );
+        }
+            break;
+
+        case 'VALUE' :
+        {
+            if ($parent_element == "CORRECTRESPONSE") {
+                if ($cardinality == "single") {
+                    $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id] = $data;
+                } else {
+                    $exercise_info['question'][$current_question_ident]['correct_answers'][] = $data;
+                }
+            }
+        }
+            break;
+
+        case 'ITEMBODY' :
+        {
+            $current_question_item_body .= $data;
+
+        }
+            break;
+
+        case 'INLINECHOICE' :
+        {
+
+            // if this is the right answer, then we must replace the claroline tags in the FIB text bye the answer between "[" and "]" :
+
+            $answer_identifier = $exercise_info['question'][$current_question_ident]['correct_answers'][$current_answer_id];
+
+            if ($current_inlinechoice_id == $answer_identifier) {
+
+                $current_question_item_body = str_replace(
+                    "**claroline_start**".$current_answer_id."**claroline_end**",
+                    "[".$data."]",
+                    $current_question_item_body
+                );
+            } else // save wrong answers in an array
+            {
+                if (!isset ($exercise_info['question'][$current_question_ident]['wrong_answers'])) {
+                    $exercise_info['question'][$current_question_ident]['wrong_answers'] = array();
+                }
+                $exercise_info['question'][$current_question_ident]['wrong_answers'][] = $data;
+            }
+        }
+            break;
+    }
 }

+ 40 - 35
main/exercice/export/exercise_import.php

@@ -13,13 +13,12 @@ require '../../inc/global.inc.php';
 
 //SECURITY CHECK
 
-if ( api_is_platform_admin() ) api_not_allowed();
+if (api_is_platform_admin()) {
+    api_not_allowed();
+}
 
 //DECLARE NEEDED LIBRARIES
 
-require_once api_get_path(LIBRARY_PATH) . 'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
-
 require_once 'exercise_import.inc.php';
 include_once '../exercise.class.php';
 include_once '../question.class.php';
@@ -27,8 +26,8 @@ include_once 'qti/qti_classes.php';
 
 //SQL table name
 
-$tbl_exercise              = Database::get_course_table(TABLE_QUIZ_TEST);
-$tbl_question              = Database::get_course_table(TABLE_QUIZ_QUESTION);
+$tbl_exercise = Database::get_course_table(TABLE_QUIZ_TEST);
+$tbl_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
 $tbl_rel_exercise_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
 
 // tool libraries
@@ -41,32 +40,33 @@ $nameTools = get_lang('ImportExercise');
 
 //bredcrump
 
-$interbredcrump[]= array ('url' => '../exercice.php','name' => get_lang('Exercises'));
+$interbredcrump[] = array('url' => '../exercice.php', 'name' => get_lang('Exercises'));
 
 //----------------------------------
 // EXECUTE COMMAND
 //----------------------------------
 
-$cmd = (isset($_REQUEST['cmd'])? $_REQUEST['cmd'] : 'show_import');
+$cmd = (isset($_REQUEST['cmd']) ? $_REQUEST['cmd'] : 'show_import');
 
-switch ( $cmd )
-{
+switch ($cmd) {
     case 'show_import' :
     {
         $display = '<p>'
-        .            get_lang('Imported exercises must consist of a zip or an XML file (IMS-QTI) and be compatible with your Claroline version.') . '<br>'
-        .            '</p>'
-        .            '<form enctype="multipart/form-data" action="" method="post">'
-        .            '<input name="cmd" type="hidden" value="import" />'
-        .            '<input name="uploadedExercise" type="file" /><br><br>'
-        .            get_lang('Import exercise') . ' : '
-        .            '<input value="' . get_lang('Ok') . '" type="submit" /> '
-        .            claro_html_button( $_SERVER['PHP_SELF'], get_lang('Cancel'))
-        .            '<br><br>'
-        .            '<small>' . get_lang('Max file size') . ' :  2&nbsp;MB</small>'
-        .            '</form>';
+            .get_lang(
+                'Imported exercises must consist of a zip or an XML file (IMS-QTI) and be compatible with your Claroline version.'
+            ).'<br>'
+            .'</p>'
+            .'<form enctype="multipart/form-data" action="" method="post">'
+            .'<input name="cmd" type="hidden" value="import" />'
+            .'<input name="uploadedExercise" type="file" /><br><br>'
+            .get_lang('Import exercise').' : '
+            .'<input value="'.get_lang('Ok').'" type="submit" /> '
+            .claro_html_button($_SERVER['PHP_SELF'], get_lang('Cancel'))
+            .'<br><br>'
+            .'<small>'.get_lang('Max file size').' :  2&nbsp;MB</small>'
+            .'</form>';
     }
-    break;
+        break;
 
     case 'import' :
     {
@@ -78,13 +78,12 @@ switch ( $cmd )
 
         $dialogBox = '';
 
-        foreach ($result_log as $log)
-        {
-            $dialogBox .= $log . '<br>';
+        foreach ($result_log as $log) {
+            $dialogBox .= $log.'<br>';
         }
 
     }
-    break;
+        break;
 }
 
 //----------------------------------
@@ -97,30 +96,36 @@ switch ( $cmd )
 // DISPLAY
 //----------------------------------
 
-include api_get_path(INCLUDE_PATH) . '/header.inc.php';
+include api_get_path(INCLUDE_PATH).'/header.inc.php';
 
 //display title
 
 
 // Tool introduction
 // TODO: These settings to be checked when it is possible.
-Display::display_introduction_section(TOOL_QUIZ, array(
-		'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
-		'CreateDocumentDir' => '../../../courses/'.api_get_course_path().'/document/',
-		'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/'
-	)
+Display::display_introduction_section(
+    TOOL_QUIZ,
+    array(
+        'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
+        'CreateDocumentDir' => '../../../courses/'.api_get_course_path().'/document/',
+        'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/'
+    )
 );
 
 
 //Display Forms or dialog box(if needed)
 
-if ( isset($dialogBox) ) echo Display::display_normal_message($dialogBox,false);
+if (isset($dialogBox)) {
+    echo Display::display_normal_message($dialogBox, false);
+}
 
 //display content
 
-if (isset($display) ) echo $display;
+if (isset($display)) {
+    echo $display;
+}
 
 //footer display
 
-include api_get_path(INCLUDE_PATH) . '/footer.inc.php';
+include api_get_path(INCLUDE_PATH).'/footer.inc.php';
 ?>

+ 54 - 49
main/exercice/feedback.php

@@ -2,11 +2,11 @@
 /* For licensing terms, see /license.txt */
 // Note by Ivan Tcholakov, 14-JUL-2009: I can't see where this file is used. Is it obsolete?
 /**
-*	Feedback
-*	@package chamilo.exercise
-* 	@author
-* 	@version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
-*/
+ *    Feedback
+ * @package chamilo.exercise
+ * @author
+ * @version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $
+ */
 /**
  * Code
  */
@@ -17,65 +17,70 @@ include('answer.class.php');
 include('exercise.lib.php');
 
 // name of the language file that needs to be included
-$language_file='exercice';
+$language_file = 'exercice';
 
 include("../inc/global.inc.php");
-$this_section=SECTION_COURSES;
+$this_section = SECTION_COURSES;
 
-include_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
 include_once(api_get_path(LIBRARY_PATH).'document.lib.php');
-include_once(api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-$nameTools=get_lang('ExerciseManagement');
+$nameTools = get_lang('ExerciseManagement');
 
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
+if (isset($_SESSION['gradebook'])) {
+    $gradebook = $_SESSION['gradebook'];
 }
 
-if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('ToolGradebook')
-		);
+if (!empty($gradebook) && $gradebook == 'view') {
+    $interbreadcrumb[] = array(
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+        'name' => get_lang('ToolGradebook')
+    );
 }
 
-$interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
-Display::display_header($nameTools,"Exercise");
+$interbreadcrumb[] = array("url" => "exercice.php", "name" => get_lang('Exercices'));
+Display::display_header($nameTools, "Exercise");
 ?>
 <table border="0" align="center" cellpadding="2" cellspacing="2" width="100%">
-<h4>
-  <?php echo "Add Feedback"; ?>
-</h4>
-<?php
-	$id = $_REQUEST['question'];
-	$objQuestionTmp = Question::read($id);
-	echo "<tr><td><b>".get_lang('Question')." : </b>";
-	echo $objQuestionTmp->selectTitle();
-	echo "</td></tr>";
-	echo " <br><tr><td><b><br>".get_lang('Answer')." : </b></td></tr>";
-	$objAnswerTmp=new Answer($id);
-	$num = $objAnswerTmp->selectNbrAnswers();
-	$objAnswerTmp->read();
-	for($i=1;$i<=$num;$i++)
-	{
-	echo "<tr><td width='10%'> ";
-	$ans =  $objAnswerTmp->answer[$i];
+    <h4>
+        <?php echo "Add Feedback"; ?>
+    </h4>
+    <?php
+    $id = $_REQUEST['question'];
+    $objQuestionTmp = Question::read($id);
+    echo "<tr><td><b>".get_lang('Question')." : </b>";
+    echo $objQuestionTmp->selectTitle();
+    echo "</td></tr>";
+    echo " <br><tr><td><b><br>".get_lang('Answer')." : </b></td></tr>";
+    $objAnswerTmp = new Answer($id);
+    $num = $objAnswerTmp->selectNbrAnswers();
+    $objAnswerTmp->read();
+    for ($i = 1; $i <= $num; $i++) {
+        echo "<tr><td width='10%'> ";
+        $ans = $objAnswerTmp->answer[$i];
 
-	$form = new FormValidator('feedbackform','post',api_get_self()."?".api_get_cidreq()."&modifyQuestion=".$modifyQuestion."&newQuestion=".$newQuestion);
-	$obj_registration_form = new HTML_QuickForm('frmRegistration', 'POST');
-	$renderer =& $obj_registration_form->defaultRenderer();
-	$renderer->setElementTemplate(
-'<tr>
+        $form = new FormValidator('feedbackform', 'post', api_get_self()."?".api_get_cidreq(
+        )."&modifyQuestion=".$modifyQuestion."&newQuestion=".$newQuestion);
+        $obj_registration_form = new HTML_QuickForm('frmRegistration', 'POST');
+        $renderer =& $obj_registration_form->defaultRenderer();
+        $renderer->setElementTemplate(
+            '<tr>
 	<td align="left" style="" valign="top" width=30%>{label}
 		<!-- BEGIN required --><span style="color: #ff0000">*</span><!-- END required -->
 	</td>
 	<td align="left" width=70%>{element}
 		<!-- BEGIN error --><br /><span style="color: #ff0000;font-size:10px">{error}</span><!-- END error -->
 	</td>
-</tr>');
-	$form->add_html_editor('Feedback', $i.'.'.$ans, false, false, array('ToolbarSet' => 'TestAnswerFeedback', 'Width' => '600', 'Height' => '200'));
-	$form->display();
-	echo "</td>";
-	}?>
-	<form name="frm" action="javascript: void(0);" method="post">
-	 Click Ok to finish <input  type="submit" value="Ok" />
-	</form>
+</tr>'
+        );
+        $form->add_html_editor(
+            'Feedback',
+            $i.'.'.$ans,
+            false,
+            false,
+            array('ToolbarSet' => 'TestAnswerFeedback', 'Width' => '600', 'Height' => '200')
+        );
+        $form->display();
+        echo "</td>";
+    }?>
+    <form name="frm" action="javascript: void(0);" method="post">
+        Click Ok to finish <input type="submit" value="Ok"/>
+    </form>

+ 64 - 35
main/exercice/hotpotatoes.php

@@ -9,15 +9,12 @@
  * Code
  */
 // Name of the language file that needs to be included.
-$language_file ='exercice';
+$language_file = 'exercice';
 
 // 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).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
 require_once 'hotpotatoes.lib.php';
 
 // Section (for the tabs).
@@ -34,9 +31,9 @@ if (isset($_SESSION['gradebook'])) {
 
 if (!empty($gradebook) && $gradebook == 'view') {
     $interbreadcrumb[] = array(
-            'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-            'name' => get_lang('ToolGradebook')
-        );
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+        'name' => get_lang('ToolGradebook')
+    );
 }
 // The breadcrumbs.
 $interbreadcrumb[] = array('url' => './exercice.php', 'name' => get_lang('Exercices'));
@@ -44,21 +41,21 @@ $interbreadcrumb[] = array('url' => './exercice.php', 'name' => get_lang('Exerci
 $is_allowedToEdit = api_is_allowed_to_edit(null, true);
 
 // Database table definitions.
-$dbTable        = Database::get_course_table(TABLE_DOCUMENT);
+$dbTable = Database::get_course_table(TABLE_DOCUMENT);
 $course_id = api_get_course_int_id();
 
 // Setting some variables.
 $document_sys_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
 $uploadPath = '/HotPotatoes_files';
-$finish         = (!empty($_POST['finish']) ? $_POST['finish'] : 0);
-$imgcount       = (!empty($_POST['imgcount']) ? $_POST['imgcount'] : null);
-$fld            = (!empty($_POST['fld']) ? $_POST['fld'] : null);
+$finish = (!empty($_POST['finish']) ? $_POST['finish'] : 0);
+$imgcount = (!empty($_POST['imgcount']) ? $_POST['imgcount'] : null);
+$fld = (!empty($_POST['fld']) ? $_POST['fld'] : null);
 
 // If user is allowed to edit...
 if (api_is_allowed_to_edit(null, true)) {
     if (hotpotatoes_init($document_sys_path.$uploadPath)) {
         // If the directory doesn't exist, create the "HotPotatoes" directory.
-        $doc_id = add_document($_course, '/HotPotatoes_files', 'folder', 0, get_lang('HotPotatoesFiles'));
+        $doc_id = FileManager::add_document($_course, '/HotPotatoes_files', 'folder', 0, get_lang('HotPotatoesFiles'));
         // Update properties in dbase (in any case).
         api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
         // Make invisible (in any case) - why?
@@ -69,7 +66,8 @@ if (api_is_allowed_to_edit(null, true)) {
 /** Display */
 $nameTools = get_lang('HotPotatoesTests');
 
-$form = new FormValidator('hotpotatoes', 'post', api_get_self()."?".api_get_cidreq(), null, array('enctype' => 'multipart/form-data'));    
+$form = new FormValidator('hotpotatoes', 'post', api_get_self()."?".api_get_cidreq(
+), null, array('enctype' => 'multipart/form-data'));
 $form->addElement('header', $nameTools);
 $form->addElement('hidden', 'uploadPath');
 $form->addElement('hidden', 'fld', $fld);
@@ -83,7 +81,7 @@ $form->addElement('advanced_settings', Display::return_icon('hotpotatoes.jpg', g
 $label = get_lang('DownloadImg').' : ';
 if ($finish == 0) {
     $label = get_lang('DownloadFile').' : ';
-}    
+}
 
 $form->addElement('file', 'userFile', $label);
 $form->addElement('button', 'submit', get_lang('SendFile'));
@@ -91,17 +89,21 @@ $form->addElement('button', 'submit', get_lang('SendFile'));
 
 // If finish is set; it's because the user came from this script in the first place (displaying hidden "finish" field).
 if ((api_is_allowed_to_edit(null, true)) && (($finish == 0) || ($finish == 2))) {
-    
+
 
     // Moved this down here as the upload handling functions give output.
     if ($form->validate()) {
 
         //initialise $finish
-        if (!isset($finish)) { $finish = 0; }
+        if (!isset($finish)) {
+            $finish = 0;
+        }
 
         //if the size is not defined, it's probably because there has been an error or no file was submitted
         if (!$_FILES['userFile']['size']) {
-            $dialogBox .= get_lang('SendFileError').'<br />'.get_lang('Notice').' : '.get_lang('MaxFileSize').' '.ini_get('upload_max_filesize');
+            $dialogBox .= get_lang('SendFileError').'<br />'.get_lang('Notice').' : '.get_lang(
+                'MaxFileSize'
+            ).' '.ini_get('upload_max_filesize');
         } else {
             $unzip = 0;
             if (preg_match('/\.zip$/i', $_FILES['userFile']['name'])) {
@@ -114,25 +116,37 @@ if ((api_is_allowed_to_edit(null, true)) && (($finish == 0) || ($finish == 2)))
                 $filename = replace_dangerous_char(trim($_FILES['userFile']['name']), 'strict');
                 $fld = GenerateHpFolder($document_sys_path.$uploadPath.'/');
 
-                //$doc_id = add_document($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);
+                //$doc_id = FileManager::add_document($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);
                 //api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
                 @mkdir($document_sys_path.$uploadPath.'/'.$fld, api_get_permissions_for_new_directories());
-                $doc_id = add_document($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);                    
+                $doc_id = FileManager::add_document($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);
                 api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
             } else {
                 // It is not the first step... get the filename directly from the system params.
                 $filename = $_FILES['userFile']['name'];
             }
 
-            /*if (treat_uploaded_file($_FILES['userFile'], $document_sys_path, $uploadPath."/".$fld, $max_filled_space, $unzip))*/
             $allow_output_on_success = false;
-            if (handle_uploaded_document($_course, $_FILES['userFile'], $document_sys_path, $uploadPath.'/'.$fld, api_get_user_id(), null, null, $unzip, '', $allow_output_on_success)) {
+            if (FileManager::handle_uploaded_document(
+                $_course,
+                $_FILES['userFile'],
+                $document_sys_path,
+                $uploadPath.'/'.$fld,
+                api_get_user_id(),
+                null,
+                null,
+                $unzip,
+                '',
+                $allow_output_on_success
+            )
+            ) {
 
                 if ($finish == 2) {
                     $imgparams = $_POST['imgparams'];
                     $checked = CheckImageName($imgparams, $filename);
-                    if ($checked) { $imgcount = $imgcount-1; }
-                    else {
+                    if ($checked) {
+                        $imgcount = $imgcount - 1;
+                    } else {
                         $dialogBox .= $filename.' '.get_lang('NameNotEqual');
                         FileManager::my_delete($document_sys_path.$uploadPath.'/'.$fld.'/'.$filename);
                         FileManager::update_db_info('delete', $uploadPath.'/'.$fld.'/'.$filename);
@@ -147,14 +161,23 @@ if ((api_is_allowed_to_edit(null, true)) && (($finish == 0) || ($finish == 2)))
                         // Get number and name of images from the files contents.
                         GetImgParams('/'.$filename, $document_sys_path.$uploadPath.'/'.$fld, $imgparams, $imgcount);
                         if ($imgcount == 0) // There is no img link, so finish the upload process.
-                            { $finish = 1; }
-                        else // There is still one or more img missing.
-                            { $dialogBox .= get_lang('DownloadEnd'); }
+                        {
+                            $finish = 1;
+                        } else // There is still one or more img missing.
+                        {
+                            $dialogBox .= get_lang('DownloadEnd');
+                        }
                     }
                 }
 
-                $title = @htmlspecialchars(GetQuizName($filename, $document_sys_path.$uploadPath.'/'.$fld.'/'), ENT_COMPAT, api_get_system_encoding());
-                $query = "UPDATE $dbTable SET comment='".Database::escape_string($title)."' WHERE c_id = $course_id AND path=\"".$uploadPath."/".$fld."/".$filename."\"";
+                $title = @htmlspecialchars(
+                    GetQuizName($filename, $document_sys_path.$uploadPath.'/'.$fld.'/'),
+                    ENT_COMPAT,
+                    api_get_system_encoding()
+                );
+                $query = "UPDATE $dbTable SET comment='".Database::escape_string(
+                    $title
+                )."' WHERE c_id = $course_id AND path=\"".$uploadPath."/".$fld."/".$filename."\"";
                 Database::query($query);
                 api_item_property_update($_course, TOOL_QUIZ, $id, 'QuizAdded', api_get_user_id());
 
@@ -163,16 +186,17 @@ if ((api_is_allowed_to_edit(null, true)) && (($finish == 0) || ($finish == 2)))
                     // delete?
                     //$dialogBox .= get_lang('NoImg');
                 }
-                $finish = 0;    // error
+                $finish = 0; // error
                 if (api_failure::get_last_failure() == 'not_enough_space') {
                     $dialogBox .= get_lang('NoSpace');
                 } elseif (api_failure::get_last_failure() == 'php_file_in_zip_file') {
                     $dialogBox .= get_lang('ZipNoPhp');
                 }
             }
-        }        
+        }
     }
-    if ($finish == 1) { /** ok -> send to main exercises page */
+    if ($finish == 1) {
+        /** ok -> send to main exercises page */
         header('Location: exercice.php?'.api_get_cidreq());
         exit;
     }
@@ -180,10 +204,15 @@ if ((api_is_allowed_to_edit(null, true)) && (($finish == 0) || ($finish == 2)))
     Display::display_header($nameTools, get_lang('Exercise'));
 
     echo '<div class="actions">';
-    echo '<a href="exercice.php?show=test">'.Display :: return_icon('back.png', get_lang('BackToExercisesList'),'',ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="exercice.php?show=test">'.Display :: return_icon(
+        'back.png',
+        get_lang('BackToExercisesList'),
+        '',
+        ICON_SIZE_MEDIUM
+    ).'</a>';
     echo '</div>';
 
-    if ($finish==2) { // If we are in the img upload process.
+    if ($finish == 2) { // If we are in the img upload process.
         $dialogBox .= get_lang('ImgNote_st').$imgcount.get_lang('ImgNote_en').'<br />';
         while (list($key, $string) = each($imgparams)) {
             $dialogBox .= $string.'; ';
@@ -193,8 +222,8 @@ if ((api_is_allowed_to_edit(null, true)) && (($finish == 0) || ($finish == 2)))
     if ($dialogBox) {
         Display::display_normal_message($dialogBox, false);
     }
-    
-    $form->display();    
+
+    $form->display();
 }
 // Display the footer.
 Display::display_footer();

+ 151 - 109
main/exercice/hotpotatoes_exercise_report.php

@@ -1,9 +1,9 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- *	Exercise list: This script shows the list of exercises for administrators and students.
- *	@package chamilo.exercise
- *	@author hubert.borderiou
+ *    Exercise list: This script shows the list of exercises for administrators and students.
+ * @package chamilo.exercise
+ * @author hubert.borderiou
  *
  */
 /**
@@ -30,28 +30,26 @@ require_once 'exercise.class.php';
 require_once 'exercise.lib.php';
 require_once 'question.class.php';
 require_once 'answer.class.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once 'hotpotatoes.lib.php';
 
 // need functions of statsutils lib to display previous exercices scores
-require_once api_get_path(LIBRARY_PATH) . 'statsUtils.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php';
 
 // document path
-$documentPath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . "/document";
+$documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
 
 /*	Constants and variables */
-$is_allowedToEdit           = api_is_allowed_to_edit(null, true) || api_is_drh();
-$is_tutor                   = api_is_allowed_to_edit(true);
+$is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_drh();
+$is_tutor = api_is_allowed_to_edit(true);
 
-$TBL_QUESTIONS              = Database :: get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_TRACK_EXERCICES        = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$TBL_TRACK_HOTPOTATOES_EXERCICES        = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
-$TBL_LP_ITEM_VIEW           = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+$TBL_QUESTIONS = Database :: get_course_table(TABLE_QUIZ_QUESTION);
+$TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_HOTPOTATOES_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+$TBL_LP_ITEM_VIEW = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
 
-$course_id            = api_get_course_int_id();
-$hotpotatoes_path     = isset($_REQUEST['path']) ? $_REQUEST['path'] : null;
-$filter_user          = isset($_REQUEST['filter_by_user']) ? intval($_REQUEST['filter_by_user']) : null;
+$course_id = api_get_course_int_id();
+$hotpotatoes_path = isset($_REQUEST['path']) ? $_REQUEST['path'] : null;
+$filter_user = isset($_REQUEST['filter_by_user']) ? intval($_REQUEST['filter_by_user']) : null;
 
 $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE);
 
@@ -61,7 +59,7 @@ if (empty($hotpotatoes_path)) {
 }
 
 if (!$is_allowedToEdit) {
-   // api_not_allowed();
+    // api_not_allowed();
 }
 
 if (!empty($_REQUEST['path'])) {
@@ -69,8 +67,6 @@ if (!empty($_REQUEST['path'])) {
 }
 
 
-
-
 if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
     if (api_is_platform_admin() || api_is_course_admin() || api_is_course_tutor() || api_is_course_coach()) {
         $load_extra_data = false;
@@ -88,9 +84,9 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
 //                break;
 //            case 'csv' :
 //            default :
-                $export = new HotpotatoesExerciseResult();
-                $export->exportCompleteReportCSV($documentPath, $hotpotatoes_path);
-                exit;
+        $export = new HotpotatoesExerciseResult();
+        $export->exportCompleteReportCSV($documentPath, $hotpotatoes_path);
+        exit;
 //                break;
 //        }
     } else {
@@ -215,11 +211,23 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
 if ($is_allowedToEdit && $origin != 'learnpath') {
     // the form
     if (api_is_platform_admin() || api_is_course_admin() || api_is_course_tutor() || api_is_course_coach()) {
-        $actions .= '<a href="admin.php?exerciseId='.intval($_GET['exerciseId']).'">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
-        $actions .= '<a id="export_opener" href="'.api_get_self().'?export_report=1&path='.Security::remove_XSS($hotpotatoes_path).' ">'.Display::return_icon('save.png',   get_lang('Export'),'',ICON_SIZE_MEDIUM).'</a>';
+        $actions .= '<a href="admin.php?exerciseId='.intval($_GET['exerciseId']).'">'.Display :: return_icon(
+            'back.png',
+            get_lang('GoBackToQuestionList'),
+            '',
+            ICON_SIZE_MEDIUM
+        ).'</a>';
+        $actions .= '<a id="export_opener" href="'.api_get_self().'?export_report=1&path='.Security::remove_XSS(
+            $hotpotatoes_path
+        ).' ">'.Display::return_icon('save.png', get_lang('Export'), '', ICON_SIZE_MEDIUM).'</a>';
     }
 } else {
-    $actions .= '<a href="exercice.php">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
+    $actions .= '<a href="exercice.php">'.Display :: return_icon(
+        'back.png',
+        get_lang('GoBackToQuestionList'),
+        '',
+        ICON_SIZE_MEDIUM
+    ).'</a>';
 }
 
 //Deleting an attempt
@@ -237,13 +245,13 @@ if ($is_allowedToEdit && $origin != 'learnpath') {
 
 if ($is_allowedToEdit || $is_tutor) {
     $nameTools = get_lang('StudentScore');
-    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
+    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook", "name" => get_lang('Exercices'));
     $objExerciseTmp = new Exercise();
     if ($objExerciseTmp->read($exercise_id)) {
         $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$exercise_id, "name" => $objExerciseTmp->name);
     }
 } else {
-    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
+    $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook", "name" => get_lang('Exercices'));
     $objExerciseTmp = new Exercise();
     if ($objExerciseTmp->read($exercise_id)) {
         $nameTools = get_lang('Results').': '.$objExerciseTmp->name;
@@ -252,9 +260,9 @@ if ($is_allowedToEdit || $is_tutor) {
 
 Display :: display_header($nameTools);
 
-$actions = Display::div($actions, array('class'=> 'actions'));
+$actions = Display::div($actions, array('class' => 'actions'));
 
-$extra =  '<script type="text/javascript">
+$extra = '<script type="text/javascript">
     $(document).ready(function() {
 
         $( "#dialog:ui-dialog" ).dialog( "destroy" );
@@ -289,19 +297,29 @@ $extra =  '<script type="text/javascript">
 
 $extra .= '<div id="dialog-confirm" title="'.get_lang("ConfirmYourChoice").'">';
 $form = new FormValidator('report', 'post', null, null, array('class' => 'form-vertical'));
-$form->addElement('radio', 'export_format', null, get_lang('ExportAsCSV'), 'csv', array('id' => 'export_format_csv_label'));
+$form->addElement(
+    'radio',
+    'export_format',
+    null,
+    get_lang('ExportAsCSV'),
+    'csv',
+    array('id' => 'export_format_csv_label')
+);
 //$form->addElement('radio', 'export_format', null, get_lang('ExportAsXLS'), 'xls', array('id' => 'export_format_xls_label'));
 //$form->addElement('checkbox', 'load_extra_data', null, get_lang('LoadExtraData'), '0', array('id' => 'export_format_xls_label'));
 $form->setDefaults(array('export_format' => 'csv'));
 $extra .= $form->return_form();
 $extra .= '</div>';
 
-if ($is_allowedToEdit)
+if ($is_allowedToEdit) {
     echo $extra;
+}
 
 echo $actions;
 
-$url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_hotpotatoes_exercise_results&path='.$hotpotatoes_path.'&filter_by_user='.$filter_user;
+$url = api_get_path(
+    WEB_AJAX_PATH
+).'model.ajax.php?a=get_hotpotatoes_exercise_results&path='.$hotpotatoes_path.'&filter_by_user='.$filter_user;
 
 //$activeurl = '?sidx=session_active';
 $action_links = '';
@@ -309,7 +327,7 @@ $action_links = '';
 //Generating group list
 
 $group_list = GroupManager::get_group_list();
-$group_parameters = array('group_all:'.get_lang('All'),'group_none:'.get_lang('None'));
+$group_parameters = array('group_all:'.get_lang('All'), 'group_none:'.get_lang('None'));
 
 foreach ($group_list as $group) {
     $group_parameters[] = $group['id'].':'.$group['name'];
@@ -320,27 +338,48 @@ if (!empty($group_parameters)) {
 
 if ($is_allowedToEdit || $is_tutor) {
 
-	//The order is important you need to check the the $column variable in the model.ajax.php file
-	$columns        = array(get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'),
-                        get_lang('Group'), get_lang('StartDate'),  get_lang('Score'),  get_lang('Actions'));
-
-  //Column config
-  // @todo fix search firstname/lastname that doesn't work. rmove search for the moment
-	$column_model   = array(
-                        array('name'=>'firstname',      'index'=>'firstname',		'width'=>'50',   'align'=>'left', 'search' => 'false'),
-                        array('name'=>'lastname',		    'index'=>'lastname',		'width'=>'50',   'align'=>'left', 'formatter'=>'action_formatter', 'search' => 'false'),
-                        array('name'=>'login',          'hidden'=>'true',       'index'=>'username',        'width'=>'40',   'align'=>'left', 'search' => 'false'),
-                        array('name'=>'group_name',		  'index'=>'group_id',    'width'=>'40',   'align'=>'left', 'search' => 'false'),
-            						array('name'=>'exe_date',		    'index'=>'exe_date',		'width'=>'60',   'align'=>'left', 'search' => 'false'),
-            						array('name'=>'score',			    'index'=>'exe_result',	'width'=>'50',   'align'=>'left', 'search' => 'false'),
-            						array('name'=>'actions',        'index'=>'actions',     'width'=>'60',  'align'=>'left', 'search' => 'false')
-                       );
+    //The order is important you need to check the the $column variable in the model.ajax.php file
+    $columns = array(
+        get_lang('FirstName'),
+        get_lang('LastName'),
+        get_lang('LoginName'),
+        get_lang('Group'),
+        get_lang('StartDate'),
+        get_lang('Score'),
+        get_lang('Actions')
+    );
+
+    //Column config
+    // @todo fix search firstname/lastname that doesn't work. rmove search for the moment
+    $column_model = array(
+        array('name' => 'firstname', 'index' => 'firstname', 'width' => '50', 'align' => 'left', 'search' => 'false'),
+        array(
+            'name' => 'lastname',
+            'index' => 'lastname',
+            'width' => '50',
+            'align' => 'left',
+            'formatter' => 'action_formatter',
+            'search' => 'false'
+        ),
+        array(
+            'name' => 'login',
+            'hidden' => 'true',
+            'index' => 'username',
+            'width' => '40',
+            'align' => 'left',
+            'search' => 'false'
+        ),
+        array('name' => 'group_name', 'index' => 'group_id', 'width' => '40', 'align' => 'left', 'search' => 'false'),
+        array('name' => 'exe_date', 'index' => 'exe_date', 'width' => '60', 'align' => 'left', 'search' => 'false'),
+        array('name' => 'score', 'index' => 'exe_result', 'width' => '50', 'align' => 'left', 'search' => 'false'),
+        array('name' => 'actions', 'index' => 'actions', 'width' => '60', 'align' => 'left', 'search' => 'false')
+    );
 
     $action_links = '
     // add username as title in lastname filed - ref 4226
     function action_formatter(cellvalue, options, rowObject) {
         // rowObject is firstname,lastname,login,... get the third word
-        var loginx = "'.api_htmlentities(sprintf(get_lang("LoginX"),":::"), ENT_QUOTES).'";
+        var loginx = "'.api_htmlentities(sprintf(get_lang("LoginX"), ":::"), ENT_QUOTES).'";
         var tabLoginx = loginx.split(/:::/);
         // tabLoginx[0] is before and tabLoginx[1] is after :::
         // may be empty string but is defined
@@ -348,15 +387,15 @@ if ($is_allowedToEdit || $is_tutor) {
     }';
 } else {
     //The order is important you need to check the the $column variable in the model.ajax.php file
-	$columns        = array(get_lang('StartDate'),  get_lang('Score'),  get_lang('Actions'));
-
-  //Column config
-  // @todo fix search firstname/lastname that doesn't work. rmove search for the moment
-	$column_model   = array(
-                        array('name'=>'exe_date',		    'index'=>'exe_date',		'width'=>'60',   'align'=>'left', 'search' => 'false'),
-            			array('name'=>'score',			    'index'=>'exe_result',	'width'=>'50',   'align'=>'left', 'search' => 'false'),
-            			array('name'=>'actions',        'index'=>'actions',     'width'=>'60',  'align'=>'left', 'search' => 'false')
-                       );
+    $columns = array(get_lang('StartDate'), get_lang('Score'), get_lang('Actions'));
+
+    //Column config
+    // @todo fix search firstname/lastname that doesn't work. rmove search for the moment
+    $column_model = array(
+        array('name' => 'exe_date', 'index' => 'exe_date', 'width' => '60', 'align' => 'left', 'search' => 'false'),
+        array('name' => 'score', 'index' => 'exe_result', 'width' => '50', 'align' => 'left', 'search' => 'false'),
+        array('name' => 'actions', 'index' => 'actions', 'width' => '60', 'align' => 'left', 'search' => 'false')
+    );
 }
 
 //Autowidth
@@ -370,79 +409,82 @@ $extra_params['height'] = 'auto';
 ?>
 <script>
 
-function setSearchSelect(columnName) {
-    $("#results").jqGrid('setColProp', columnName,
-    {
-       searchoptions:{
-            dataInit:function(el){
-                $("option[value='1']",el).attr("selected", "selected");
-                setTimeout(function(){
-                    $(el).trigger('change');
-                },1000);
-            }
-        }
-    });
-}
+    function setSearchSelect(columnName) {
+        $("#results").jqGrid('setColProp', columnName,
+                {
+                    searchoptions:{
+                        dataInit:function (el) {
+                            $("option[value='1']", el).attr("selected", "selected");
+                            setTimeout(function () {
+                                $(el).trigger('change');
+                            }, 1000);
+                        }
+                    }
+                });
+    }
 
-function exportExcel() {
-    var mya=new Array();
-    mya=$("#results").getDataIDs();  // Get All IDs
-    var data=$("#results").getRowData(mya[0]);     // Get First row to get the labels
-    var colNames=new Array();
-    var ii=0;
-    for (var i in data){colNames[ii++]=i;}    // capture col names
-    var html="";
-
-    for(i=0;i<mya.length;i++) {
-        data=$("#results").getRowData(mya[i]); // get each row
-        for(j=0;j<colNames.length;j++) {
-            html=html+data[colNames[j]]+","; // output each column as tab delimited
+    function exportExcel() {
+        var mya = new Array();
+        mya = $("#results").getDataIDs();  // Get All IDs
+        var data = $("#results").getRowData(mya[0]);     // Get First row to get the labels
+        var colNames = new Array();
+        var ii = 0;
+        for (var i in data) {
+            colNames[ii++] = i;
+        }    // capture col names
+        var html = "";
+
+        for (i = 0; i < mya.length; i++) {
+            data = $("#results").getRowData(mya[i]); // get each row
+            for (j = 0; j < colNames.length; j++) {
+                html = html + data[colNames[j]] + ","; // output each column as tab delimited
+            }
+            html = html + "\n";  // output each row with end of line
         }
-        html=html+"\n";  // output each row with end of line
-    }
-    html = html+"\n";  // end of line at the end
+        html = html + "\n";  // end of line at the end
 
-    var form = $("#export_report_form");
+        var form = $("#export_report_form");
 
-    $("#csvBuffer").attr('value', html);
-    form.target='_blank';
-    form.submit();
-}
+        $("#csvBuffer").attr('value', html);
+        form.target = '_blank';
+        form.submit();
+    }
 
-$(function() {
+    $(function () {
     <?php
-    echo Display::grid_js('results', $url,$columns,$column_model, $extra_params, array(), $action_links, true);
+    echo Display::grid_js('results', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
 
-    if ($is_allowedToEdit || $is_tutor) { ?>
+    if ($is_allowedToEdit || $is_tutor) {
+        ?>
 
         //setSearchSelect("status");
         //
         //view:true, del:false, add:false, edit:false, excel:true}
-        $("#results").jqGrid('navGrid','#results_pager', {view:true, edit:false, add:false, del:false, excel:false},
-            {height:280, reloadAfterSubmit:false}, // view options
-            {height:280, reloadAfterSubmit:false}, // edit options
-            {height:280, reloadAfterSubmit:false}, // add options
-            {reloadAfterSubmit: false}, // del options
-            {width:500} // search options
+        $("#results").jqGrid('navGrid', '#results_pager', {view:true, edit:false, add:false, del:false, excel:false},
+                {height:280, reloadAfterSubmit:false}, // view options
+                {height:280, reloadAfterSubmit:false}, // edit options
+                {height:280, reloadAfterSubmit:false}, // add options
+                {reloadAfterSubmit:false}, // del options
+                {width:500} // search options
         );
 
         //Adding search options
         var options = {
-            'stringResult': true,
-            'autosearch' : true,
+            'stringResult':true,
+            'autosearch':true,
             'searchOnEnter':false
         }
-        jQuery("#results").jqGrid('filterToolbar',options);
+        jQuery("#results").jqGrid('filterToolbar', options);
         var sgrid = $("#results")[0];
         sgrid.triggerToolbar();
 
-    <?php } ?>
-});
+        <?php } ?>
+    });
 </script>
 <form id="export_report_form" method="post" action="hotpotatoes_exercise_report.php">
-    <input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
-    <input type="hidden" name="export_report" id="export_report" value="1" />
-    <input type="hidden" name="path" id="path" value="<?php echo $hotpotatoes_path ?>" />
+    <input type="hidden" name="csvBuffer" id="csvBuffer" value=""/>
+    <input type="hidden" name="export_report" id="export_report" value="1"/>
+    <input type="hidden" name="path" id="path" value="<?php echo $hotpotatoes_path ?>"/>
 </form>
 <?php
 

+ 43 - 36
main/exercice/qti2.php

@@ -1,11 +1,11 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*	Code for Qti2 import integration.
-*	@package chamilo.exercise
-* 	@author Ronny Velasquez
-* 	@version $Id: qti2.php  2010-03-12 12:14:25Z $
-*/
+ *    Code for Qti2 import integration.
+ * @package chamilo.exercise
+ * @author Ronny Velasquez
+ * @version $Id: qti2.php  2010-03-12 12:14:25Z $
+ */
 /**
  * Code
  */
@@ -26,56 +26,63 @@ $this_section = SECTION_COURSES;
 
 // access restriction: only teachers are allowed here
 if (!api_is_allowed_to_edit(null, true)) {
-	api_not_allowed();
+    api_not_allowed();
 }
 
 // the breadcrumbs
-$interbreadcrumb[]= array ("url"=>"exercice.php", "name"=> get_lang('Exercices'));
+$interbreadcrumb[] = array("url" => "exercice.php", "name" => get_lang('Exercices'));
 $is_allowedToEdit = api_is_allowed_to_edit(null, true);
 
 /**
  * This function displays the form for import of the zip file with qti2
  */
-function ch_qti2_display_form() {
-	$name_tools = get_lang('ImportQtiQuiz');
-	$form  = '<div class="actions">';
-	$form .= '<a href="exercice.php?show=test">' . Display :: return_icon('back.png', get_lang('BackToExercisesList'),'',ICON_SIZE_MEDIUM).'</a>';
-	$form .= '</div>';
-    $form_validator  = new FormValidator('qti_upload', 'post',api_get_self()."?".api_get_cidreq(), null, array('enctype' => 'multipart/form-data') );
-    $form_validator->addElement('header', $name_tools);    
-    $form_validator->addElement('file', 'userFile', get_lang('DownloadFile'));    
-    $form_validator->addElement('style_submit_button', 'submit', get_lang('Send'), 'class="upload"');    
-    $form .= $form_validator->return_form();	
+function ch_qti2_display_form()
+{
+    $name_tools = get_lang('ImportQtiQuiz');
+    $form = '<div class="actions">';
+    $form .= '<a href="exercice.php?show=test">'.Display :: return_icon(
+        'back.png',
+        get_lang('BackToExercisesList'),
+        '',
+        ICON_SIZE_MEDIUM
+    ).'</a>';
+    $form .= '</div>';
+    $form_validator = new FormValidator('qti_upload', 'post', api_get_self()."?".api_get_cidreq(
+    ), null, array('enctype' => 'multipart/form-data'));
+    $form_validator->addElement('header', $name_tools);
+    $form_validator->addElement('file', 'userFile', get_lang('DownloadFile'));
+    $form_validator->addElement('style_submit_button', 'submit', get_lang('Send'), 'class="upload"');
+    $form .= $form_validator->return_form();
 
-	echo $form;
+    echo $form;
 }
 
 /**
  * This function will import the zip file with the respective qti2
  * @param array $uploaded_file ($_FILES)
  */
-function ch_qti2_import_file($array_file) {
-	$unzip = 0;
-	$lib_path = api_get_path(LIBRARY_PATH);
-	require_once $lib_path.'fileUpload.lib.php';
-	require_once $lib_path.'fileManage.lib.php';
-	$process = process_uploaded_file($array_file);
-	if (preg_match('/\.zip$/i', $array_file['name'])) {
-		// if it's a zip, allow zip upload
-		$unzip = 1;
-	}
-	if ($process && $unzip == 1) {
-		$main_path = api_get_path(SYS_CODE_PATH);
-		require_once $main_path.'exercice/export/exercise_import.inc.php';
+function ch_qti2_import_file($array_file)
+{
+    $unzip = 0;
+    $lib_path = api_get_path(LIBRARY_PATH);
+    $process = FileManager::process_uploaded_file($array_file);
+    if (preg_match('/\.zip$/i', $array_file['name'])) {
+        // if it's a zip, allow zip upload
+        $unzip = 1;
+    }
+    if ($process && $unzip == 1) {
+        $main_path = api_get_path(SYS_CODE_PATH);
+        require_once $main_path.'exercice/export/exercise_import.inc.php';
         require_once $main_path.'exercice/export/qti2/qti2_classes.php';
         $imported = import_exercise($array_file['name']);
         if ($imported) {
-        	header('Location: exercice.php?'.api_get_cidreq());
+            header('Location: exercice.php?'.api_get_cidreq());
         } else {
             Display::display_error_message(get_lang('UplNoFileUploaded'));
+
             return false;
         }
-	}
+    }
 }
 
 // display header
@@ -83,9 +90,9 @@ Display::display_header(get_lang('ImportQtiQuiz'), 'Exercises');
 
 // import file
 if ((api_is_allowed_to_edit(null, true))) {
-	if (isset($_POST['submit'])) {
-		ch_qti2_import_file($_FILES['userFile']);
-	}
+    if (isset($_POST['submit'])) {
+        ch_qti2_import_file($_FILES['userFile']);
+    }
 }
 
 // display qti form

Fișier diff suprimat deoarece este prea mare
+ 667 - 583
main/exercice/question.class.php


+ 10 - 11
main/exercice/savescores.php

@@ -2,10 +2,10 @@
 
 /* For licensing terms, see /license.txt */
 /**
- * 	Saving the scores.
- * 	@package chamilo.exercise
- * 	@author
- * 	@version $Id: savescores.php 15602 2008-06-18 08:52:24Z pcool $
+ *     Saving the scores.
+ * @package chamilo.exercise
+ * @author
+ * @version $Id: savescores.php 15602 2008-06-18 08:52:24Z pcool $
  */
 /**
  * Code
@@ -25,8 +25,6 @@ if (isset($_GET['origin']) && $_GET['origin'] == 'learnpath') {
 require_once '../inc/global.inc.php';
 $this_section = SECTION_COURSES;
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
 $full_file_path = $documentPath.$test;
 
@@ -47,13 +45,14 @@ $jscript2run = '';
  * for HotPotatoes quizzes. When coming from the learning path, we
  * use the session variables telling us which item of the learning path has to
  * be updated (score-wise)
- * @param	string	File is the exercise name (the file name for a HP)
- * @param	integer	Score to save inside the tracking tables (HP and learnpath)
- * @return	void
+ * @param    string    File is the exercise name (the file name for a HP)
+ * @param    integer    Score to save inside the tracking tables (HP and learnpath)
+ * @return    void
  */
-function save_scores($file, $score) {
+function save_scores($file, $score)
+{
     global $origin, $_user, $_cid,
-    $TABLETRACK_HOTPOTATOES;
+           $TABLETRACK_HOTPOTATOES;
     // if tracking is disabled record nothing
     $weighting = 100; // 100%
     $date = api_get_utc_datetime();

+ 45 - 38
main/exercice/showinframes.php

@@ -1,26 +1,25 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- *	Code library for HotPotatoes integration.
- *	@package chamilo.exercise
- * 	@author Istvan Mandak
+ *    Code library for HotPotatoes integration.
+ * @package chamilo.exercise
+ * @author Istvan Mandak
  */
 /**
  * Included libraries
  */
 require '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'exercice/hotpotatoes.lib.php';
 
 $time = time();
 $doc_url = str_replace(array('../', '\\', '\\0', '..'), array('', '', '', ''), urldecode($_GET['file']));
-$cid                = api_get_course_id();
-$document_path      = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-$document_web_path  = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document';
-$origin             = $_REQUEST['origin'];
-$learnpath_id       = $_REQUEST['learnpath_id'];
-$learnpath_item_id  = $_REQUEST['learnpath_item_id'];
-$time               = $_REQUEST['time'];
+$cid = api_get_course_id();
+$document_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
+$document_web_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document';
+$origin = $_REQUEST['origin'];
+$learnpath_id = $_REQUEST['learnpath_id'];
+$learnpath_item_id = $_REQUEST['learnpath_item_id'];
+$time = $_REQUEST['time'];
 
 $user_id = api_get_user_id();
 $full_file_path = $document_path.$doc_url;
@@ -28,19 +27,27 @@ FileManager::my_delete($full_file_path.$user_id.'.t.html');
 $content = ReadFileCont($full_file_path.$user_id.'.t.html');
 
 if ($content == '') {
-	$content = ReadFileCont($full_file_path);
-	$mit = "function Finish(){";
-	$js_content = "
+    $content = ReadFileCont($full_file_path);
+    $mit = "function Finish(){";
+    $js_content = "
         //Code added - start
         var SaveScoreVariable = 0;
         function mySaveScore() {
             if (SaveScoreVariable==0) {
                 SaveScoreVariable = 1;
                     if (C.ie) {
-                        document.location.href = '".api_get_path(WEB_PATH)."main/exercice/savescores.php?origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&time=".Security::remove_XSS($time)."&test=".$doc_url."&uid=".$user_id."&cid=".$cid."&score='+Score;
+                        document.location.href = '".api_get_path(
+        WEB_PATH
+    )."main/exercice/savescores.php?origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&time=".Security::remove_XSS(
+        $time
+    )."&test=".$doc_url."&uid=".$user_id."&cid=".$cid."&score='+Score;
 						//window.alert(Score);
                     } else {
-                        window.location.href = '".api_get_path(WEB_PATH)."main/exercice/savescores.php?origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&time=".Security::remove_XSS($time)."&test=".$doc_url."&uid=".$user_id."&cid=".$cid."&score='+Score;
+                        window.location.href = '".api_get_path(
+        WEB_PATH
+    )."main/exercice/savescores.php?origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&time=".Security::remove_XSS(
+        $time
+    )."&test=".$doc_url."&uid=".$user_id."&cid=".$cid."&score='+Score;
                     }
 						}
 				}
@@ -49,39 +56,39 @@ if ($content == '') {
         //Code added - end
     ";
 
-	$newcontent = str_replace($mit, $js_content, $content);
-	$prehref = "<!-- BeginTopNavButtons -->";
-	$posthref = "<!-- BeginTopNavButtons -->";
-	$newcontent = str_replace($prehref, $posthref, $newcontent);
+    $newcontent = str_replace($mit, $js_content, $content);
+    $prehref = "<!-- BeginTopNavButtons -->";
+    $posthref = "<!-- BeginTopNavButtons -->";
+    $newcontent = str_replace($prehref, $posthref, $newcontent);
 
-	if (CheckSubFolder($full_file_path.$user_id.'.t.html') == 0) {
-		$newcontent = ReplaceImgTag($newcontent);
-	}
+    if (CheckSubFolder($full_file_path.$user_id.'.t.html') == 0) {
+        $newcontent = ReplaceImgTag($newcontent);
+    }
 } else {
-	$newcontent = $content;
+    $newcontent = $content;
 }
 
 
 WriteFileCont($full_file_path.$user_id.'.t.html', $newcontent);
 $doc_url = GetFolderPath($doc_url).urlencode(basename($doc_url));
 
-$documentPath= api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
+$documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
 $my_file = Security::remove_XSS($_GET['file']);
-$my_file = str_replace(array('../','\\..','\\0','..\\'),array('','','',''),urldecode($my_file));
+$my_file = str_replace(array('../', '\\..', '\\0', '..\\'), array('', '', '', ''), urldecode($my_file));
 
-$title = GetQuizName($my_file,$documentPath);
-if ($title =='') {
-	$title = basename($my_file);
+$title = GetQuizName($my_file, $documentPath);
+if ($title == '') {
+    $title = basename($my_file);
 }
 $nameTools = $title;
-$noPHP_SELF=true;
-if (isset($_SESSION['gradebook'])){
-	$gradebook=	$_SESSION['gradebook'];
+$noPHP_SELF = true;
+if (isset($_SESSION['gradebook'])) {
+    $gradebook = $_SESSION['gradebook'];
 }
 
-if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-        'url'  => '../gradebook/'.$_SESSION['gradebook_dest'],
+if (!empty($gradebook) && $gradebook == 'view') {
+    $interbreadcrumb[] = array(
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
         'name' => get_lang('ToolGradebook')
     );
 }
@@ -93,11 +100,11 @@ $htmlHeadXtra[] = '
     });
 </script>';
 
-$interbreadcrumb[]= array ("url"=>"./exercice.php", "name"=> get_lang('Exercices'));
+$interbreadcrumb[] = array("url" => "./exercice.php", "name" => get_lang('Exercices'));
 if ($origin == 'learnpath') {
-    Display::display_reduced_header($nameTools,"Exercise");
+    Display::display_reduced_header($nameTools, "Exercise");
 } else {
-    Display::display_header($nameTools,"Exercise");
+    Display::display_header($nameTools, "Exercise");
 }
 $url = $document_web_path.$doc_url.$user_id.'.t.html?time='.Security::remove_XSS($time);
 echo '<iframe style="overflow:hidden" id="hotpotatoe" width="100%" frameborder="0" src="'.$url.'"></iframe>';

+ 64 - 30
main/exercice/upload_exercise.php

@@ -1,10 +1,10 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- * 	Upload quiz: This script shows the upload quiz feature
+ *     Upload quiz: This script shows the upload quiz feature
  *  Initial work by Isaac flores on Nov 4 of 2010
  *  Encoding fixes Julio Montoya
- * 	@package chamilo.exercise
+ * @package chamilo.exercise
  */
 /**
  * Language files that should be included
@@ -19,8 +19,7 @@ $help_content = 'exercise_upload';
 
 // including the global Dokeos file
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'pear/excelreader/reader.php';
+require_once api_get_path(LIBRARY_PATH).'pear/excelreader/reader.php';
 require_once 'exercise.class.php';
 require_once 'question.class.php';
 require_once 'unique_answer.class.php';
@@ -45,19 +44,19 @@ $htmlHeadXtra[] = "<script type='text/javascript'>
 // Action handling
 lp_upload_quiz_action_handling();
 
-$interbreadcrumb[]= array ("url"=>"exercice.php", "name"=> get_lang('Exercices'));
+$interbreadcrumb[] = array("url" => "exercice.php", "name" => get_lang('Exercices'));
 
 // Display the header
 if ($origin != 'learnpath') {
     //so we are not in learnpath tool
     Display :: display_header(get_lang('ImportExcelQuiz'), 'Exercises');
     if (isset ($_GET['message'])) {
-        if (in_array($_GET['message'], array ('ExerciseEdited'))) {
+        if (in_array($_GET['message'], array('ExerciseEdited'))) {
             Display :: display_confirmation_message(get_lang($_GET['message']));
         }
     }
 } else {
-    echo '<link rel="stylesheet" type="text/css" href="' . api_get_path(WEB_CODE_PATH) . 'css/default.css"/>';
+    echo '<link rel="stylesheet" type="text/css" href="'.api_get_path(WEB_CODE_PATH).'css/default.css"/>';
 }
 // display the actions
 echo '<div class="actions">';
@@ -72,30 +71,49 @@ lp_upload_quiz_main();
 // close the content div
 echo '</div>';
 
-function lp_upload_quiz_actions() {
+function lp_upload_quiz_actions()
+{
     $lp_id = Security::remove_XSS($_GET['lp_id']);
     $return = "";
-    $return .= '<a href="exercice.php?'.api_get_cidReq().'">'.Display::return_icon('back.png', get_lang('BackToExercisesList'),'',ICON_SIZE_MEDIUM).'</a>';
+    $return .= '<a href="exercice.php?'.api_get_cidReq().'">'.Display::return_icon(
+        'back.png',
+        get_lang('BackToExercisesList'),
+        '',
+        ICON_SIZE_MEDIUM
+    ).'</a>';
+
     return $return;
 }
 
-function lp_upload_quiz_secondary_actions() {
- $lp_id = Security::remove_XSS($_GET['lp_id']);
- $return.= '';
- $return.='<a href="exercise_report.php?' . api_get_cidreq() . '">' . Display :: return_icon('reporting32.png', get_lang('Tracking')) . get_lang('Tracking') . '</a>';
- return $return;
+function lp_upload_quiz_secondary_actions()
+{
+    $lp_id = Security::remove_XSS($_GET['lp_id']);
+    $return .= '';
+    $return .= '<a href="exercise_report.php?'.api_get_cidreq().'">'.Display :: return_icon(
+        'reporting32.png',
+        get_lang('Tracking')
+    ).get_lang('Tracking').'</a>';
+
+    return $return;
 }
 
-function lp_upload_quiz_main() {
+function lp_upload_quiz_main()
+{
 
     // variable initialisation
     $lp_id = Security::remove_XSS($_GET['lp_id']);
 
-    $form = new FormValidator('upload', 'POST', api_get_self() . '?' . api_get_cidreq() . '&lp_id=' . $lp_id, '', array('enctype' => 'multipart/form-data'));
+    $form = new FormValidator('upload', 'POST', api_get_self().'?'.api_get_cidreq(
+    ).'&lp_id='.$lp_id, '', array('enctype' => 'multipart/form-data'));
     $form->addElement('header', get_lang('ImportExcelQuiz'));
     $form->addElement('file', 'user_upload_quiz', get_lang('FileUpload'));
 
-    $link = '<a href="../exercice/quiz_template.xls">'.Display::return_icon('export_excel.png', get_lang('DownloadExcelTemplate'),null,16).get_lang('DownloadExcelTemplate');
+    $link = '<a href="../exercice/quiz_template.xls">'.Display::return_icon(
+        'export_excel.png',
+        get_lang('DownloadExcelTemplate'),
+        null,
+        16
+    ).get_lang('DownloadExcelTemplate');
 
     $form->addElement('advanced_settings', $link);
 
@@ -109,7 +127,8 @@ function lp_upload_quiz_main() {
 /**
  * Handles a given Excel spreadsheets as in the template provided
  */
-function lp_upload_quiz_action_handling() {
+function lp_upload_quiz_action_handling()
+{
     global $_course, $debug;
     if (!isset($_POST['submit_upload_quiz'])) {
         return;
@@ -187,10 +206,10 @@ function lp_upload_quiz_action_handling() {
             $score_list[$z] = $column_data; //a complete line where 1st column is 'Score'
             $z++;
         } elseif (in_array($i, $feedback_true_index)) {
-            $feedback_true_list[$q] = $column_data;//a complete line where 1st column is 'FeedbackTrue'
+            $feedback_true_list[$q] = $column_data; //a complete line where 1st column is 'FeedbackTrue'
             $q++;
         } elseif (in_array($i, $feedback_false_index)) {
-            $feedback_false_list[$l] = $column_data;//a complete line where 1st column is 'FeedbackFalse' for wrong answers
+            $feedback_false_list[$l] = $column_data; //a complete line where 1st column is 'FeedbackFalse' for wrong answers
             $l++;
         }
     }
@@ -226,7 +245,16 @@ function lp_upload_quiz_action_handling() {
         $feedback = 0;
         // Quiz object
         $quiz_object = new Exercise();
-        $quiz_id = $quiz_object->create_quiz($quiz_title, $expired_time, $type, $random, $active, $results, $max_attempt, $feedback);
+        $quiz_id = $quiz_object->create_quiz(
+            $quiz_title,
+            $expired_time,
+            $type,
+            $random,
+            $active,
+            $results,
+            $max_attempt,
+            $feedback
+        );
 
         if ($quiz_id) {
 
@@ -258,13 +286,13 @@ function lp_upload_quiz_action_handling() {
                         } else {
                             $comment = $feedback_false_list[$i][2];
                         }
-    /*
-                        if ($id == 1) {
-                            $comment = $feedback_true_list[$i][2];
-                        } elseif ($id == 2) {
-                            $comment = $feedback_false_list[$i][2];
-                        }
-    */
+                        /*
+                                            if ($id == 1) {
+                                                $comment = $feedback_true_list[$i][2];
+                                            } elseif ($id == 2) {
+                                                $comment = $feedback_false_list[$i][2];
+                                            }
+                        */
                         // Create answer
                         $unique_answer->create_answer($id, $question_id, $answer, $comment, $score, $correct);
                         $id++;
@@ -302,11 +330,17 @@ function lp_upload_quiz_action_handling() {
             // Add a Quiz as Lp Item
             $_SESSION['oLP']->add_item($parent, $previous, TOOL_QUIZ, $quiz_id, ($quiz_title), '');
             // Redirect to home page for add more content
-            header('location: ../newscorm/lp_controller.php?' . api_get_cidreq() . '&action=add_item&type=step&lp_id=' . Security::remove_XSS($_GET['lp_id']).'&session_id='.api_get_session_id());
+            header(
+                'location: ../newscorm/lp_controller.php?'.api_get_cidreq(
+                ).'&action=add_item&type=step&lp_id='.Security::remove_XSS(
+                    $_GET['lp_id']
+                ).'&session_id='.api_get_session_id()
+            );
             exit;
         } else {
             //  header('location: exercice.php?' . api_get_cidreq());
-            echo '<script>window.location.href = "admin.php?'.api_get_cidReq().'&exerciseId='.$quiz_id.'&session_id='.api_get_session_id().'"</script>';
+            echo '<script>window.location.href = "admin.php?'.api_get_cidReq(
+            ).'&exerciseId='.$quiz_id.'&session_id='.api_get_session_id().'"</script>';
         }
     }
 }

Fișier diff suprimat deoarece este prea mare
+ 345 - 153
main/forum/forumfunction.inc.php


+ 406 - 348
main/gradebook/gradebook_view_result.php

@@ -17,9 +17,8 @@ require_once 'lib/gradebook_functions.inc.php';
 require_once 'lib/fe/displaygradebook.php';
 require_once 'lib/fe/evalform.class.php';
 require_once 'lib/fe/dataform.class.php';
-require_once api_get_path(LIBRARY_PATH) . 'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'export.lib.inc.php';
-require_once api_get_path(LIBRARY_PATH) . 'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 require_once 'lib/results_data_generator.class.php';
 require_once 'lib/fe/resulttable.class.php';
 require_once 'lib/fe/exportgradebook.php';
@@ -31,457 +30,516 @@ api_block_anonymous_users();
 
 block_students();
 
-$interbreadcrumb[]= array (
-	'url' => $_SESSION['gradebook_dest'],
-	'name' => get_lang('Gradebook'
-));
+$interbreadcrumb[] = array(
+    'url' => $_SESSION['gradebook_dest'],
+    'name' => get_lang(
+        'Gradebook'
+    )
+);
 
 //load the evaluation & category
-$select_eval=Security::remove_XSS($_GET['selecteval']);
+$select_eval = Security::remove_XSS($_GET['selecteval']);
 if (empty($select_eval)) {
-	api_not_allowed();
+    api_not_allowed();
 }
 
 $displayscore = Scoredisplay :: instance();
-$eval= Evaluation :: load($select_eval);
-$overwritescore= 0;
+$eval = Evaluation :: load($select_eval);
+$overwritescore = 0;
 if ($eval[0]->get_category_id() < 0) {
-	// if category id is negative, then the evaluation's origin is a link
-	$link= LinkFactory :: get_evaluation_link($eval[0]->get_id());
-	$currentcat= Category :: load($link->get_category_id());
-} else
-	$currentcat= Category :: load($eval[0]->get_category_id());
-	//load the result with the evaluation id
+    // if category id is negative, then the evaluation's origin is a link
+    $link = LinkFactory :: get_evaluation_link($eval[0]->get_id());
+    $currentcat = Category :: load($link->get_category_id());
+} else {
+    $currentcat = Category :: load($eval[0]->get_category_id());
+}
+//load the result with the evaluation id
 
 if (isset ($_GET['delete_mark'])) {
-    $result = Result :: load($_GET['delete_mark']);  
-    if (!empty( $result[0])) {  
+    $result = Result :: load($_GET['delete_mark']);
+    if (!empty($result[0])) {
         $result[0]->delete();
     }
 }
 
 if (isset ($_GET['selecteval'])) {
-	$allresults= Result :: load(null,null,$select_eval);
-	$iscourse= $currentcat[0]->get_course_code() == null ? 1 : 0;
+    $allresults = Result :: load(null, null, $select_eval);
+    $iscourse = $currentcat[0]->get_course_code() == null ? 1 : 0;
 }
 
 if (isset ($_GET['editres'])) {
-	$edit_res_xml=Security::remove_XSS($_GET['editres']);
-	$select_eval_edit=Security::remove_XSS($_GET['selecteval']);
-	$resultedit= Result :: load($edit_res_xml);
-	$edit_res_form= new EvalForm(EvalForm :: TYPE_RESULT_EDIT, $eval[0], $resultedit[0], 'edit_result_form', null, api_get_self() . '?editres=' . $resultedit[0]->get_id() . '&selecteval=' .$select_eval_edit);
-	if ($edit_res_form->validate()) {
-
-		$values= $edit_res_form->exportValues();
-		$result= new Result();
-		$resultlog=new Result();
-		$resultlog->add_result__log($values['hid_user_id'],$select_eval_edit);
-		$result->set_id($edit_res_xml);
-		$result->set_user_id($values['hid_user_id']);
-		$result->set_evaluation_id($select_eval_edit);
-		$row_value = isset($values['score']) ? (float)$values['score'] : 0 ;
-		if ((!empty ($row_value)) || ($row_value == 0)) {
-			$result->set_score(floatval(number_format($row_value, api_get_setting('gradebook_number_decimals'))));
-		}
-		$result->save();
-		unset ($result);
-		header('Location: gradebook_view_result.php?selecteval=' . $select_eval_edit . '&editresmessage=');
-		exit;
-	}
+    $edit_res_xml = Security::remove_XSS($_GET['editres']);
+    $select_eval_edit = Security::remove_XSS($_GET['selecteval']);
+    $resultedit = Result :: load($edit_res_xml);
+    $edit_res_form = new EvalForm(EvalForm :: TYPE_RESULT_EDIT, $eval[0], $resultedit[0], 'edit_result_form', null, api_get_self(
+    ).'?editres='.$resultedit[0]->get_id().'&selecteval='.$select_eval_edit);
+    if ($edit_res_form->validate()) {
+
+        $values = $edit_res_form->exportValues();
+        $result = new Result();
+        $resultlog = new Result();
+        $resultlog->add_result__log($values['hid_user_id'], $select_eval_edit);
+        $result->set_id($edit_res_xml);
+        $result->set_user_id($values['hid_user_id']);
+        $result->set_evaluation_id($select_eval_edit);
+        $row_value = isset($values['score']) ? (float)$values['score'] : 0;
+        if ((!empty ($row_value)) || ($row_value == 0)) {
+            $result->set_score(floatval(number_format($row_value, api_get_setting('gradebook_number_decimals'))));
+        }
+        $result->save();
+        unset ($result);
+        header('Location: gradebook_view_result.php?selecteval='.$select_eval_edit.'&editresmessage=');
+        exit;
+    }
 }
 
-if (isset ($_GET['import'])) {    
-    
-	$interbreadcrumb[]= array ('url' => 'gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']), 'name' => get_lang('ViewResult'));
-	$import_result_form = new DataForm(DataForm :: TYPE_IMPORT, 'import_result_form', null, api_get_self() . '?import=&selecteval=' . Security::remove_XSS($_GET['selecteval']), '_blank', '');
-	if (!$import_result_form->validate()) {
-		Display :: display_header(get_lang('Import'));
-	}
-    
+if (isset ($_GET['import'])) {
+
+    $interbreadcrumb[] = array(
+        'url' => 'gradebook_view_result.php?selecteval='.Security::remove_XSS(
+            $_GET['selecteval']
+        ),
+        'name' => get_lang('ViewResult')
+    );
+    $import_result_form = new DataForm(DataForm :: TYPE_IMPORT, 'import_result_form', null, api_get_self(
+    ).'?import=&selecteval='.Security::remove_XSS($_GET['selecteval']), '_blank', '');
+    if (!$import_result_form->validate()) {
+        Display :: display_header(get_lang('Import'));
+    }
+
     $eval[0]->check_lock_permissions();
 
-	if ($_POST['formSent'] ) {
-		if (!empty ($_FILES['import_file']['name'])) {
-			$values= $import_result_form->exportValues();
-			$file_type= $_POST['file_type'];
-			$file_name= $_FILES['import_file']['tmp_name'];
-			if ($file_type == 'csv') {
-				$results= Import :: csv_to_array($file_name);
-			} else {
-				$results= parse_xml_data($file_name);
-			}
-
-			$nr_results_added= 0;
-			foreach ($results as $index => $importedresult) {
-				//check username & score
-				$importedresult['user_id'] = UserManager::get_user_id_from_username($importedresult['username']);
-				$added= '0';
-				foreach ($allresults as $allresult) {
-					if (($importedresult['user_id'] == $allresult->get_user_id())) {
-						if ($importedresult['score'] != $allresult->get_score()) {
-							if (!isset ($values['overwrite'])) {
-								header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&import_score_error=' . $importedresult['user_id']);
-								exit;
-								break;
-							} else {
-								overwritescore($allresult->get_id(), $importedresult['score'], $eval[0]->get_max());
-								$overwritescore++;
-								$added= '1';
-							}
-						} else {
-							$added= '1';
-						}
-
-					}
-
-				}
-				if ($importedresult['user_id'] == null) {
-					header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&incorrectdata=');
-					exit;
-				}
-				$userinfo= get_user_info_from_id($importedresult['user_id']);
-				if ($userinfo['lastname'] != $importedresult['lastname'] || $userinfo['firstname'] != $importedresult['firstname'] || $userinfo['official_code'] != $importedresult['official_code']) {
-					if (!isset ($values['ignoreerrors'])) {
-						header('Location: gradebook_view_result.php?selecteval=' .Security::remove_XSS($_GET['selecteval']) . '&import_user_error=' . $importedresult['user_id']);
-						exit;
-					}
-				}
-				if ($added != '1') {
-					if ($importedresult['score'] > $eval[0]->get_max()) {
-						header('Location: gradebook_view_result.php?selecteval=' .Security::remove_XSS($_GET['selecteval']) . '&overwritemax=');
-						exit;
-					}
-					$result= new Result();
-					$result->set_user_id($importedresult['user_id']);
-					if (!empty ($importedresult['score'])) {
-						$result->set_score(floatval(number_format($importedresult['score'], api_get_setting('gradebook_number_decimals'))));
-					}
-					if (!empty ($importedresult['date'])) {
-						$result->set_date(api_get_utc_datetime($importedresult['date']));
-					} else {
-						$result->set_date(api_get_utc_datetime());
-					}
-					$result->set_evaluation_id($_GET['selecteval']);
-					$result->add();
-					$nr_results_added++;
-				}
-			}
-		} else {
-			header('Location: ' . api_get_self() . '?import=&selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&importnofile=');
-			exit;
-		}
-		if ($overwritescore != 0) {
-			header('Location: ' . api_get_self() . '?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&importoverwritescore=' . $overwritescore);
-			exit;
-		}
-		if ($nr_results_added == 0) {
-			header('Location: ' . api_get_self() . '?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&nothingadded=');
-			exit;
-		}
-		header('Location: ' . api_get_self() . '?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&importok=');
-		exit;
-	}
+    if ($_POST['formSent']) {
+        if (!empty ($_FILES['import_file']['name'])) {
+            $values = $import_result_form->exportValues();
+            $file_type = $_POST['file_type'];
+            $file_name = $_FILES['import_file']['tmp_name'];
+            if ($file_type == 'csv') {
+                $results = Import :: csv_to_array($file_name);
+            } else {
+                $results = parse_xml_data($file_name);
+            }
+
+            $nr_results_added = 0;
+            foreach ($results as $index => $importedresult) {
+                //check username & score
+                $importedresult['user_id'] = UserManager::get_user_id_from_username($importedresult['username']);
+                $added = '0';
+                foreach ($allresults as $allresult) {
+                    if (($importedresult['user_id'] == $allresult->get_user_id())) {
+                        if ($importedresult['score'] != $allresult->get_score()) {
+                            if (!isset ($values['overwrite'])) {
+                                header(
+                                    'Location: gradebook_view_result.php?selecteval='.Security::remove_XSS(
+                                        $_GET['selecteval']
+                                    ).'&import_score_error='.$importedresult['user_id']
+                                );
+                                exit;
+                                break;
+                            } else {
+                                overwritescore($allresult->get_id(), $importedresult['score'], $eval[0]->get_max());
+                                $overwritescore++;
+                                $added = '1';
+                            }
+                        } else {
+                            $added = '1';
+                        }
+
+                    }
+
+                }
+                if ($importedresult['user_id'] == null) {
+                    header(
+                        'Location: gradebook_view_result.php?selecteval='.Security::remove_XSS(
+                            $_GET['selecteval']
+                        ).'&incorrectdata='
+                    );
+                    exit;
+                }
+                $userinfo = get_user_info_from_id($importedresult['user_id']);
+                if ($userinfo['lastname'] != $importedresult['lastname'] || $userinfo['firstname'] != $importedresult['firstname'] || $userinfo['official_code'] != $importedresult['official_code']) {
+                    if (!isset ($values['ignoreerrors'])) {
+                        header(
+                            'Location: gradebook_view_result.php?selecteval='.Security::remove_XSS(
+                                $_GET['selecteval']
+                            ).'&import_user_error='.$importedresult['user_id']
+                        );
+                        exit;
+                    }
+                }
+                if ($added != '1') {
+                    if ($importedresult['score'] > $eval[0]->get_max()) {
+                        header(
+                            'Location: gradebook_view_result.php?selecteval='.Security::remove_XSS(
+                                $_GET['selecteval']
+                            ).'&overwritemax='
+                        );
+                        exit;
+                    }
+                    $result = new Result();
+                    $result->set_user_id($importedresult['user_id']);
+                    if (!empty ($importedresult['score'])) {
+                        $result->set_score(
+                            floatval(
+                                number_format($importedresult['score'], api_get_setting('gradebook_number_decimals'))
+                            )
+                        );
+                    }
+                    if (!empty ($importedresult['date'])) {
+                        $result->set_date(api_get_utc_datetime($importedresult['date']));
+                    } else {
+                        $result->set_date(api_get_utc_datetime());
+                    }
+                    $result->set_evaluation_id($_GET['selecteval']);
+                    $result->add();
+                    $nr_results_added++;
+                }
+            }
+        } else {
+            header(
+                'Location: '.api_get_self().'?import=&selecteval='.Security::remove_XSS(
+                    $_GET['selecteval']
+                ).'&importnofile='
+            );
+            exit;
+        }
+        if ($overwritescore != 0) {
+            header(
+                'Location: '.api_get_self().'?selecteval='.Security::remove_XSS(
+                    $_GET['selecteval']
+                ).'&importoverwritescore='.$overwritescore
+            );
+            exit;
+        }
+        if ($nr_results_added == 0) {
+            header(
+                'Location: '.api_get_self().'?selecteval='.Security::remove_XSS($_GET['selecteval']).'&nothingadded='
+            );
+            exit;
+        }
+        header('Location: '.api_get_self().'?selecteval='.Security::remove_XSS($_GET['selecteval']).'&importok=');
+        exit;
+    }
 }
 
 if (isset($_GET['export'])) {
-    $interbreadcrumb[]= array ('url' => 'gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']),'name' => get_lang('ViewResult'));
+    $interbreadcrumb[] = array(
+        'url' => 'gradebook_view_result.php?selecteval='.Security::remove_XSS(
+            $_GET['selecteval']
+        ),
+        'name' => get_lang('ViewResult')
+    );
     $locked_status = $eval[0]->get_locked();
-    $export_result_form= new DataForm(DataForm :: TYPE_EXPORT, 'export_result_form', null, api_get_self() . '?export=&selecteval=' . $_GET['selecteval'], '_blank', $locked_status);
+    $export_result_form = new DataForm(DataForm :: TYPE_EXPORT, 'export_result_form', null, api_get_self(
+    ).'?export=&selecteval='.$_GET['selecteval'], '_blank', $locked_status);
     if (!$export_result_form->validate()) {
-    	Display :: display_header(get_lang('Export'));
+        Display :: display_header(get_lang('Export'));
     }
-    
+
     if ($export_result_form->validate()) {
-    	$export= $export_result_form->exportValues();
-    	$file_type= $export['file_type'];
-    	$filename= 'export_results_' . gmdate('Y-m-d_H-i-s');
-    	$results= Result :: load(null, null, Security::remove_XSS($_GET['selecteval']));
-    	$data= array (); //when file type is csv, add a header to the output file
-    	if ($file_type == 'csv') {
-    		$alldata[]= array (
-    			'username',
-    			'official_code',
-    			'lastname',
-    			'firstname',
-    			'score',
-    			'date'
-    		);
-    	}
-    
-    	// export results to pdf file
-    	if ($file_type == 'pdf') {
-    		$number_decimals = api_get_setting('gradebook_number_decimals');
-    		$datagen = new ResultsDataGenerator ($eval[0],$allresults);
-    
-    		// set headers pdf
-    		!empty($_user['official_code'])? $officialcode=$_user['official_code'].' - ':'';
-    
-    		$h1 = array(get_lang('Teacher'),$officialcode.$_user['firstName'].', '.$_user['lastName']);
-    		$h2 = array(get_lang('Score'),$eval[0]->get_max());
-    		$h3 = array(get_lang('Course'),$_course['name']);
-    		$h4 = array(get_lang('Weight'),$eval[0]->get_weight());
-    		$h5 = array(get_lang('Session'),api_get_session_name(api_get_session_id()));
-    		$date = date('d-m-Y H:i:s', time());
-    		$h6 = array(get_lang('DateTime'),api_convert_and_format_date($date, "%d/%m/%Y %H:%M"));
-    		$header_pdf = array($h1, $h2, $h3, $h4, $h5, $h6);
-    
-    		// set footer pdf
-    		$f1 = '<hr />'.get_lang('Drh');
-    		$f2 = '<hr />'.get_lang('Teacher');
-    		$f3 = '<hr />'.get_lang('Date');
-    		$footer_pdf = array($f1, $f2, $f3);
-    
-    		// set title pdf
-    		$title_pdf = $eval[0]->get_name();
-    
-    		// set headers data table
-    		$head_ape_name = '';
-    		if (api_is_western_name_order()) {
-                $head_ape_name = get_lang('FirstName').', '.get_lang('LastName');			
-    		} else {
-    			$head_ape_name = get_lang('LastName').', '.get_lang('FirstName');
-    		}
-    		
-    		$head_table = array(
-    							array('#',	3),
-    							array(get_lang('Code'),12),
-    							array($head_ape_name, 40),
-    							array(get_lang('Score'),12)    											
-    						);
-    		if ($number_decimals == null) {
-    			$head_table[]  = array(get_lang('Letters'), 15);
-    		}    
+        $export = $export_result_form->exportValues();
+        $file_type = $export['file_type'];
+        $filename = 'export_results_'.gmdate('Y-m-d_H-i-s');
+        $results = Result :: load(null, null, Security::remove_XSS($_GET['selecteval']));
+        $data = array(); //when file type is csv, add a header to the output file
+        if ($file_type == 'csv') {
+            $alldata[] = array(
+                'username',
+                'official_code',
+                'lastname',
+                'firstname',
+                'score',
+                'date'
+            );
+        }
+
+        // export results to pdf file
+        if ($file_type == 'pdf') {
+            $number_decimals = api_get_setting('gradebook_number_decimals');
+            $datagen = new ResultsDataGenerator ($eval[0], $allresults);
+
+            // set headers pdf
+            !empty($_user['official_code']) ? $officialcode = $_user['official_code'].' - ' : '';
+
+            $h1 = array(get_lang('Teacher'), $officialcode.$_user['firstName'].', '.$_user['lastName']);
+            $h2 = array(get_lang('Score'), $eval[0]->get_max());
+            $h3 = array(get_lang('Course'), $_course['name']);
+            $h4 = array(get_lang('Weight'), $eval[0]->get_weight());
+            $h5 = array(get_lang('Session'), api_get_session_name(api_get_session_id()));
+            $date = date('d-m-Y H:i:s', time());
+            $h6 = array(get_lang('DateTime'), api_convert_and_format_date($date, "%d/%m/%Y %H:%M"));
+            $header_pdf = array($h1, $h2, $h3, $h4, $h5, $h6);
+
+            // set footer pdf
+            $f1 = '<hr />'.get_lang('Drh');
+            $f2 = '<hr />'.get_lang('Teacher');
+            $f3 = '<hr />'.get_lang('Date');
+            $footer_pdf = array($f1, $f2, $f3);
+
+            // set title pdf
+            $title_pdf = $eval[0]->get_name();
+
+            // set headers data table
+            $head_ape_name = '';
+            if (api_is_western_name_order()) {
+                $head_ape_name = get_lang('FirstName').', '.get_lang('LastName');
+            } else {
+                $head_ape_name = get_lang('LastName').', '.get_lang('FirstName');
+            }
+
+            $head_table = array(
+                array('#', 3),
+                array(get_lang('Code'), 12),
+                array($head_ape_name, 40),
+                array(get_lang('Score'), 12)
+            );
+            if ($number_decimals == null) {
+                $head_table[] = array(get_lang('Letters'), 15);
+            }
             $head_display_score = '';
-            $scoredisplay = ScoreDisplay :: instance();            
-            $customdisplays = $scoredisplay->get_custom_score_display_settings();            
-            
+            $scoredisplay = ScoreDisplay :: instance();
+            $customdisplays = $scoredisplay->get_custom_score_display_settings();
+
             if (!empty($customdisplays) && $scoredisplay->is_custom()) {
                 $head_display_score = get_lang('Display');
-                $head_table[] = array($head_display_score,15);
+                $head_table[] = array($head_display_score, 15);
             }
-                
-    		// get data table
-    		if (api_sort_by_first_name()) {
-     			$data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_FIRSTNAME, 0, null, false, true);
-    		} else {
-    			$data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_LASTNAME, 0,  null, false, true);
-    		}
-    		$data_table = array();
-    		
-    		foreach ($data_array as $data) {
-    			$result 	= array();
-    			$user_info	= api_get_user_info($data['id']);    			
-    			$result[] 	= $user_info['username'];
-    			
-    			if (api_is_western_name_order()) {
-                    $result[] = $user_info['firstname'].', '.$user_info['lastname'];                				
-    			} else {
-    				$result[] = $user_info['lastname'].', '.$user_info['firstname'];
-    			}
+
+            // get data table
+            if (api_sort_by_first_name()) {
+                $data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_FIRSTNAME, 0, null, false, true);
+            } else {
+                $data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_LASTNAME, 0, null, false, true);
+            }
+            $data_table = array();
+
+            foreach ($data_array as $data) {
+                $result = array();
+                $user_info = api_get_user_info($data['id']);
+                $result[] = $user_info['username'];
+
+                if (api_is_western_name_order()) {
+                    $result[] = $user_info['firstname'].', '.$user_info['lastname'];
+                } else {
+                    $result[] = $user_info['lastname'].', '.$user_info['firstname'];
+                }
                 if ($number_decimals == null) {
-	                if (empty($data['scoreletter']) && !is_numeric($data['score'])) {
-	                    $result[] = get_lang('DidNotTakeTheExam');
-	                } else {
-						$result[] = api_strtoupper(get_lang('Literal'.$data['scoreletter']));	                    
-	                }           
+                    if (empty($data['scoreletter']) && !is_numeric($data['score'])) {
+                        $result[] = get_lang('DidNotTakeTheExam');
+                    } else {
+                        $result[] = api_strtoupper(get_lang('Literal'.$data['scoreletter']));
+                    }
                 } else {
-                	if (empty($data['score']) && !is_numeric($data['score'])) {
-                		$result[] = get_lang('DidNotTakeTheExamAcronym');
-                	} else {
-                		$result[] = $data['score'];                        
-                	}	
+                    if (empty($data['score']) && !is_numeric($data['score'])) {
+                        $result[] = get_lang('DidNotTakeTheExamAcronym');
+                    } else {
+                        $result[] = $data['score'];
+                    }
                 }
                 if ($scoredisplay->is_custom()) {
-                    $result[] = $data['display'];                    
+                    $result[] = $data['display'];
                 }
-    			$data_table[] = $result;
-    		}
-    		export_pdf_with_html($head_table, $data_table, $header_pdf, $footer_pdf, $title_pdf);
-    	}
-    
-    	// export results to xml or csv file
-    	foreach ($results as $result) {
-    		$userinfo= get_user_info_from_id($result->get_user_id());
-    		$data['username']= $userinfo['username']; //$result->get_user_id();
-    		$data['official_code']= $userinfo['official_code'];
-    		$data['lastname']= $userinfo['lastname'];
-    		$data['firstname']= $userinfo['firstname'];
-    		$data['score']= $result->get_score();
-    		$data['date'] = api_format_date($result->get_date(), "%d/%m/%Y %R");
-    		$alldata[]= $data;
-    	}
-    
-    	switch ($file_type) {
-    		case 'xml' :
-    			Export :: export_table_xml($alldata, $filename, 'Result', 'XMLResults');
-    			exit;
-    			break;
-    		case 'csv' :
-    			Export :: export_table_csv($alldata, $filename);
-    			exit;
-    			break;
-    	}
-	}
+                $data_table[] = $result;
+            }
+            export_pdf_with_html($head_table, $data_table, $header_pdf, $footer_pdf, $title_pdf);
+        }
+
+        // export results to xml or csv file
+        foreach ($results as $result) {
+            $userinfo = get_user_info_from_id($result->get_user_id());
+            $data['username'] = $userinfo['username']; //$result->get_user_id();
+            $data['official_code'] = $userinfo['official_code'];
+            $data['lastname'] = $userinfo['lastname'];
+            $data['firstname'] = $userinfo['firstname'];
+            $data['score'] = $result->get_score();
+            $data['date'] = api_format_date($result->get_date(), "%d/%m/%Y %R");
+            $alldata[] = $data;
+        }
+
+        switch ($file_type) {
+            case 'xml' :
+                Export :: export_table_xml($alldata, $filename, 'Result', 'XMLResults');
+                exit;
+                break;
+            case 'csv' :
+                Export :: export_table_csv($alldata, $filename);
+                exit;
+                break;
+        }
+    }
 }
 if (isset ($_GET['resultdelete'])) {
-	$result= Result :: load($_GET['resultdelete']);
-	$result[0]->delete();
-	header('Location: gradebook_view_result.php?deleteresult=&selecteval=' .Security::remove_XSS($_GET['selecteval']));
-	exit;
+    $result = Result :: load($_GET['resultdelete']);
+    $result[0]->delete();
+    header('Location: gradebook_view_result.php?deleteresult=&selecteval='.Security::remove_XSS($_GET['selecteval']));
+    exit;
 }
 if (isset ($_POST['action'])) {
-	$number_of_selected_items= count($_POST['id']);
-	if ($number_of_selected_items == '0') {
-		Display :: display_warning_message(get_lang('NoItemsSelected'),false);
-	} else {
+    $number_of_selected_items = count($_POST['id']);
+    if ($number_of_selected_items == '0') {
+        Display :: display_warning_message(get_lang('NoItemsSelected'), false);
+    } else {
         switch ($_POST['action']) {
-    		case 'delete' :
-    			$number_of_deleted_results= 0;
-    			foreach ($_POST['id'] as $indexstr) {
-    				$result= Result :: load($indexstr);
-    				$result[0]->delete();
-    				$number_of_deleted_results++;
-    			}
-    			header('Location: gradebook_view_result.php?massdelete=&selecteval=' .Security::remove_XSS($_GET['selecteval']));
-    			exit;
-    			break;
-    	}
-	}
+            case 'delete' :
+                $number_of_deleted_results = 0;
+                foreach ($_POST['id'] as $indexstr) {
+                    $result = Result :: load($indexstr);
+                    $result[0]->delete();
+                    $number_of_deleted_results++;
+                }
+                header(
+                    'Location: gradebook_view_result.php?massdelete=&selecteval='.Security::remove_XSS(
+                        $_GET['selecteval']
+                    )
+                );
+                exit;
+                break;
+        }
+    }
 } // TODO - what if selecteval not set ?
 
-$addparams = array ('selecteval' => $eval[0]->get_id());
+$addparams = array('selecteval' => $eval[0]->get_id());
 if (isset ($_GET['print'])) {
-	$datagen = new ResultsDataGenerator ($eval[0],$allresults);
-	if (api_sort_by_first_name()) {
-		$data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_FIRSTNAME, 0, null, true);
-	} else {
-		$data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_LASTNAME,0,null,true);
-	}
-	if ($displayscore->is_custom()) {
-		if (api_is_western_name_order()) {
-			$header_names = array(get_lang('FirstName'),get_lang('LastName'),get_lang('Score'),get_lang('Display'));
-		} else {
-			$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'),get_lang('Display'));
-		}
-	} else {
-		if (api_is_western_name_order()) {
-			$header_names = array(get_lang('FirstName'),get_lang('LastName'),get_lang('Score'));
-		}else {
-			$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'));
-		}
-	}
-	$newarray = array();
-	foreach ($data_array as $data) {
-		$newarray[] = array_slice($data, 3);
-	}
-
-	echo print_table($newarray, $header_names,get_lang('ViewResult'), $eval[0]->get_name());
-	exit;
+    $datagen = new ResultsDataGenerator ($eval[0], $allresults);
+    if (api_sort_by_first_name()) {
+        $data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_FIRSTNAME, 0, null, true);
+    } else {
+        $data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_LASTNAME, 0, null, true);
+    }
+    if ($displayscore->is_custom()) {
+        if (api_is_western_name_order()) {
+            $header_names = array(get_lang('FirstName'), get_lang('LastName'), get_lang('Score'), get_lang('Display'));
+        } else {
+            $header_names = array(get_lang('LastName'), get_lang('FirstName'), get_lang('Score'), get_lang('Display'));
+        }
+    } else {
+        if (api_is_western_name_order()) {
+            $header_names = array(get_lang('FirstName'), get_lang('LastName'), get_lang('Score'));
+        } else {
+            $header_names = array(get_lang('LastName'), get_lang('FirstName'), get_lang('Score'));
+        }
+    }
+    $newarray = array();
+    foreach ($data_array as $data) {
+        $newarray[] = array_slice($data, 3);
+    }
+
+    echo print_table($newarray, $header_names, get_lang('ViewResult'), $eval[0]->get_name());
+    exit;
 } else {
-	$resulttable= new ResultTable($eval[0], $allresults, $iscourse, $addparams);
+    $resulttable = new ResultTable($eval[0], $allresults, $iscourse, $addparams);
 }
 
-$htmlHeadXtra[]= '<script type="text/javascript">
-	
+$htmlHeadXtra[] = '<script type="text/javascript">
+
 function confirmationuser() {
-    if (confirm("' . get_lang('DeleteUser') . '?"))
+    if (confirm("'.get_lang('DeleteUser').'?"))
     	{return true;}
     else
     	{return false;}
 }
 
 function confirmationall () {
-    if (confirm("' . get_lang('DeleteAll') . '?"))
+    if (confirm("'.get_lang('DeleteAll').'?"))
     	{return true;}
     else
     	{return false;}
     }
 </script>';
 if (isset ($_GET['deleteall'])) {
-	$eval[0]->delete_results();
-	header('Location: gradebook_view_result.php?allresdeleted=&selecteval=' . Security::remove_XSS($_GET['selecteval']));
-	exit;
+    $eval[0]->delete_results();
+    header('Location: gradebook_view_result.php?allresdeleted=&selecteval='.Security::remove_XSS($_GET['selecteval']));
+    exit;
 }
 if ((!isset ($_GET['export'])) && (!isset ($_GET['import']))) {
-	if (!isset($_GET['selectcat'])) {
-		$interbreadcrumb[]= array (
-		'url' => $_SESSION['gradebook_dest'].'?selectcat=' .$currentcat[0]->get_id(),
-		'name' => get_lang('Details')
-		  );
-	}
-	$interbreadcrumb[]= array ('url' => 'gradebook_view_result.php'.'?selecteval='.Security::remove_XSS($_GET['selecteval']),'name' => get_lang('ViewResult'));
-	Display :: display_header('');
+    if (!isset($_GET['selectcat'])) {
+        $interbreadcrumb[] = array(
+            'url' => $_SESSION['gradebook_dest'].'?selectcat='.$currentcat[0]->get_id(),
+            'name' => get_lang('Details')
+        );
+    }
+    $interbreadcrumb[] = array(
+        'url' => 'gradebook_view_result.php'.'?selecteval='.Security::remove_XSS(
+            $_GET['selecteval']
+        ),
+        'name' => get_lang('ViewResult')
+    );
+    Display :: display_header('');
 }
 if (isset ($_GET['addresultnostudents'])) {
-	Display :: display_warning_message(get_lang('AddResultNoStudents'),false);
+    Display :: display_warning_message(get_lang('AddResultNoStudents'), false);
 }
 
 if (isset ($_GET['editresmessage'])) {
-	Display :: display_confirmation_message(get_lang('ResultEdited'),false);
+    Display :: display_confirmation_message(get_lang('ResultEdited'), false);
 }
 
 if (isset ($_GET['addresult'])) {
-	Display :: display_confirmation_message(get_lang('ResultAdded'),false);
+    Display :: display_confirmation_message(get_lang('ResultAdded'), false);
 }
 
 if (isset ($_GET['adduser'])) {
-	Display :: display_confirmation_message(get_lang('UserAdded'),false);
+    Display :: display_confirmation_message(get_lang('UserAdded'), false);
 }
 
 if (isset ($_GET['deleteresult'])) {
-	Display :: display_confirmation_message(get_lang('ResultDeleted'),false);
+    Display :: display_confirmation_message(get_lang('ResultDeleted'), false);
 }
 
 if (isset ($_GET['editallresults'])) {
-	Display :: display_confirmation_message(get_lang('AllResultsEdited'),false);
+    Display :: display_confirmation_message(get_lang('AllResultsEdited'), false);
 }
 if (isset ($_GET['importok'])) {
-	Display :: display_confirmation_message(get_lang('FileUploadComplete'),false);
+    Display :: display_confirmation_message(get_lang('FileUploadComplete'), false);
 }
 if (isset ($_GET['importnofile'])) {
-	Display :: display_warning_message(get_lang('ImportNoFile'),false);
+    Display :: display_warning_message(get_lang('ImportNoFile'), false);
 }
 if (isset ($_GET['incorrectdata'])) {
-	Display :: display_warning_message(get_lang('IncorrectData'),false);
+    Display :: display_warning_message(get_lang('IncorrectData'), false);
 }
 if (isset ($_GET['nothingadded'])) {
-	Display :: display_warning_message(get_lang('ProblemUploadingFile'),false);
+    Display :: display_warning_message(get_lang('ProblemUploadingFile'), false);
 }
 if (isset ($_GET['massdelete'])) {
-	Display :: display_confirmation_message(get_lang('ResultsDeleted'),false);
+    Display :: display_confirmation_message(get_lang('ResultsDeleted'), false);
 }
 if (isset ($_GET['nouser'])) {
-	Display :: display_warning_message(get_lang('NoUser'),false);
+    Display :: display_warning_message(get_lang('NoUser'), false);
 }
 if (isset ($_GET['overwritemax'])) {
-	Display :: display_warning_message(get_lang('OverWriteMax'),false);
+    Display :: display_warning_message(get_lang('OverWriteMax'), false);
 }
 if (isset ($_GET['importoverwritescore'])) {
-	Display :: display_confirmation_message(get_lang('ImportOverWriteScore') . ' ' . $_GET['importoverwritescore']);
+    Display :: display_confirmation_message(get_lang('ImportOverWriteScore').' '.$_GET['importoverwritescore']);
 }
 if (isset ($_GET['import_user_error'])) {
-	$userinfo= get_user_info_from_id($_GET['import_user_error']);
-	Display :: display_warning_message(get_lang('UserInfoDoesNotMatch') . ' ' . api_get_person_name($userinfo['firstname'], $userinfo['lastname']));
+    $userinfo = get_user_info_from_id($_GET['import_user_error']);
+    Display :: display_warning_message(
+        get_lang('UserInfoDoesNotMatch').' '.api_get_person_name($userinfo['firstname'], $userinfo['lastname'])
+    );
 }
 if (isset ($_GET['allresdeleted'])) {
-	Display :: display_confirmation_message(get_lang('AllResultDeleted'));
+    Display :: display_confirmation_message(get_lang('AllResultDeleted'));
 }
 if (isset ($_GET['import_score_error'])) {
-	$userinfo= get_user_info_from_id($_GET['import_score_error']);
-	Display :: display_warning_message(get_lang('ScoreDoesNotMatch') . ' ' . api_get_person_name($userinfo['firstname'], $userinfo['lastname']));
+    $userinfo = get_user_info_from_id($_GET['import_score_error']);
+    Display :: display_warning_message(
+        get_lang('ScoreDoesNotMatch').' '.api_get_person_name($userinfo['firstname'], $userinfo['lastname'])
+    );
 }
 if ($file_type == null) { //show the result header
     if (isset ($export_result_form) && !(isset ($edit_res_form))) {
-    	echo $export_result_form->display();
-    	DisplayGradebook :: display_header_result($eval[0], $currentcat[0]->get_id(), 1);
+        echo $export_result_form->display();
+        DisplayGradebook :: display_header_result($eval[0], $currentcat[0]->get_id(), 1);
     } else {
-    	if (isset ($import_result_form)) {    		
-    		echo $import_result_form->display();    		
-    	}
-    	if (isset ($edit_res_form)) {
-    		echo $edit_res_form->toHtml();
-    	}
-    	DisplayGradebook :: display_header_result($eval[0], $currentcat[0]->get_id(), 1);
+        if (isset ($import_result_form)) {
+            echo $import_result_form->display();
+        }
+        if (isset ($edit_res_form)) {
+            echo $edit_res_form->toHtml();
+        }
+        DisplayGradebook :: display_header_result($eval[0], $currentcat[0]->get_id(), 1);
     }
     $resulttable->display();
     Display :: display_footer();

+ 24 - 22
main/gradebook/user_info.php

@@ -10,19 +10,18 @@
 $language_file = 'gradebook';
 //$cidReset = true;
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH) . 'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'export.lib.inc.php';
-require_once api_get_path(LIBRARY_PATH) . 'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 api_block_anonymous_users();
 
 if (isset($_GET['userid'])) {
-	$user_id = Security::remove_XSS($_GET['userid']);
-	$user = UserManager::get_user_info_by_id($user_id);
-	if (!$user) {
-		api_not_allowed();
-	}
+    $user_id = Security::remove_XSS($_GET['userid']);
+    $user = UserManager::get_user_info_by_id($user_id);
+    if (!$user) {
+        api_not_allowed();
+    }
 } else {
-	api_not_allowed();
+    api_not_allowed();
 }
 
 require_once 'lib/be.inc.php';
@@ -30,32 +29,35 @@ require_once 'lib/gradebook_functions.inc.php';
 require_once 'lib/fe/userform.class.php';
 block_students();
 
-$form = new UserForm(UserForm :: TYPE_USER_INFO, $user, 'user_info_form', null, api_get_self() . '?userid=' . $user_id . '&selectcat=' . Security::remove_XSS($_GET['selectcat']));
+$form = new UserForm(UserForm :: TYPE_USER_INFO, $user, 'user_info_form', null, api_get_self(
+).'?userid='.$user_id.'&selectcat='.Security::remove_XSS($_GET['selectcat']));
 if ($form->validate()) {
-	header('Location: user_stats.php?selectcat=' . Security::remove_XSS($_GET['selectcat']).'&userid=' .$user_id);
-	exit;
+    header('Location: user_stats.php?selectcat='.Security::remove_XSS($_GET['selectcat']).'&userid='.$user_id);
+    exit;
 }
 
-$interbreadcrumb[] = array (
-	'url' => $_SESSION['gradebook_dest'],
-	'name' => get_lang('Gradebook'
-));
+$interbreadcrumb[] = array(
+    'url' => $_SESSION['gradebook_dest'],
+    'name' => get_lang(
+        'Gradebook'
+    )
+);
 Display :: display_header(get_lang('UserInfo'));
 
 //User picture size is calculated from SYSTEM path
-$image_syspath = UserManager::get_user_picture_path_by_id($user_id,'system',false,true);
+$image_syspath = UserManager::get_user_picture_path_by_id($user_id, 'system', false, true);
 $image_size = getimagesize($image_syspath['dir'].$image_syspath['file']);
 //Web path
-$image_path = UserManager::get_user_picture_path_by_id($user_id,'web',false,true);
+$image_path = UserManager::get_user_picture_path_by_id($user_id, 'web', false, true);
 $image_file = $image_path['dir'].$image_path['file'];
 
 $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
-	.'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
-	.'style="float:left; padding:5px;" ';
+    .'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
+    .'style="float:left; padding:5px;" ';
 
 if ($image_size[0] > 300) {
-	//limit display width to 300px
-	$img_attributes .= 'width="300" ';
+    //limit display width to 300px
+    $img_attributes .= 'width="300" ';
 }
 //@todo need a "makeup"
 echo '<img '.$img_attributes.'/>';

+ 228 - 163
main/inc/global.inc.php

@@ -16,15 +16,15 @@
  * @todo isn't configuration.php renamed to configuration.inc.php yet?
  * @todo use the $_configuration array for all the needed variables
  * @todo remove the code that displays the button that links to the install page
- * 		but use a redirect immediately. By doing so the $already_installed variable can be removed.
+ *         but use a redirect immediately. By doing so the $already_installed variable can be removed.
  * @todo make it possible to enable / disable the tracking through the Chamilo config page.
  *
  */
 
- //@todo will be removed before a stable release
+//@todo will be removed before a stable release
 
 $mtime = microtime();
-$mtime = explode(" ",$mtime);
+$mtime = explode(" ", $mtime);
 $mtime = $mtime[1] + $mtime[0];
 $starttime = $mtime;
 define('START', $starttime);
@@ -65,15 +65,15 @@ if (!isset($GLOBALS['_configuration'])) {
 
 // Code for trnasitional purposes, it can be removed right before the 1.8.7 release.
 if (empty($_configuration['system_version'])) {
-    $_configuration['system_version']   = (!empty($_configuration['dokeos_version'])?$_configuration['dokeos_version']:'');
-    $_configuration['system_stable']    = (!empty($_configuration['dokeos_stable'])?$_configuration['dokeos_stable']:'');
-    $_configuration['software_url']     = 'http://www.chamilo.org/';
+    $_configuration['system_version'] = (!empty($_configuration['dokeos_version']) ? $_configuration['dokeos_version'] : '');
+    $_configuration['system_stable'] = (!empty($_configuration['dokeos_stable']) ? $_configuration['dokeos_stable'] : '');
+    $_configuration['software_url'] = 'http://www.chamilo.org/';
 }
 
 // For backward compatibility.
-$_configuration['dokeos_version']       = $_configuration['system_version'];
-$_configuration['dokeos_stable']        = $_configuration['system_stable'];
-$userPasswordCrypted                    = (!empty($_configuration['password_encryption']) ? $_configuration['password_encryption'] : 'sha1');
+$_configuration['dokeos_version'] = $_configuration['system_version'];
+$_configuration['dokeos_stable'] = $_configuration['system_stable'];
+$userPasswordCrypted = (!empty($_configuration['password_encryption']) ? $_configuration['password_encryption'] : 'sha1');
 
 // Include the main Chamilo platform library file.
 require_once $includePath.'/lib/main_api.lib.php';
@@ -136,18 +136,24 @@ $app->register(new Silex\Provider\UrlGeneratorServiceProvider());
 
 $app->register(new Silex\Provider\ValidatorServiceProvider());
 
-$app->register(new Silex\Provider\TranslationServiceProvider(),array(
-    'locale_fallback' => 'en'
-));
+$app->register(
+    new Silex\Provider\TranslationServiceProvider(),
+    array(
+        'locale_fallback' => 'en'
+    )
+);
 
 //Form provider
 $app->register(new Silex\Provider\FormServiceProvider());
 
 //Monolog
-$app->register(new Silex\Provider\MonologServiceProvider(), array(
-    'monolog.logfile' => api_get_path(SYS_ARCHIVE_PATH).'chamilo_development.log',
-    'monolog.name'    => 'chamilo',
-));
+$app->register(
+    new Silex\Provider\MonologServiceProvider(),
+    array(
+        'monolog.logfile' => api_get_path(SYS_ARCHIVE_PATH).'chamilo_development.log',
+        'monolog.name' => 'chamilo',
+    )
+);
 
 /*
 //Monolog examples
@@ -158,62 +164,80 @@ $app['monolog']->addError('Testing the Monolog logging.');
 $app['translator.messages'] = array();
 
 //Setting the Twig service provider
-$app->register(new Silex\Provider\TwigServiceProvider(), array(
-    'twig.path' => array(
-        api_get_path(SYS_CODE_PATH).'template', //template folder
-        api_get_path(SYS_PLUGIN_PATH)             //plugin folder
-    ),
-    'twig.form.templates' => array('form_div_layout.html.twig', 'default/form/form_custom_template.tpl'),
-    'twig.options'          => array(
-        'debug'             => $app['debug'],
-        'charset'           => 'utf-8',
-        'strict_variables'  => false,
-        'autoescape'        => false,
-        'cache'             => $app['debug'] ? false : $app['cache.path'].'twig',
-        'optimizations' => -1, // turn on optimizations with -1
+$app->register(
+    new Silex\Provider\TwigServiceProvider(),
+    array(
+        'twig.path' => array(
+            api_get_path(SYS_CODE_PATH).'template', //template folder
+            api_get_path(SYS_PLUGIN_PATH) //plugin folder
+        ),
+        'twig.form.templates' => array('form_div_layout.html.twig', 'default/form/form_custom_template.tpl'),
+        'twig.options' => array(
+            'debug' => $app['debug'],
+            'charset' => 'utf-8',
+            'strict_variables' => false,
+            'autoescape' => false,
+            'cache' => $app['debug'] ? false : $app['cache.path'].'twig',
+            'optimizations' => -1, // turn on optimizations with -1
+        )
     )
-));
+);
 
 //Setting Twig options
-$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
-    $twig->addFilter('get_lang', new Twig_Filter_Function('get_lang'));
-    $twig->addFilter('get_path', new Twig_Filter_Function('api_get_path'));
-    $twig->addFilter('get_setting', new Twig_Filter_Function('api_get_setting'));
-    $twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
-    $twig->addFilter('return_message', new Twig_Filter_Function('Display::return_message_and_translate'));
-    $twig->addFilter('display_page_header', new Twig_Filter_Function('Display::page_header_and_translate'));
-    $twig->addFilter('display_page_subheader', new Twig_Filter_Function('Display::page_subheader_and_translate'));
-    $twig->addFilter('icon', new Twig_Filter_Function('Template::get_icon_path'));
-    $twig->addFilter('format_date', new Twig_Filter_Function('Template::format_date'));
-    return $twig;
-}));
+$app['twig'] = $app->share(
+    $app->extend(
+        'twig',
+        function ($twig, $app) {
+            $twig->addFilter('get_lang', new Twig_Filter_Function('get_lang'));
+            $twig->addFilter('get_path', new Twig_Filter_Function('api_get_path'));
+            $twig->addFilter('get_setting', new Twig_Filter_Function('api_get_setting'));
+            $twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
+            $twig->addFilter('return_message', new Twig_Filter_Function('Display::return_message_and_translate'));
+            $twig->addFilter('display_page_header', new Twig_Filter_Function('Display::page_header_and_translate'));
+            $twig->addFilter(
+                'display_page_subheader',
+                new Twig_Filter_Function('Display::page_subheader_and_translate')
+            );
+            $twig->addFilter('icon', new Twig_Filter_Function('Template::get_icon_path'));
+            $twig->addFilter('format_date', new Twig_Filter_Function('Template::format_date'));
+
+            return $twig;
+        }
+    )
+);
 
 //Setting Doctrine service provider (DBAL)
 if (isset($_configuration['main_database'])) {
 
-    $app->register(new Silex\Provider\DoctrineServiceProvider(), array(
-        'db.options' => array(
-            'driver'    => 'pdo_mysql',
-            'dbname'    => $_configuration['main_database'],
-            'user'      => $_configuration['db_user'],
-            'password'  => $_configuration['db_password'],
-            'host'      => $_configuration['db_host'],
+    $app->register(
+        new Silex\Provider\DoctrineServiceProvider(),
+        array(
+            'db.options' => array(
+                'driver' => 'pdo_mysql',
+                'dbname' => $_configuration['main_database'],
+                'user' => $_configuration['db_user'],
+                'password' => $_configuration['db_password'],
+                'host' => $_configuration['db_host'],
+            )
         )
-    ));
+    );
 
     //Setting Doctrine ORM
-    $app->register(new Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider, array(
-        "orm.proxies_dir" => $app['db.orm.proxies_dir'],
-        "orm.em.options" => array(
-            "mappings" => array(
-                array(
-                    "type" => "annotation",
-                    "namespace" => "Entity",
-                    "path" => api_get_path(INCLUDE_PATH).'Entity',
-                )
+    $app->register(
+        new Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider,
+        array(
+            "orm.proxies_dir" => $app['db.orm.proxies_dir'],
+            "orm.em.options" => array(
+                "mappings" => array(
+                    array(
+                        "type" => "annotation",
+                        "namespace" => "Entity",
+                        "path" => api_get_path(INCLUDE_PATH).'Entity',
+                    )
+                ),
             ),
-        ),
-    ));
+        )
+    );
 
 
     //Setting Doctrine2 extensions
@@ -231,14 +255,20 @@ if (isset($_configuration['main_database'])) {
 //Creating Chamilo service provider
 use Silex\ServiceProviderInterface;
 
-class ChamiloServiceProvider implements ServiceProviderInterface {
-    public function register(Application $app) {
+class ChamiloServiceProvider implements ServiceProviderInterface
+{
+    public function register(Application $app)
+    {
         //Template
-        $app['template'] = $app->share(function() use($app){
-            return new Template(null, $app);
-        });
+        $app['template'] = $app->share(
+            function () use ($app) {
+                return new Template(null, $app);
+            }
+        );
     }
-    public function boot(Application $app) {
+
+    public function boot(Application $app)
+    {
     }
 }
 
@@ -248,36 +278,41 @@ $app->register(new ChamiloServiceProvider(), array());
 //Controllers as services
 $app->register(new Silex\Provider\ServiceControllerServiceProvider());
 
-$app['pages.controller'] = $app->share(function() use ($app) {
-    return new PagesController($app['pages.repository']);
-});
+$app['pages.controller'] = $app->share(
+    function () use ($app) {
+        return new PagesController($app['pages.repository']);
+    }
+);
 
 //Manage error messages
 
-$app->error(function (\Exception $e, $code) use ($app) {
-    if ($app['debug']) {
-        //return;
-    }
+$app->error(
+    function (\Exception $e, $code) use ($app) {
+        if ($app['debug']) {
+            //return;
+        }
 
-    if (isset($code)) {
-        switch ($code) {
-             case 404:
-                $message = 'The requested page could not be found.';
-                break;
-            default:
-                //$message = 'We are sorry, but something went terribly wrong.';
-                $message = $e->getMessage();
+        if (isset($code)) {
+            switch ($code) {
+                case 404:
+                    $message = 'The requested page could not be found.';
+                    break;
+                default:
+                    //$message = 'We are sorry, but something went terribly wrong.';
+                    $message = $e->getMessage();
+            }
+        } else {
+            $code = null;
+            $message = null;
         }
-    } else {
-        $code = null;
-        $message = null;
+        //$code = ($e instanceof HttpException) ? $e->getStatusCode() : 500;
+        $app['template']->assign('error_code', $code);
+        $app['template']->assign('error_message', $message);
+        $response = $app['template']->render_layout('error.tpl');
+
+        return new Response($response);
     }
-    //$code = ($e instanceof HttpException) ? $e->getStatusCode() : 500;
-    $app['template']->assign('error_code', $code);
-    $app['template']->assign('error_message', $message);
-    $response = $app['template']->render_layout('error.tpl');
-    return new Response($response);
-});
+);
 
 /*
 use Symfony\Component\HttpKernel\Debug\ErrorHandler;
@@ -286,40 +321,46 @@ ErrorHandler::register();
 use Symfony\Component\HttpFoundation\RedirectResponse;
 
 //Filters
-$app->before(function() use ($app) {
-    //Check the PHP version
-    if (api_check_php_version() == false) {
-        $app->abort(500, "Incorrect PHP version"); //error 1
+$app->before(
+    function () use ($app) {
+        //Check the PHP version
+        if (api_check_php_version() == false) {
+            $app->abort(500, "Incorrect PHP version"); //error 1
+        }
+
+        if (!file_exists($app['configuration_file'])) {
+            return new RedirectResponse(api_get_path(WEB_CODE_PATH).'install');
+        }
+        //$app['request']->getSession()->start();
     }
+);
 
-    if (!file_exists($app['configuration_file'])) {
-        return new RedirectResponse(api_get_path(WEB_CODE_PATH).'install');
+$app->after(
+    function () {
+    }
+);
+
+$app->finish(
+    function () use ($app) {
+        //@todo will be removed before a stable release
+        $mtime = microtime();
+        $mtime = explode(" ", $mtime);
+        $mtime = $mtime[1] + $mtime[0];
+
+        $message = "Page loaded in:".($mtime - START);
+        $app['monolog']->addInfo($message);
+        $message = "memory_get_usage: ".format_file_size(memory_get_usage(true));
+        $app['monolog']->addInfo($message);
+        $message = "memory_get_peak_usage: ".format_file_size(memory_get_peak_usage(true));
+        $app['monolog']->addInfo($message);
     }
-    //$app['request']->getSession()->start();
-});
-
-$app->after(function() {
-});
-
-$app->finish(function() use ($app) {
-    //@todo will be removed before a stable release
-    $mtime = microtime();
-    $mtime = explode(" ",$mtime);
-    $mtime = $mtime[1] + $mtime[0];
-
-    $message = "Page loaded in:".($mtime-START);
-    $app['monolog']->addInfo($message);
-    $message = "memory_get_usage: ".format_file_size(memory_get_usage(true));
-    $app['monolog']->addInfo($message);
-    $message = "memory_get_peak_usage: ".format_file_size(memory_get_peak_usage(true));
-    $app['monolog']->addInfo($message);
-});
-
-$app['template.show_header']        = true;
-$app['template.show_footer']        = true;
-$app['template.show_learnpath']     = true;
-$app['template.hide_global_chat']   = true;
-$app['template.load_plugins']       = true;
+);
+
+$app['template.show_header'] = true;
+$app['template.show_footer'] = true;
+$app['template.show_learnpath'] = true;
+$app['template.hide_global_chat'] = true;
+$app['template.load_plugins'] = true;
 
 //Default template style
 $app['template_style'] = 'default';
@@ -328,7 +369,6 @@ $app['default_layout'] = 'layout_1_col.tpl';
 
 //Database constants
 require_once $lib_path.'database.constants.inc.php';
-require_once $lib_path.'fileManage.lib.php';
 require_once $lib_path.'text.lib.php';
 require_once $lib_path.'array.lib.php';
 require_once $lib_path.'events.lib.inc.php';
@@ -341,11 +381,14 @@ global $database_connection;
 // Connect to the server database and select the main chamilo database.
 if (!($conn_return = @Database::connect(
     array(
-        'server'        => $_configuration['db_host'],
-        'username'      => $_configuration['db_user'],
-        'password'      => $_configuration['db_password'],
-        'persistent'    => $_configuration['db_persistent_connection'] // When $_configuration['db_persistent_connection'] is set, it is expected to be a boolean type.
-    )))) {
+        'server' => $_configuration['db_host'],
+        'username' => $_configuration['db_user'],
+        'password' => $_configuration['db_password'],
+        'persistent' => $_configuration['db_persistent_connection']
+        // When $_configuration['db_persistent_connection'] is set, it is expected to be a boolean type.
+    )
+))
+) {
     //$app->abort(500, "Database is unavailable"); //error 3
 }
 
@@ -408,7 +451,7 @@ if (api_is_utf8($charset)) {
     // See Bug #1802: For UTF-8 systems we prefer to use "SET NAMES 'utf8'" statement in order to avoid a bizarre problem with Chinese language.
     Database::query("SET NAMES 'utf8';");
 } else {
-    Database::query("SET CHARACTER SET '" . Database::to_db_encoding($charset) . "';");
+    Database::query("SET CHARACTER SET '".Database::to_db_encoding($charset)."';");
 }
 Database::query("SET NAMES 'utf8';");
 
@@ -448,31 +491,36 @@ require $includePath.'/local.inc.php';
 
 //Fixes bug in Chamilo 1.8.7.1 array was not set
 $administrator['email'] = isset($administrator['email']) ? $administrator['email'] : 'admin@example.com';
-$administrator['name']  = isset($administrator['name']) ? $administrator['name'] : 'Admin';
+$administrator['name'] = isset($administrator['name']) ? $administrator['name'] : 'Admin';
 
 $mail_conf = api_get_path(CONFIGURATION_PATH).'mail.conf.php';
 
 if (file_exists($mail_conf)) {
-	require_once $mail_conf;
+    require_once $mail_conf;
 }
 
 $mail_settings = array();
 
-$app->register(new Silex\Provider\SwiftmailerServiceProvider(), array(
-     'swiftmailer.options' =>  array(
-        'host' => $platform_email['SMTP_HOST'],
-        'port' => $platform_email['SMTP_PORT'],
-        'username' => $platform_email['SMTP_USER'],
-        'password' => $platform_email['SMTP_PASS'],
-        'encryption' => null,
-        'auth_mode' => null
+$app->register(
+    new Silex\Provider\SwiftmailerServiceProvider(),
+    array(
+        'swiftmailer.options' => array(
+            'host' => $platform_email['SMTP_HOST'],
+            'port' => $platform_email['SMTP_PORT'],
+            'username' => $platform_email['SMTP_USER'],
+            'password' => $platform_email['SMTP_PASS'],
+            'encryption' => null,
+            'auth_mode' => null
+        )
     )
-));
+);
 
 //if (isset($platform_email['SMTP_MAILER']) && $platform_email['SMTP_MAILER'] == 'smtp') {
-$app['mailer'] = $app->share(function ($app) {
-    return new \Swift_Mailer($app['swiftmailer.transport']);
-});
+$app['mailer'] = $app->share(
+    function ($app) {
+        return new \Swift_Mailer($app['swiftmailer.transport']);
+    }
+);
 
 
 // check and modify the date of user in the track.e.online table
@@ -492,11 +540,21 @@ if (api_get_setting('server_type') == 'test') {
     error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
 
     // TODO: These obsolete variables $HTTP_* to be check whether they are actually used.
-    if (!isset($HTTP_GET_VARS)) { $HTTP_GET_VARS = $_GET; }
-    if (!isset($HTTP_POST_VARS)) { $HTTP_POST_VARS = $_POST; }
-    if (!isset($HTTP_POST_FILES)) { $HTTP_POST_FILES = $_FILES; }
-    if (!isset($HTTP_SESSION_VARS)) { $HTTP_SESSION_VARS = $_SESSION; }
-    if (!isset($HTTP_SERVER_VARS)) { $HTTP_SERVER_VARS = $_SERVER; }
+    if (!isset($HTTP_GET_VARS)) {
+        $HTTP_GET_VARS = $_GET;
+    }
+    if (!isset($HTTP_POST_VARS)) {
+        $HTTP_POST_VARS = $_POST;
+    }
+    if (!isset($HTTP_POST_FILES)) {
+        $HTTP_POST_FILES = $_FILES;
+    }
+    if (!isset($HTTP_SESSION_VARS)) {
+        $HTTP_SESSION_VARS = $_SESSION;
+    }
+    if (!isset($HTTP_SERVER_VARS)) {
+        $HTTP_SERVER_VARS = $_SERVER;
+    }
 
     // Register SESSION variables into $GLOBALS
     if (sizeof($HTTP_SESSION_VARS)) {
@@ -514,8 +572,8 @@ if (api_get_setting('server_type') == 'test') {
         $_SERVER = array();
         foreach ($HTTP_SERVER_VARS as $key => $val) {
             $_SERVER[$key] = $HTTP_SERVER_VARS[$key];
-            if (!isset($_SESSION[$key]) && $key != 'includePath' && $key != 'rootSys' && $key!= 'lang_path' && $key!= 'extAuthSource' && $key!= 'thisAuthSource' && $key!= 'main_configuration_file_path' && $key!= 'phpDigIncCn' && $key!= 'drs') {
-                $GLOBALS[$key]=$HTTP_SERVER_VARS[$key];
+            if (!isset($_SESSION[$key]) && $key != 'includePath' && $key != 'rootSys' && $key != 'lang_path' && $key != 'extAuthSource' && $key != 'thisAuthSource' && $key != 'main_configuration_file_path' && $key != 'phpDigIncCn' && $key != 'drs') {
+                $GLOBALS[$key] = $HTTP_SERVER_VARS[$key];
             }
         }
     }
@@ -542,7 +600,10 @@ $langpath = api_get_path(SYS_LANG_PATH);
 if (isset($this_script) && $this_script == 'sub_language') {
     require_once '../admin/sub_language.class.php';
     // getting the arrays of files i.e notification, trad4all, etc
-    $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(api_get_path(SYS_LANG_PATH).'english', true);
+    $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(
+        api_get_path(SYS_LANG_PATH).'english',
+        true
+    );
     //getting parent info
     $parent_language = SubLanguageManager::get_all_information_of_language($_REQUEST['id']);
     //getting sub language info
@@ -578,7 +639,7 @@ if (isset($this_script) && $this_script == 'sub_language') {
         $parent_language_array[$language_file_item] = compact($lang_list_result);
 
         //cleaning the variables
-        foreach($lang_list_result as $item) {
+        foreach ($lang_list_result as $item) {
             unset(${$item});
         }
 
@@ -591,7 +652,7 @@ if (isset($this_script) && $this_script == 'sub_language') {
         $sub_language_array[$language_file_item] = compact($lang_list_result);
 
         //cleaning the variables
-        foreach($lang_list_result as $item) {
+        foreach ($lang_list_result as $item) {
             unset(${$item});
         }
     }
@@ -611,35 +672,39 @@ if (!empty($valid_languages)) {
     $language_priority3 = api_get_setting('languagePriority3');
     $language_priority4 = api_get_setting('languagePriority4');
 
-    if (in_array($user_language, $valid_languages['folder']) && (isset($_GET['language']) || isset($_POST['language_list']))) {
+    if (in_array(
+        $user_language,
+        $valid_languages['folder']
+    ) && (isset($_GET['language']) || isset($_POST['language_list']))
+    ) {
         $user_selected_language = $user_language; // $_GET['language'];
         $_SESSION['user_language_choice'] = $user_selected_language;
         $platformLanguage = $user_selected_language;
     }
 
-    if (!empty($language_priority4) && api_get_language_from_type($language_priority4) !== false ) {
-        $language_interface =  api_get_language_from_type($language_priority4);
+    if (!empty($language_priority4) && api_get_language_from_type($language_priority4) !== false) {
+        $language_interface = api_get_language_from_type($language_priority4);
     } else {
         $language_interface = api_get_setting('platformLanguage');
     }
 
-    if (!empty($language_priority3) && api_get_language_from_type($language_priority3) !== false ) {
-        $language_interface =  api_get_language_from_type($language_priority3);
+    if (!empty($language_priority3) && api_get_language_from_type($language_priority3) !== false) {
+        $language_interface = api_get_language_from_type($language_priority3);
     } else {
         if (isset($_SESSION['user_language_choice'])) {
             $language_interface = $_SESSION['user_language_choice'];
         }
     }
 
-    if (!empty($language_priority2) && api_get_language_from_type($language_priority2) !== false ) {
-        $language_interface =  api_get_language_from_type($language_priority2);
+    if (!empty($language_priority2) && api_get_language_from_type($language_priority2) !== false) {
+        $language_interface = api_get_language_from_type($language_priority2);
     } else {
         if (isset($_user['language'])) {
             $language_interface = $_user['language'];
         }
     }
-    if (!empty($language_priority1) && api_get_language_from_type($language_priority1) !== false ) {
-        $language_interface =  api_get_language_from_type($language_priority1);
+    if (!empty($language_priority1) && api_get_language_from_type($language_priority1) !== false) {
+        $language_interface = api_get_language_from_type($language_priority1);
     } else {
         if ($_course['language']) {
             $language_interface = $_course['language'];
@@ -730,7 +795,7 @@ if (!isset($_SESSION['login_as']) && isset($_user)) {
         // is the latest logout_date still relevant?
         $sql_logout_date = "SELECT logout_date FROM $tbl_track_login WHERE login_id=$i_id_last_connection";
         $q_logout_date = Database::query($sql_logout_date);
-        $res_logout_date = convert_sql_date(Database::result($q_logout_date,0,'logout_date'));
+        $res_logout_date = convert_sql_date(Database::result($q_logout_date, 0, 'logout_date'));
 
         if ($res_logout_date < time() - $_configuration['session_lifetime']) {
             // it isn't, we should create a fresh entry

+ 224 - 62
main/inc/lib/announcements.inc.php

@@ -46,14 +46,15 @@ class AnnouncementManager
         $data['course_link'] = Display::url($course_link, $course_link);
 
         $content = str_replace(self::get_tags(), $data, $content);
+
         return $content;
     }
 
     /**
      * Gets all announcements from a course
-     * @param	string course db
-     * @param	int session id
-     * @return	array html with the content and count of announcements or false otherwise
+     * @param    string course db
+     * @param    int session id
+     * @return    array html with the content and count of announcements or false otherwise
      */
     public static function get_all_annoucement_by_course($course_info, $session_id = 0)
     {
@@ -79,15 +80,17 @@ class AnnouncementManager
             while ($row = Database::fetch_array($rs)) {
                 $list[] = $row;
             }
+
             return $list;
         }
+
         return false;
     }
 
     /**
      * This functions swithes the visibility a course resource
      * using the visibility field in 'item_property'
-     * @param    array	the course array
+     * @param    array    the course array
      * @param    int     ID of the element of the corresponding type
      * @return   bool    False on failure, True on success
      */
@@ -100,13 +103,14 @@ class AnnouncementManager
         } else {
             api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, 'visible', api_get_user_id());
         }
+
         return true;
     }
 
     /**
      * Deletes an announcement
      * @param array the course array
-     * @param int 	the announcement id
+     * @param int     the announcement id
      */
     public static function delete_announcement($_course, $id)
     {
@@ -159,14 +163,15 @@ class AnnouncementManager
             }
 
             if (api_get_user_id() != 0) {
-               $sql_query = "	SELECT announcement.*, toolitemproperties.*
+                $sql_query = "	SELECT announcement.*, toolitemproperties.*
     							FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
     							WHERE
                                     announcement.id = toolitemproperties.ref  AND
                                     announcement.id = '$announcement_id' AND
                                     toolitemproperties.tool='announcement' AND
                                     (
-                                        (toolitemproperties.to_user_id='".api_get_user_id()."'  AND toolitemproperties.to_group_id = ".api_get_group_id().") OR
+                                        (toolitemproperties.to_user_id='".api_get_user_id(
+                )."'  AND toolitemproperties.to_group_id = ".api_get_group_id().") OR
                                          toolitemproperties.to_group_id IN ('".api_get_group_id()."') AND toolitemproperties.to_user_id = 0
                                     ) AND
                                     $visibility_condition AND
@@ -197,7 +202,13 @@ class AnnouncementManager
             echo "<tr><td><h2>".$title."</h2></td></tr>";
 
             if (self::user_can_edit_announcement()) {
-                $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$announcement_id."\">".Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
+                $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq(
+                )."&action=modify&id=".$announcement_id."\">".Display::return_icon(
+                    'edit.png',
+                    get_lang('Edit'),
+                    '',
+                    ICON_SIZE_SMALL
+                )."</a>";
                 if ($result['visibility'] == 1) {
                     $image_visibility = "visible";
                     $alt_visibility = get_lang('Hide');
@@ -207,11 +218,17 @@ class AnnouncementManager
                 }
                 global $stok;
 
-                $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&origin=".(!empty($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : '')."&action=showhide&id=".$announcement_id."&sec_token=".$stok."\">".
+                $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq(
+                )."&origin=".(!empty($_GET['origin']) ? Security::remove_XSS(
+                    $_GET['origin']
+                ) : '')."&action=showhide&id=".$announcement_id."&sec_token=".$stok."\">".
                     Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
 
                 if (self::user_can_edit_announcement()) {
-                    $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=delete&id=".$announcement_id."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."')) return false;\">".
+                    $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq(
+                    )."&action=delete&id=".$announcement_id."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
+                        api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)
+                    )."')) return false;\">".
                         Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
                         "</a>";
                 }
@@ -220,7 +237,10 @@ class AnnouncementManager
 
             echo "<tr><td>$content</td></tr>";
 
-            echo "<tr><td class=\"announcements_datum\">".get_lang('LastUpdateDate')." : ".api_convert_and_format_date($result['insert_date'], DATE_TIME_FORMAT_LONG)."</td></tr>";
+            echo "<tr><td class=\"announcements_datum\">".get_lang('LastUpdateDate')." : ".api_convert_and_format_date(
+                $result['insert_date'],
+                DATE_TIME_FORMAT_LONG
+            )."</td></tr>";
 
             // User or group icon
             $sent_to_icon = '';
@@ -245,7 +265,11 @@ class AnnouncementManager
                 echo '<a href="'.$full_file_name.' "> '.$user_filename.' </a>';
                 echo ' - <span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
                 if (api_is_allowed_to_edit(false, true)) {
-                    echo Display::url(Display::return_icon('delete.png', get_lang('Delete'), '', 16), api_get_self()."?".api_get_cidreq()."&action=delete_attachment&id_attach=".$attachment_list['id']."&sec_token=".$stok);
+                    echo Display::url(
+                        Display::return_icon('delete.png', get_lang('Delete'), '', 16),
+                        api_get_self()."?".api_get_cidreq(
+                        )."&action=delete_attachment&id_attach=".$attachment_list['id']."&sec_token=".$stok
+                    );
                 }
                 echo '</td></tr>';
             }
@@ -267,6 +291,7 @@ class AnnouncementManager
             $row_max = Database::fetch_array($res_max);
             $order = intval($row_max[0]) + 1;
         }
+
         return $order;
     }
 
@@ -276,12 +301,18 @@ class AnnouncementManager
      * @param string    Content of the announcement (can be HTML)
      * @param int       Display order in the list of announcements
      * @param array     Array of users and groups to send the announcement to
-     * @param array	    uploaded file $_FILES
+     * @param array        uploaded file $_FILES
      * @param string    Comment describing the attachment
      * @return int      false on failure, ID of the announcement on success
      */
-    public static function add_announcement($emailTitle, $newContent, $sent_to, $file = array(), $file_comment = null, $end_date = null)
-    {
+    public static function add_announcement(
+        $emailTitle,
+        $newContent,
+        $sent_to,
+        $file = array(),
+        $file_comment = null,
+        $end_date = null
+    ) {
         global $_course;
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
 
@@ -324,29 +355,59 @@ class AnnouncementManager
                 // storing the selected groups
                 if (is_array($send_to['groups'])) {
                     foreach ($send_to['groups'] as $group) {
-                        api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), $group);
+                        api_item_property_update(
+                            $_course,
+                            TOOL_ANNOUNCEMENT,
+                            $last_id,
+                            "AnnouncementAdded",
+                            api_get_user_id(),
+                            $group
+                        );
                     }
                 }
 
                 // storing the selected users
                 if (is_array($send_to['users'])) {
                     foreach ($send_to['users'] as $user) {
-                        api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), '', $user);
+                        api_item_property_update(
+                            $_course,
+                            TOOL_ANNOUNCEMENT,
+                            $last_id,
+                            "AnnouncementAdded",
+                            api_get_user_id(),
+                            '',
+                            $user
+                        );
                     }
                 }
             } else {
                 // the message is sent to everyone, so we set the group to 0
-                api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), '0');
+                api_item_property_update(
+                    $_course,
+                    TOOL_ANNOUNCEMENT,
+                    $last_id,
+                    "AnnouncementAdded",
+                    api_get_user_id(),
+                    '0'
+                );
             }
+
             return $last_id;
         }
     }
+
     /*
       STORE ANNOUNCEMENT  GROUP ITEM
      */
 
-    public static function add_group_announcement($emailTitle, $newContent, $to, $to_users, $file = array(), $file_comment = '')
-    {
+    public static function add_group_announcement(
+        $emailTitle,
+        $newContent,
+        $to,
+        $to_users,
+        $file = array(),
+        $file_comment = ''
+    ) {
         global $_course;
 
         // database definitions
@@ -387,7 +448,14 @@ class AnnouncementManager
             // storing the selected groups
             if (is_array($send_to['groups'])) {
                 foreach ($send_to['groups'] as $group) {
-                    api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), $group);
+                    api_item_property_update(
+                        $_course,
+                        TOOL_ANNOUNCEMENT,
+                        $last_id,
+                        "AnnouncementAdded",
+                        api_get_user_id(),
+                        $group
+                    );
                 }
             }
         } else {
@@ -395,12 +463,22 @@ class AnnouncementManager
             // storing the selected users
             if (is_array($to_users)) {
                 foreach ($to_users as $user) {
-                    api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), api_get_group_id(), $user);
+                    api_item_property_update(
+                        $_course,
+                        TOOL_ANNOUNCEMENT,
+                        $last_id,
+                        "AnnouncementAdded",
+                        api_get_user_id(),
+                        api_get_group_id(),
+                        $user
+                    );
                 }
             }
         }
+
         return $last_id;
     }
+
     /*
       EDIT ANNOUNCEMENT
      */
@@ -409,11 +487,11 @@ class AnnouncementManager
      * This function stores the announcement item in the announcement table
      * and updates the item_property table
      *
-     * @param int 	id of the announcement
+     * @param int     id of the announcement
      * @param string email
      * @param string content
-     * @param array 	users that will receive the announcement
-     * @param mixed 	attachment
+     * @param array     users that will receive the announcement
+     * @param mixed     attachment
      * @param string file comment
      *
      */
@@ -459,13 +537,28 @@ class AnnouncementManager
             // storing the selected groups
             if (is_array($send_to['groups'])) {
                 foreach ($send_to['groups'] as $group) {
-                    api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, "AnnouncementUpdated", api_get_user_id(), $group);
+                    api_item_property_update(
+                        $_course,
+                        TOOL_ANNOUNCEMENT,
+                        $id,
+                        "AnnouncementUpdated",
+                        api_get_user_id(),
+                        $group
+                    );
                 }
             }
             // storing the selected users
             if (is_array($send_to['users'])) {
                 foreach ($send_to['users'] as $user) {
-                    api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, "AnnouncementUpdated", api_get_user_id(), 0, $user);
+                    api_item_property_update(
+                        $_course,
+                        TOOL_ANNOUNCEMENT,
+                        $id,
+                        "AnnouncementUpdated",
+                        api_get_user_id(),
+                        0,
+                        $user
+                    );
                 }
             }
         } else {
@@ -473,6 +566,7 @@ class AnnouncementManager
             api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, "AnnouncementUpdated", api_get_user_id(), '0');
         }
     }
+
     /*
       MAIL FUNCTIONS
      */
@@ -492,9 +586,9 @@ class AnnouncementManager
 
     /**
      * Gets all announcements from a user by course
-     * @param	string course db
-     * @param	int user id
-     * @return	array html with the content and count of announcements or false otherwise
+     * @param    string course db
+     * @param    int user id
+     * @return    array html with the content and count of announcements or false otherwise
      */
     public static function get_all_annoucement_by_user_course($course_code, $user_id)
     {
@@ -527,18 +621,22 @@ class AnnouncementManager
             $result = array();
             if ($num_rows > 0) {
                 while ($myrow = Database::fetch_array($rs)) {
-                    $content.= '<strong>'.$myrow['title'].'</strong><br /><br />';
-                    $content.= $myrow['content'];
+                    $content .= '<strong>'.$myrow['title'].'</strong><br /><br />';
+                    $content .= $myrow['content'];
                     $i++;
                 }
                 $result['content'] = $content;
                 $result['count'] = $i;
+
                 return $result;
             }
+
             return false;
         }
+
         return false;
     }
+
     /*
       SHOW_TO_FORM
      */
@@ -594,7 +692,10 @@ class AnnouncementManager
         echo "<td>";
         echo "<select name=\"not_selected_form[]\" size=5 class=\"span4\" multiple>";
         foreach ($group_users as $user) {
-            echo '<option value="'.$user['user_id'].'" title="'.sprintf(get_lang('LoginX'), $user['username']).'" >'.api_get_person_name($user['firstname'], $user['lastname']).'</option>';
+            echo '<option value="'.$user['user_id'].'" title="'.sprintf(
+                get_lang('LoginX'),
+                $user['username']
+            ).'" >'.api_get_person_name($user['firstname'], $user['lastname']).'</option>';
         }
         echo '</select>';
         echo "</td>";
@@ -613,7 +714,10 @@ class AnnouncementManager
                 $user = explode(':', $user);
                 if ($user[0] == 'USER') {
                     $user = api_get_user_info($user[1]);
-                    echo '<option value="'.$user['user_id'].'" title="'.sprintf(get_lang('LoginX'), $user['username']).'" >'.api_get_person_name($user['firstname'], $user['lastname']).'</option>';
+                    echo '<option value="'.$user['user_id'].'" title="'.sprintf(
+                        get_lang('LoginX'),
+                        $user['username']
+                    ).'" >'.api_get_person_name($user['firstname'], $user['lastname']).'</option>';
                 }
             }
         }
@@ -631,20 +735,27 @@ class AnnouncementManager
     /**
      * this function shows the form for sending a message to a specific group or user.
      */
-    public static function construct_not_selected_select_form($group_list = null, $user_list = null, $to_already_selected)
-    {
+    public static function construct_not_selected_select_form(
+        $group_list = null,
+        $user_list = null,
+        $to_already_selected
+    ) {
 
         echo '<select name="not_selected_form[]" size="7" class="span4" multiple>';
         // adding the groups to the select form
         if ($group_list) {
             foreach ($group_list as $this_group) {
                 if (is_array($to_already_selected)) {
-                    if (!in_array("GROUP:".$this_group['id'], $to_already_selected)) { // $to_already_selected is the array containing the groups (and users) that are already selected
+                    if (!in_array(
+                        "GROUP:".$this_group['id'],
+                        $to_already_selected
+                    )
+                    ) { // $to_already_selected is the array containing the groups (and users) that are already selected
                         $user_label = ($this_group['userNb'] > 0) ? get_lang('Users') : get_lang('LowerCaseUser');
                         $user_disabled = ($this_group['userNb'] > 0) ? "" : "disabled=disabled";
                         echo "<option $user_disabled value=\"GROUP:".$this_group['id']."\">",
                         "G: ", $this_group['name'], " - ".$this_group['userNb']." ".$user_label.
-                        "</option>";
+                            "</option>";
                     }
                 }
             }
@@ -655,8 +766,15 @@ class AnnouncementManager
         if ($user_list) {
             foreach ($user_list as $this_user) {
                 if (is_array($to_already_selected)) {
-                    if (!in_array("USER:".$this_user['user_id'], $to_already_selected)) { // $to_already_selected is the array containing the users (and groups) that are already selected
-                        echo "<option value=\"USER:".$this_user['user_id']."\" title='".sprintf(get_lang('LoginX'), $this_user['username'])."'>",
+                    if (!in_array(
+                        "USER:".$this_user['user_id'],
+                        $to_already_selected
+                    )
+                    ) { // $to_already_selected is the array containing the users (and groups) that are already selected
+                        echo "<option value=\"USER:".$this_user['user_id']."\" title='".sprintf(
+                            get_lang('LoginX'),
+                            $this_user['username']
+                        )."'>",
                         "", api_get_person_name($this_user['firstname'], $this_user['lastname']),
                         "</option>";
                     }
@@ -665,6 +783,7 @@ class AnnouncementManager
         }
         echo "</select>";
     }
+
     /*
       CONSTRUCT_SELECTED_SELECT_FORM
      */
@@ -697,7 +816,10 @@ class AnnouncementManager
                 } else {
                     foreach ($ref_array_users as $key => $value) {
                         if ($value['user_id'] == $id) {
-                            echo "<option value=\"".$groupuser."\" title='".sprintf(get_lang('LoginX'), $value['username'])."'>".api_get_person_name($value['firstname'], $value['lastname'])."</option>";
+                            echo "<option value=\"".$groupuser."\" title='".sprintf(
+                                get_lang('LoginX'),
+                                $value['username']
+                            )."'>".api_get_person_name($value['firstname'], $value['lastname'])."</option>";
                             break;
                         }
                     }
@@ -709,17 +831,28 @@ class AnnouncementManager
                 if (is_array($ref_array_groups)) {
                     foreach ($ref_array_groups as $this_group) {
                         //api_display_normal_message("group " . $thisGroup[id] . $thisGroup[name]);
-                        if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'], $to_already_selected)) { // $to_already_selected is the array containing the groups (and users) that are already selected
+                        if (!is_array($to_already_selected) || !in_array(
+                            "GROUP:".$this_group['id'],
+                            $to_already_selected
+                        )
+                        ) { // $to_already_selected is the array containing the groups (and users) that are already selected
                             echo "<option value=\"GROUP:".$this_group['id']."\">",
                             "G: ", $this_group['name'], " &ndash; ".$this_group['userNb']." ".get_lang('Users').
-                            "</option>";
+                                "</option>";
                         }
                     }
                 }
                 // adding the individual users to the select form
                 foreach ($ref_array_users as $this_user) {
-                    if (!is_array($to_already_selected) || !in_array("USER:".$this_user['user_id'], $to_already_selected)) { // $to_already_selected is the array containing the users (and groups) that are already selected
-                        echo "<option value=\"USER:", $this_user['user_id'], "\"  title='".sprintf(get_lang('LoginX'), $user['username'])."'>",
+                    if (!is_array($to_already_selected) || !in_array(
+                        "USER:".$this_user['user_id'],
+                        $to_already_selected
+                    )
+                    ) { // $to_already_selected is the array containing the users (and groups) that are already selected
+                        echo "<option value=\"USER:", $this_user['user_id'], "\"  title='".sprintf(
+                            get_lang('LoginX'),
+                            $user['username']
+                        )."'>",
                         "", api_get_person_name($this_user['firstname'], $this_user['lastname']),
                         "</option>";
                     }
@@ -728,6 +861,7 @@ class AnnouncementManager
         }
         echo "</select>";
     }
+
     /*
       DATA FUNCTIONS
      */
@@ -758,6 +892,7 @@ class AnnouncementManager
         if (Database::num_rows($result)) {
             return Database::fetch_array($result);
         }
+
         return array();
     }
 
@@ -791,8 +926,10 @@ class AnnouncementManager
         } else {
             $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), 0, 1);
         }
+
         return $new_group_list;
     }
+
     /*
      *
       LOAD_EDIT_USERS
@@ -831,8 +968,10 @@ class AnnouncementManager
                 $to[] = "USER:".$to_user;
             }
         }
+
         return $to;
     }
+
     /*
       USER_GROUP_FILTER_JAVASCRIPT
      */
@@ -853,6 +992,7 @@ class AnnouncementManager
 		//-->
 		</script>";
     }
+
     /*
       TO_JAVASCRIPT
      */
@@ -878,19 +1018,21 @@ class AnnouncementManager
         $code = "var www = '$root';\n";
         $code .= Javascript::get_lang('FieldRequired', 'Send2All', 'AddAnAttachment', 'Everybody');
         $result .= Javascript::tag_code($code);
+
         return $result;
     }
+
     /*
       SENT_TO_FORM
      */
 
     /**
      * constructs the form to display all the groups and users the message has been sent to
-     * input: 	$sent_to_array is a 2 dimensional array containing the groups and the users
-     * 			the first level is a distinction between groups and users:
-     * 			$sent_to_array['groups'] * and $sent_to_array['users']
-     * 			$sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
-     * 			containing all the id's of the groups (resp. users) who have received this message.
+     * input:     $sent_to_array is a 2 dimensional array containing the groups and the users
+     *             the first level is a distinction between groups and users:
+     *             $sent_to_array['groups'] * and $sent_to_array['users']
+     *             $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
+     *             containing all the id's of the groups (resp. users) who have received this message.
      * @author Patrick Cool <patrick.cool@>
      */
     public static function sent_to_form($sent_to_array)
@@ -935,7 +1077,10 @@ class AnnouncementManager
                 $user_info = api_get_user_info($sent_to_array['users'][0]);
                 $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
             }
-            if (isset($sent_to_array['groups']) and is_array($sent_to_array['groups']) and isset($sent_to_array['groups'][0]) and $sent_to_array['groups'][0] !== 0) {
+            if (isset($sent_to_array['groups']) and is_array(
+                $sent_to_array['groups']
+            ) and isset($sent_to_array['groups'][0]) and $sent_to_array['groups'][0] !== 0
+            ) {
                 $group_id = $sent_to_array['groups'][0];
                 $output[] = "&nbsp;".$group_names[$group_id]['name'];
             }
@@ -945,13 +1090,13 @@ class AnnouncementManager
         }
 
 
-
         if (!empty($output)) {
             $output = array_filter($output);
 
             if (count($output) > 0) {
                 $output = implode(', ', $output);
             }
+
             return $output;
         }
     }
@@ -985,8 +1130,10 @@ class AnnouncementManager
 
         $send_to['groups'] = $grouplist;
         $send_to['users'] = $userlist;
+
         return $send_to;
     }
+
     /*
       SENT_TO()
      */
@@ -1031,8 +1178,10 @@ class AnnouncementManager
         if (isset($sent_to_user)) {
             $sent_to['users'] = $sent_to_user;
         }
+
         return $sent_to;
     }
+
     /* 		ATTACHMENT FUNCTIONS	 */
 
     /**
@@ -1054,6 +1203,7 @@ class AnnouncementManager
         if (Database::num_rows($result) != 0) {
             $row = Database::fetch_array($result, 'ASSOC');
         }
+
         return $row;
     }
 
@@ -1078,11 +1228,11 @@ class AnnouncementManager
             $updir = $sys_course_path.$courseDir;
 
             // Try to add an extension to the file if it hasn't one
-            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
+            $new_file_name = FileManager::add_ext_on_mime(stripslashes($file['name']), $file['type']);
             // user's file name
             $file_name = $file['name'];
 
-            if (!filter_extension($new_file_name)) {
+            if (!FileManager::filter_extension($new_file_name)) {
                 $return = -1;
                 Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
             } else {
@@ -1094,11 +1244,14 @@ class AnnouncementManager
                 $safe_new_file_name = Database::escape_string($new_file_name);
                 // Storing the attachments if any
                 $sql = "INSERT INTO $tbl_announcement_attachment (c_id, filename, comment, path, announcement_id, size) VALUES
-                        ($course_id, '$safe_file_name', '$file_comment', '$safe_new_file_name' , '$announcement_id', '".intval($file['size'])."' )";
+                        ($course_id, '$safe_file_name', '$file_comment', '$safe_new_file_name' , '$announcement_id', '".intval(
+                    $file['size']
+                )."' )";
                 Database::query($sql);
                 $return = 1;
             }
         }
+
         return $return;
     }
 
@@ -1122,11 +1275,11 @@ class AnnouncementManager
             $updir = $sys_course_path.$courseDir;
 
             // Try to add an extension to the file if it hasn't one
-            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
+            $new_file_name = FileManager::add_ext_on_mime(stripslashes($file['name']), $file['type']);
             // user's file name
             $file_name = $file ['name'];
 
-            if (!filter_extension($new_file_name)) {
+            if (!FileManager::filter_extension($new_file_name)) {
                 $return - 1;
                 Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
             } else {
@@ -1137,7 +1290,9 @@ class AnnouncementManager
                 $safe_file_name = Database::escape_string($file_name);
                 $safe_new_file_name = Database::escape_string($new_file_name);
                 $id_attach = intval($id_attach);
-                $sql = "UPDATE $tbl_announcement_attachment SET filename = '$safe_file_name', comment = '$safe_file_comment', path = '$safe_new_file_name', size ='".intval($file['size'])."'
+                $sql = "UPDATE $tbl_announcement_attachment SET filename = '$safe_file_name', comment = '$safe_file_comment', path = '$safe_new_file_name', size ='".intval(
+                    $file['size']
+                )."'
 					 	WHERE c_id = $course_id AND id = '$id_attach'";
                 $result = Database::query($sql);
                 if ($result === false) {
@@ -1148,6 +1303,7 @@ class AnnouncementManager
                 }
             }
         }
+
         return $return;
     }
 
@@ -1173,11 +1329,17 @@ class AnnouncementManager
         $email->send();
     }
 
-    public static function user_can_edit_announcement() {
+    public static function user_can_edit_announcement()
+    {
         $group_id = api_get_group_id();
-        return  api_is_allowed_to_edit(false, true) OR
-                (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) OR
-                (!empty($group_id) AND GroupManager::user_has_access(api_get_user_id(), $group_id, GroupManager::GROUP_TOOL_ANNOUNCEMENT) AND GroupManager::is_tutor_of_group(api_get_user_id(), $group_id));
+
+        return api_is_allowed_to_edit(false, true) OR
+            (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) OR
+            (!empty($group_id) AND GroupManager::user_has_access(
+                api_get_user_id(),
+                $group_id,
+                GroupManager::GROUP_TOOL_ANNOUNCEMENT
+            ) AND GroupManager::is_tutor_of_group(api_get_user_id(), $group_id));
 
     }
 }

Fișier diff suprimat deoarece este prea mare
+ 637 - 546
main/inc/lib/blog.lib.php


Fișier diff suprimat deoarece este prea mare
+ 313 - 212
main/inc/lib/document.lib.php


+ 293 - 312
main/inc/lib/fckeditor/editor/filemanager/connectors/php/commands.php

@@ -22,327 +22,308 @@
  * This is the File Manager Connector for PHP.
  */
 
-function GetFolders( $resourceType, $currentFolder )
+function GetFolders($resourceType, $currentFolder)
 {
-	// Map the virtual path to the local server path.
-	$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFolders' ) ;
-
-	// Array that will hold the folders names.
-	$aFolders	= array() ;
-
-	$oCurrentFolder = @opendir( $sServerDir ) ;
-
-	$in_group = api_is_in_group();
-	if($currentFolder=='/shared_folder/' || $currentFolder =='/shared_folder_session_'.api_get_session_id().'/')
-	{
-		$in_shared_folder=true;
-	}
-	else
-	{
-		$in_shared_folder=false;
-	}	
-	$user_id = api_get_user_id();
-
-	if ($oCurrentFolder !== false)
-	{
-		while ( $sFile = readdir( $oCurrentFolder ) )
-		{
-			if ( $sFile != '.' && $sFile != '..'
-				&& strpos( $sFile, '_DELETED_' ) === false
-				&& strpos( $sFile, 'chat_files' ) === false
-				&& strpos( $sFile, 'HotPotatoes_files' ) === false
-				&& ( $in_group || ( !$in_group && strpos( $sFile, '_groupdocs' ) === false ) )
-				&& (!$in_shared_folder || ($in_shared_folder && $sFile == 'sf_user_'.$user_id))
-				&& $sFile != '.thumbs'
-				&& $sFile != '.svn'
-				&& is_dir( $sServerDir . $sFile ) )
-			{
-				$aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) . '" />' ;
-			}
-		}
-		closedir( $oCurrentFolder ) ;
-	}
-
-	// Open the "Folders" node.
-	echo "<Folders>" ;
-
-	natcasesort( $aFolders ) ;
-	foreach ( $aFolders as $sFolder )
-		echo $sFolder ;
-
-	// Close the "Folders" node.
-	echo "</Folders>" ;
+    // Map the virtual path to the local server path.
+    $sServerDir = ServerMapFolder($resourceType, $currentFolder, 'GetFolders');
+
+    // Array that will hold the folders names.
+    $aFolders = array();
+
+    $oCurrentFolder = @opendir($sServerDir);
+
+    $in_group = api_is_in_group();
+    if ($currentFolder == '/shared_folder/' || $currentFolder == '/shared_folder_session_'.api_get_session_id().'/') {
+        $in_shared_folder = true;
+    } else {
+        $in_shared_folder = false;
+    }
+    $user_id = api_get_user_id();
+
+    if ($oCurrentFolder !== false) {
+        while ($sFile = readdir($oCurrentFolder)) {
+            if ($sFile != '.' && $sFile != '..'
+                && strpos($sFile, '_DELETED_') === false
+                && strpos($sFile, 'chat_files') === false
+                && strpos($sFile, 'HotPotatoes_files') === false
+                && ($in_group || (!$in_group && strpos($sFile, '_groupdocs') === false))
+                && (!$in_shared_folder || ($in_shared_folder && $sFile == 'sf_user_'.$user_id))
+                && $sFile != '.thumbs'
+                && $sFile != '.svn'
+                && is_dir($sServerDir.$sFile)
+            ) {
+                $aFolders[] = '<Folder name="'.ConvertToXmlAttribute($sFile).'" />';
+            }
+        }
+        closedir($oCurrentFolder);
+    }
+
+    // Open the "Folders" node.
+    echo "<Folders>";
+
+    natcasesort($aFolders);
+    foreach ($aFolders as $sFolder) {
+        echo $sFolder;
+    }
+
+    // Close the "Folders" node.
+    echo "</Folders>";
 }
 
-function GetFoldersAndFiles( $resourceType, $currentFolder )
+function GetFoldersAndFiles($resourceType, $currentFolder)
 {
-	// Map the virtual path to the local server path.
-	$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFoldersAndFiles' ) ;
-
-	// Arrays that will hold the folders and files names.
-	$aFolders	= array() ;
-	$aFiles		= array() ;
-
-	$oCurrentFolder = @opendir( $sServerDir ) ;
-
-	$in_group = api_is_in_group();
-	
-	if($currentFolder=='/shared_folder/' || $currentFolder =='/shared_folder_session_'.api_get_session_id().'/')
-	{
-		$in_shared_folder=true;
-	}
-	else
-	{
-		$in_shared_folder=false;
-	}	
-	
-	$user_id = api_get_user_id();
-
-	if ($oCurrentFolder !== false)
-	{
-		while ( $sFile = readdir( $oCurrentFolder ) )
-		{
-			$is_dir = @is_dir( $sServerDir . $sFile );
-			if ( $sFile != '.' && $sFile != '..'
-				&& strpos( $sFile, '_DELETED_' ) === false
-				&& strpos( $sFile, 'chat_files' ) === false
-				&& strpos( $sFile, 'HotPotatoes_files' ) === false
-				&& ( $in_group || ( !$in_group && strpos( $sFile, '_groupdocs' ) === false ) )
-				&& (!$in_shared_folder || ($in_shared_folder && (!$is_dir || ($is_dir && $sFile == $user_id))))
-				&& $sFile != '.thumbs'
-				&& strpos( $sFile, '.editor_' ) === false
-				&& $sFile != '.svn' )
-			{
-				if ( $is_dir )
-					$aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) . '" />' ;
-				else
-				{
-					$iFileSize = @filesize( $sServerDir . $sFile ) ;
-					if ( !$iFileSize ) {
-						$iFileSize = 0 ;
-					}
-					if ( $iFileSize > 0 )
-					{
-						$iFileSize = round( $iFileSize / 1024 ) ;
-						if ( $iFileSize < 1 ) $iFileSize = 1 ;
-					}
-
-					$aFiles[] = '<File name="' . ConvertToXmlAttribute( $sFile ) . '" size="' . $iFileSize . '" />' ;
-				}
-			}
-		}
-		closedir( $oCurrentFolder ) ;
-	}
-
-	// Send the folders
-	natcasesort( $aFolders ) ;
-	echo '<Folders>' ;
-
-	foreach ( $aFolders as $sFolder )
-		echo $sFolder ;
-
-	echo '</Folders>' ;
-
-	// Send the files
-	natcasesort( $aFiles ) ;
-	echo '<Files>' ;
-
-	foreach ( $aFiles as $sFiles )
-		echo $sFiles ;
-
-	echo '</Files>' ;
+    // Map the virtual path to the local server path.
+    $sServerDir = ServerMapFolder($resourceType, $currentFolder, 'GetFoldersAndFiles');
+
+    // Arrays that will hold the folders and files names.
+    $aFolders = array();
+    $aFiles = array();
+
+    $oCurrentFolder = @opendir($sServerDir);
+
+    $in_group = api_is_in_group();
+
+    if ($currentFolder == '/shared_folder/' || $currentFolder == '/shared_folder_session_'.api_get_session_id().'/') {
+        $in_shared_folder = true;
+    } else {
+        $in_shared_folder = false;
+    }
+
+    $user_id = api_get_user_id();
+
+    if ($oCurrentFolder !== false) {
+        while ($sFile = readdir($oCurrentFolder)) {
+            $is_dir = @is_dir($sServerDir.$sFile);
+            if ($sFile != '.' && $sFile != '..'
+                && strpos($sFile, '_DELETED_') === false
+                && strpos($sFile, 'chat_files') === false
+                && strpos($sFile, 'HotPotatoes_files') === false
+                && ($in_group || (!$in_group && strpos($sFile, '_groupdocs') === false))
+                && (!$in_shared_folder || ($in_shared_folder && (!$is_dir || ($is_dir && $sFile == $user_id))))
+                && $sFile != '.thumbs'
+                && strpos($sFile, '.editor_') === false
+                && $sFile != '.svn'
+            ) {
+                if ($is_dir) {
+                    $aFolders[] = '<Folder name="'.ConvertToXmlAttribute($sFile).'" />';
+                } else {
+                    $iFileSize = @filesize($sServerDir.$sFile);
+                    if (!$iFileSize) {
+                        $iFileSize = 0;
+                    }
+                    if ($iFileSize > 0) {
+                        $iFileSize = round($iFileSize / 1024);
+                        if ($iFileSize < 1) {
+                            $iFileSize = 1;
+                        }
+                    }
+
+                    $aFiles[] = '<File name="'.ConvertToXmlAttribute($sFile).'" size="'.$iFileSize.'" />';
+                }
+            }
+        }
+        closedir($oCurrentFolder);
+    }
+
+    // Send the folders
+    natcasesort($aFolders);
+    echo '<Folders>';
+
+    foreach ($aFolders as $sFolder) {
+        echo $sFolder;
+    }
+
+    echo '</Folders>';
+
+    // Send the files
+    natcasesort($aFiles);
+    echo '<Files>';
+
+    foreach ($aFiles as $sFiles) {
+        echo $sFiles;
+    }
+
+    echo '</Files>';
 }
 
-function CreateFolder( $resourceType, $currentFolder )
+function CreateFolder($resourceType, $currentFolder)
 {
-	if (!isset($_GET)) {
-		global $_GET;
-	}
-	$sErrorNumber	= '0' ;
-	$sErrorMsg		= '' ;
-
-	if ( isset( $_GET['NewFolderName'] ) )
-	{
-		$sNewFolderName = $_GET['NewFolderName'] ;
-		$sNewFolderName = SanitizeFolderName( $sNewFolderName ) ;
-
-		if ( strpos( $sNewFolderName, '..' ) !== FALSE )
-			$sErrorNumber = '102' ;		// Invalid folder name.
-		else
-		{
-			// Map the virtual path to the local server path of the current folder.
-			$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'CreateFolder' ) ;
-
-			if ( is_writable( $sServerDir ) )
-			{
-				$sServerDir .= $sNewFolderName ;
-
-				$sErrorMsg = CreateServerFolder( $sServerDir ) ;
-
-				switch ( $sErrorMsg )
-				{
-					case '' :
-						$sErrorNumber = '0' ;
-						break ;
-					case 'Invalid argument' :
-					case 'No such file or directory' :
-						$sErrorNumber = '102' ;		// Path too long.
-						break ;
-					default :
-						$sErrorNumber = '110' ;
-						break ;
-				}
-			}
-			else
-				$sErrorNumber = '103' ;
-		}
-	}
-	else
-		$sErrorNumber = '102' ;
-
-	// Create the "Error" node.
-	echo '<Error number="' . $sErrorNumber . '" />' ;
+    if (!isset($_GET)) {
+        global $_GET;
+    }
+    $sErrorNumber = '0';
+    $sErrorMsg = '';
+
+    if (isset($_GET['NewFolderName'])) {
+        $sNewFolderName = $_GET['NewFolderName'];
+        $sNewFolderName = SanitizeFolderName($sNewFolderName);
+
+        if (strpos($sNewFolderName, '..') !== false) {
+            $sErrorNumber = '102';
+        } // Invalid folder name.
+        else {
+            // Map the virtual path to the local server path of the current folder.
+            $sServerDir = ServerMapFolder($resourceType, $currentFolder, 'CreateFolder');
+
+            if (is_writable($sServerDir)) {
+                $sServerDir .= $sNewFolderName;
+
+                $sErrorMsg = CreateServerFolder($sServerDir);
+
+                switch ($sErrorMsg) {
+                    case '' :
+                        $sErrorNumber = '0';
+                        break;
+                    case 'Invalid argument' :
+                    case 'No such file or directory' :
+                        $sErrorNumber = '102'; // Path too long.
+                        break;
+                    default :
+                        $sErrorNumber = '110';
+                        break;
+                }
+            } else {
+                $sErrorNumber = '103';
+            }
+        }
+    } else {
+        $sErrorNumber = '102';
+    }
+
+    // Create the "Error" node.
+    echo '<Error number="'.$sErrorNumber.'" />';
 }
 
-function FileUpload( $resourceType, $currentFolder, $sCommand )
+function FileUpload($resourceType, $currentFolder, $sCommand)
 {
-	if (!isset($_FILES)) {
-		global $_FILES;
-	}
-	$sErrorNumber = '0' ;
-	$sFileName = '' ;
-
-	if ( isset( $_FILES['NewFile'] ) && !is_null( $_FILES['NewFile']['tmp_name'] ) )
-	{
-		global $Config ;
-
-		$oFile = $_FILES['NewFile'] ;
-
-		// Map the virtual path to the local server path.
-		$sServerDir = ServerMapFolder( $resourceType, $currentFolder, $sCommand ) ;
-
-		// Get the uploaded file name.
-		$sFileName = $oFile['name'] ;
-		$sFileName = SanitizeFileName( $sFileName, $oFile['type'] ) ;
-
-		$sOriginalFileName = $sFileName ;
-
-		// Get the extension.
-		$sExtension = substr( $sFileName, ( strrpos($sFileName, '.') + 1 ) ) ;
-		$sExtension = strtolower( $sExtension ) ;
-
-		if ( isset( $Config['SecureImageUploads'] ) )
-		{
-			if ( ( $isImageValid = IsImageValid( $oFile['tmp_name'], $sExtension ) ) === false )
-			{
-				$sErrorNumber = '202' ;
-			}
-		}
-
-		if ( isset( $Config['HtmlExtensions'] ) )
-		{
-			if ( !IsHtmlExtension( $sExtension, $Config['HtmlExtensions'] ) &&
-				( $detectHtml = DetectHtml( $oFile['tmp_name'] ) ) === true )
-			{
-				$sErrorNumber = '202' ;
-			}
-		}
-
-		// Check if it is an allowed extension.
-		if ( !$sErrorNumber && IsAllowedExt( $sExtension, $resourceType ) )
-		{
-			$iCounter = 0 ;
-
-			while ( true )
-			{
-				$sFilePath = $sServerDir . $sFileName ;
-
-				if ( is_file( $sFilePath ) )
-				{
-					$iCounter++ ;
-					$sFileName = RemoveExtension( $sOriginalFileName ) . '(' . $iCounter . ').' . $sExtension ;
-					$sErrorNumber = '0' ; // Change $sErrorNumber '201' to '0' to allow create record files renamed
-				}
-				else
-				{
-					move_uploaded_file( $oFile['tmp_name'], $sFilePath ) ;
-
-					if ( is_file( $sFilePath ) )
-					{
-						if ( isset( $Config['ChmodOnUpload'] ) && !$Config['ChmodOnUpload'] )
-						{
-							break ;
-						}
-
-						$permissions = 0777;
-
-						if ( isset( $Config['ChmodOnUpload'] ) && $Config['ChmodOnUpload'] )
-						{
-							$permissions = $Config['ChmodOnUpload'] ;
-						}
-
-						//$oldumask = umask(0) ;
-						chmod( $sFilePath, $permissions ) ;
-						//umask( $oldumask ) ;
-					}
-
-					break ;
-				}
-			}
-
-			if ( file_exists( $sFilePath ) )
-			{
-				//previous checks failed, try once again
-				if ( isset( $isImageValid ) && $isImageValid === -1 && IsImageValid( $sFilePath, $sExtension ) === false )
-				{
-					@unlink( $sFilePath ) ;
-					$sErrorNumber = '202' ;
-				}
-				else if ( isset( $detectHtml ) && $detectHtml === -1 && DetectHtml( $sFilePath ) === true )
-				{
-					@unlink( $sFilePath ) ;
-					$sErrorNumber = '202' ;
-				}
-			}
-		}
-		else
-			$sErrorNumber = '202' ;
-	}
-	else
-		$sErrorNumber = '202' ;
-	if ($sErrorNumber == '0')
-	{
-		// While we are in a course: Registering the newly uploaded file in the course's database.
-		if (api_is_in_course())
-		{
-			global $_course, $_user;
-			$repository_path = api_get_path(REL_COURSE_PATH).api_get_course_path().'/document/';
-			$to_group_id = 0;
-
-			if (api_is_in_group())
-			{
-				global $group_properties;
-				$to_group_id = $group_properties['id'];
-			}
-			if ( file_exists( $sFilePath ) ) {
-				$file_path = substr($sFilePath, strpos($sFilePath, $repository_path) + strlen($repository_path) - 1);
-				$path = explode('/', $file_path);
-				$file_name = $path[count($path) - 1];
-				$path[count($path) - 1] = '';
-				$folder_path = '/' + implode('/', $path);
-				$file_size = @filesize($sFilePath);
-				$doc_id = add_document($_course, $file_path, 'file', $file_size, $file_name);
-				api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $to_group_id);
-				item_property_update_on_folder($_course, $folder_path, $_user['user_id']);
-			}
-		}
-	}
-
-	$sFileUrl = CombinePaths( GetResourceTypePath( $resourceType, $sCommand ) , $currentFolder ) ;
-	$sFileUrl = CombinePaths( $sFileUrl, $sFileName ) ;
-
-	SendUploadResults( $sErrorNumber, $sFileUrl, $sFileName ) ;
-
-	exit ;
+    if (!isset($_FILES)) {
+        global $_FILES;
+    }
+    $sErrorNumber = '0';
+    $sFileName = '';
+
+    if (isset($_FILES['NewFile']) && !is_null($_FILES['NewFile']['tmp_name'])) {
+        global $Config;
+
+        $oFile = $_FILES['NewFile'];
+
+        // Map the virtual path to the local server path.
+        $sServerDir = ServerMapFolder($resourceType, $currentFolder, $sCommand);
+
+        // Get the uploaded file name.
+        $sFileName = $oFile['name'];
+        $sFileName = SanitizeFileName($sFileName, $oFile['type']);
+
+        $sOriginalFileName = $sFileName;
+
+        // Get the extension.
+        $sExtension = substr($sFileName, (strrpos($sFileName, '.') + 1));
+        $sExtension = strtolower($sExtension);
+
+        if (isset($Config['SecureImageUploads'])) {
+            if (($isImageValid = IsImageValid($oFile['tmp_name'], $sExtension)) === false) {
+                $sErrorNumber = '202';
+            }
+        }
+
+        if (isset($Config['HtmlExtensions'])) {
+            if (!IsHtmlExtension($sExtension, $Config['HtmlExtensions']) &&
+                ($detectHtml = DetectHtml($oFile['tmp_name'])) === true
+            ) {
+                $sErrorNumber = '202';
+            }
+        }
+
+        // Check if it is an allowed extension.
+        if (!$sErrorNumber && IsAllowedExt($sExtension, $resourceType)) {
+            $iCounter = 0;
+
+            while (true) {
+                $sFilePath = $sServerDir.$sFileName;
+
+                if (is_file($sFilePath)) {
+                    $iCounter++;
+                    $sFileName = RemoveExtension($sOriginalFileName).'('.$iCounter.').'.$sExtension;
+                    $sErrorNumber = '0'; // Change $sErrorNumber '201' to '0' to allow create record files renamed
+                } else {
+                    move_uploaded_file($oFile['tmp_name'], $sFilePath);
+
+                    if (is_file($sFilePath)) {
+                        if (isset($Config['ChmodOnUpload']) && !$Config['ChmodOnUpload']) {
+                            break;
+                        }
+
+                        $permissions = 0777;
+
+                        if (isset($Config['ChmodOnUpload']) && $Config['ChmodOnUpload']) {
+                            $permissions = $Config['ChmodOnUpload'];
+                        }
+
+                        //$oldumask = umask(0) ;
+                        chmod($sFilePath, $permissions);
+                        //umask( $oldumask ) ;
+                    }
+
+                    break;
+                }
+            }
+
+            if (file_exists($sFilePath)) {
+                //previous checks failed, try once again
+                if (isset($isImageValid) && $isImageValid === -1 && IsImageValid($sFilePath, $sExtension) === false) {
+                    @unlink($sFilePath);
+                    $sErrorNumber = '202';
+                } else {
+                    if (isset($detectHtml) && $detectHtml === -1 && DetectHtml($sFilePath) === true) {
+                        @unlink($sFilePath);
+                        $sErrorNumber = '202';
+                    }
+                }
+            }
+        } else {
+            $sErrorNumber = '202';
+        }
+    } else {
+        $sErrorNumber = '202';
+    }
+    if ($sErrorNumber == '0') {
+        // While we are in a course: Registering the newly uploaded file in the course's database.
+        if (api_is_in_course()) {
+            global $_course, $_user;
+            $repository_path = api_get_path(REL_COURSE_PATH).api_get_course_path().'/document/';
+            $to_group_id = 0;
+
+            if (api_is_in_group()) {
+                global $group_properties;
+                $to_group_id = $group_properties['id'];
+            }
+            if (file_exists($sFilePath)) {
+                $file_path = substr($sFilePath, strpos($sFilePath, $repository_path) + strlen($repository_path) - 1);
+                $path = explode('/', $file_path);
+                $file_name = $path[count($path) - 1];
+                $path[count($path) - 1] = '';
+                $folder_path = '/' + implode('/', $path);
+                $file_size = @filesize($sFilePath);
+                $doc_id = FileManager::add_document($_course, $file_path, 'file', $file_size, $file_name);
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $doc_id,
+                    'DocumentAdded',
+                    $_user['user_id'],
+                    $to_group_id
+                );
+                FileManager::item_property_update_on_folder($_course, $folder_path, $_user['user_id']);
+            }
+        }
+    }
+
+    $sFileUrl = CombinePaths(GetResourceTypePath($resourceType, $sCommand), $currentFolder);
+    $sFileUrl = CombinePaths($sFileUrl, $sFileName);
+
+    SendUploadResults($sErrorNumber, $sFileUrl, $sFileName);
+
+    exit;
 }
+
 ?>

+ 255 - 239
main/inc/lib/fckeditor/editor/filemanager/connectors/php/io.php

@@ -22,321 +22,337 @@
  * This is the File Manager Connector for PHP.
 
  */
-function CombinePaths( $sBasePath, $sFolder )
+function CombinePaths($sBasePath, $sFolder)
 {
-	return RemoveFromEnd( $sBasePath, '/' ) . '/' . RemoveFromStart( $sFolder, '/' ) ;
+    return RemoveFromEnd($sBasePath, '/').'/'.RemoveFromStart($sFolder, '/');
 }
-function GetResourceTypePath( $resourceType, $sCommand )
+
+function GetResourceTypePath($resourceType, $sCommand)
 {
-	global $Config ;
+    global $Config;
 
-	if ( $sCommand == "QuickUpload")
-		return $Config['QuickUploadPath'][$resourceType] ;
-	else
-		return $Config['FileTypesPath'][$resourceType] ;
+    if ($sCommand == "QuickUpload") {
+        return $Config['QuickUploadPath'][$resourceType];
+    } else {
+        return $Config['FileTypesPath'][$resourceType];
+    }
 }
 
-function GetResourceTypeDirectory( $resourceType, $sCommand )
+function GetResourceTypeDirectory($resourceType, $sCommand)
 {
-	global $Config ;
-	if ( $sCommand == "QuickUpload")
-	{
-		if ( strlen( $Config['QuickUploadAbsolutePath'][$resourceType] ) > 0 )
-			return $Config['QuickUploadAbsolutePath'][$resourceType] ;
-
-		// Map the "UserFiles" path to a local directory.
-		return Server_MapPath( $Config['QuickUploadPath'][$resourceType] ) ;
-	}
-	else
-	{
-		if ( strlen( $Config['FileTypesAbsolutePath'][$resourceType] ) > 0 )
-			return $Config['FileTypesAbsolutePath'][$resourceType] ;
-
-		// Map the "UserFiles" path to a local directory.
-		return Server_MapPath( $Config['FileTypesPath'][$resourceType] ) ;
-	}
+    global $Config;
+    if ($sCommand == "QuickUpload") {
+        if (strlen($Config['QuickUploadAbsolutePath'][$resourceType]) > 0) {
+            return $Config['QuickUploadAbsolutePath'][$resourceType];
+        }
+
+        // Map the "UserFiles" path to a local directory.
+        return Server_MapPath($Config['QuickUploadPath'][$resourceType]);
+    } else {
+        if (strlen($Config['FileTypesAbsolutePath'][$resourceType]) > 0) {
+            return $Config['FileTypesAbsolutePath'][$resourceType];
+        }
+
+        // Map the "UserFiles" path to a local directory.
+        return Server_MapPath($Config['FileTypesPath'][$resourceType]);
+    }
 }
 
-function GetUrlFromPath( $resourceType, $folderPath, $sCommand )
+function GetUrlFromPath($resourceType, $folderPath, $sCommand)
 {
-	return CombinePaths( GetResourceTypePath( $resourceType, $sCommand ), $folderPath ) ;
+    return CombinePaths(GetResourceTypePath($resourceType, $sCommand), $folderPath);
 }
 
-function RemoveExtension( $fileName )
+function RemoveExtension($fileName)
 {
-	return substr( $fileName, 0, strrpos( $fileName, '.' ) ) ;
+    return substr($fileName, 0, strrpos($fileName, '.'));
 }
 
-function ServerMapFolder( $resourceType, $folderPath, $sCommand )
+function ServerMapFolder($resourceType, $folderPath, $sCommand)
 {
-	// Get the resource type directory.
-	$sResourceTypePath = GetResourceTypeDirectory( $resourceType, $sCommand ) ;
+    // Get the resource type directory.
+    $sResourceTypePath = GetResourceTypeDirectory($resourceType, $sCommand);
 
-	// Ensure that the directory exists.
-	$sErrorMsg = CreateServerFolder( $sResourceTypePath ) ;
-	if ( $sErrorMsg != '' )
-		SendError( 1, "Error creating folder \"{$sResourceTypePath}\" ({$sErrorMsg})" ) ;
+    // Ensure that the directory exists.
+    $sErrorMsg = CreateServerFolder($sResourceTypePath);
+    if ($sErrorMsg != '') {
+        SendError(1, "Error creating folder \"{$sResourceTypePath}\" ({$sErrorMsg})");
+    }
 
-	// Return the resource type directory combined with the required path.
-	return CombinePaths( $sResourceTypePath , $folderPath ) ;
+    // Return the resource type directory combined with the required path.
+    return CombinePaths($sResourceTypePath, $folderPath);
 }
 
-function GetParentFolder( $folderPath )
+function GetParentFolder($folderPath)
 {
-	$sPattern = "-[/\\\\][^/\\\\]+[/\\\\]?$-" ;
-	return preg_replace( $sPattern, '', $folderPath ) ;
+    $sPattern = "-[/\\\\][^/\\\\]+[/\\\\]?$-";
+
+    return preg_replace($sPattern, '', $folderPath);
 }
 
-function CreateServerFolder( $folderPath, $lastFolder = null )
+function CreateServerFolder($folderPath, $lastFolder = null)
 {
-	global $Config ;
-	$sParent = GetParentFolder( $folderPath ) ;
-
-	// Ensure the folder path has no double-slashes, or mkdir may fail on certain platforms
-	while ( strpos($folderPath, '//') !== false )
-	{
-		$folderPath = str_replace( '//', '/', $folderPath ) ;
-	}
-
-	// Check if the parent exists, or create it.
-	if ( !empty($sParent) && !file_exists( $sParent ) )
-	{
-		//prevents agains infinite loop when we can't create root folder
-		if ( !is_null( $lastFolder ) && $lastFolder === $sParent) {
-			return "Can't create $folderPath directory" ;
-		}
-
-		$sErrorMsg = CreateServerFolder( $sParent, $folderPath ) ;
-		if ( $sErrorMsg != '' )
-			return $sErrorMsg ;
-	}
-
-	if ( !file_exists( $folderPath ) )
-	{
-		// Turn off all error reporting.
-		error_reporting( 0 ) ;
-
-		$php_errormsg = '' ;
-		// Enable error tracking to catch the error.
-		ini_set( 'track_errors', '1' ) ;
-
-		if ( isset( $Config['ChmodOnFolderCreate'] ) && !$Config['ChmodOnFolderCreate'] )
-		{
-			mkdir( $folderPath ) ;
-		}
-		else
-		{
-			$permissions = 0777 ;
-			// $permissions = 0770 ;
-			if ( isset( $Config['ChmodOnFolderCreate'] ) )
-			{
-				$permissions = $Config['ChmodOnFolderCreate'] ;
-			}
-			// To create the folder with 0777 permissions, we need to set umask to zero.
-			//$oldumask = umask(0) ;
-			mkdir( $folderPath, $permissions ) ;
-			//umask( $oldumask ) ;
-		}
-
-		// While we are in a course: Registering the newly created folder in the course's database.
-		if (api_is_in_course())
-		{
-			global $_course, $_user;
-			$repository_path = api_get_path(REL_COURSE_PATH).api_get_course_path().'/document/';
-			$to_group_id = 0;
-
-			if (api_is_in_group())
-			{
-				global $group_properties;
-				$to_group_id = $group_properties['id'];
-			}
-
-			$folder_path=preg_replace("/^.*".TOOL_DOCUMENT."/", "", $folderPath);	// 
-			$folder_path=preg_replace("/\/$/", "", $folder_path);	// should be done in 1 regexp I guess ... 
-			// $folder_path = substr($folderPath, strpos($folderPath, $repository_path) + strlen($repository_path) - 1);
-			
-			$folder_name = explode('/', $folder_path);
-			$folder_name = $folder_name[count($folder_name) - 1];
-			$doc_id = add_document($_course, $folder_path, 'folder', 0, $folder_name);
-			api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'], $to_group_id);
-		}
-
-		$sErrorMsg = $php_errormsg ;
-
-		// Restore the configurations.
-		ini_restore( 'track_errors' ) ;
-		ini_restore( 'error_reporting' ) ;
-
-		return $sErrorMsg ;
-	}
-	else
-		return '' ;
+    global $Config;
+    $sParent = GetParentFolder($folderPath);
+
+    // Ensure the folder path has no double-slashes, or mkdir may fail on certain platforms
+    while (strpos($folderPath, '//') !== false) {
+        $folderPath = str_replace('//', '/', $folderPath);
+    }
+
+    // Check if the parent exists, or create it.
+    if (!empty($sParent) && !file_exists($sParent)) {
+        //prevents agains infinite loop when we can't create root folder
+        if (!is_null($lastFolder) && $lastFolder === $sParent) {
+            return "Can't create $folderPath directory";
+        }
+
+        $sErrorMsg = CreateServerFolder($sParent, $folderPath);
+        if ($sErrorMsg != '') {
+            return $sErrorMsg;
+        }
+    }
+
+    if (!file_exists($folderPath)) {
+        // Turn off all error reporting.
+        error_reporting(0);
+
+        $php_errormsg = '';
+        // Enable error tracking to catch the error.
+        ini_set('track_errors', '1');
+
+        if (isset($Config['ChmodOnFolderCreate']) && !$Config['ChmodOnFolderCreate']) {
+            mkdir($folderPath);
+        } else {
+            $permissions = 0777;
+            // $permissions = 0770 ;
+            if (isset($Config['ChmodOnFolderCreate'])) {
+                $permissions = $Config['ChmodOnFolderCreate'];
+            }
+            // To create the folder with 0777 permissions, we need to set umask to zero.
+            //$oldumask = umask(0) ;
+            mkdir($folderPath, $permissions);
+            //umask( $oldumask ) ;
+        }
+
+        // While we are in a course: Registering the newly created folder in the course's database.
+        if (api_is_in_course()) {
+            global $_course, $_user;
+            $repository_path = api_get_path(REL_COURSE_PATH).api_get_course_path().'/document/';
+            $to_group_id = 0;
+
+            if (api_is_in_group()) {
+                global $group_properties;
+                $to_group_id = $group_properties['id'];
+            }
+
+            $folder_path = preg_replace("/^.*".TOOL_DOCUMENT."/", "", $folderPath); //
+            $folder_path = preg_replace("/\/$/", "", $folder_path); // should be done in 1 regexp I guess ...
+            // $folder_path = substr($folderPath, strpos($folderPath, $repository_path) + strlen($repository_path) - 1);
+
+            $folder_name = explode('/', $folder_path);
+            $folder_name = $folder_name[count($folder_name) - 1];
+            $doc_id = FileManager::add_document($_course, $folder_path, 'folder', 0, $folder_name);
+            api_item_property_update(
+                $_course,
+                TOOL_DOCUMENT,
+                $doc_id,
+                'FolderCreated',
+                $_user['user_id'],
+                $to_group_id
+            );
+        }
+
+        $sErrorMsg = $php_errormsg;
+
+        // Restore the configurations.
+        ini_restore('track_errors');
+        ini_restore('error_reporting');
+
+        return $sErrorMsg;
+    } else {
+        return '';
+    }
 }
 
 function GetRootPath()
 {
-	if (!isset($_SERVER)) {
-		global $_SERVER;
-	}
-	$sRealPath = realpath( './' ) ;
-	// #2124 ensure that no slash is at the end
-	$sRealPath = rtrim($sRealPath,"\\/");
-
-	$sSelfPath = $_SERVER['PHP_SELF'] ;
-	$sSelfPath = substr( $sSelfPath, 0, strrpos( $sSelfPath, '/' ) ) ;
-
-	$sSelfPath = str_replace( '/', DIRECTORY_SEPARATOR, $sSelfPath ) ;
-
-	$position = strpos( $sRealPath, $sSelfPath ) ;
-
-	// This can check only that this script isn't run from a virtual dir
-	// But it avoids the problems that arise if it isn't checked
-	if ( $position === false || $position <> strlen( $sRealPath ) - strlen( $sSelfPath ) )
-		SendError( 1, 'Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/php/config.php".' ) ;
-
-	return substr( $sRealPath, 0, $position ) ;
+    if (!isset($_SERVER)) {
+        global $_SERVER;
+    }
+    $sRealPath = realpath('./');
+    // #2124 ensure that no slash is at the end
+    $sRealPath = rtrim($sRealPath, "\\/");
+
+    $sSelfPath = $_SERVER['PHP_SELF'];
+    $sSelfPath = substr($sSelfPath, 0, strrpos($sSelfPath, '/'));
+
+    $sSelfPath = str_replace('/', DIRECTORY_SEPARATOR, $sSelfPath);
+
+    $position = strpos($sRealPath, $sSelfPath);
+
+    // This can check only that this script isn't run from a virtual dir
+    // But it avoids the problems that arise if it isn't checked
+    if ($position === false || $position <> strlen($sRealPath) - strlen($sSelfPath)) {
+        SendError(
+            1,
+            'Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/php/config.php".'
+        );
+    }
+
+    return substr($sRealPath, 0, $position);
 }
 
 // Emulate the asp Server.mapPath function.
 // given an url path return the physical directory that it corresponds to
-function Server_MapPath( $path )
+function Server_MapPath($path)
 {
-	// This function is available only for Apache
-	if ( function_exists( 'apache_lookup_uri' ) )
-	{
-		$info = apache_lookup_uri( $path ) ;
-		return $info->filename . $info->path_info ;
-	}
-
-	// This isn't correct but for the moment there's no other solution
-	// If this script is under a virtual directory or symlink it will detect the problem and stop
-	return GetRootPath() . $path ;
+    // This function is available only for Apache
+    if (function_exists('apache_lookup_uri')) {
+        $info = apache_lookup_uri($path);
+
+        return $info->filename.$info->path_info;
+    }
+
+    // This isn't correct but for the moment there's no other solution
+    // If this script is under a virtual directory or symlink it will detect the problem and stop
+    return GetRootPath().$path;
 }
 
-function IsAllowedExt( $sExtension, $resourceType )
+function IsAllowedExt($sExtension, $resourceType)
 {
-	global $Config ;
-	// Get the allowed and denied extensions arrays.
-	$arAllowed	= $Config['AllowedExtensions'][$resourceType] ;
-	$arDenied	= $Config['DeniedExtensions'][$resourceType] ;
+    global $Config;
+    // Get the allowed and denied extensions arrays.
+    $arAllowed = $Config['AllowedExtensions'][$resourceType];
+    $arDenied = $Config['DeniedExtensions'][$resourceType];
 
-	if ( count($arAllowed) > 0 && !in_array( $sExtension, $arAllowed ) )
-		return false ;
+    if (count($arAllowed) > 0 && !in_array($sExtension, $arAllowed)) {
+        return false;
+    }
 
-	if ( count($arDenied) > 0 && in_array( $sExtension, $arDenied ) )
-		return false ;
+    if (count($arDenied) > 0 && in_array($sExtension, $arDenied)) {
+        return false;
+    }
 
-	// Adding a check using the Chamilo system's white or black list.
-	if ( !filter_extension( $sExtension ) )
-		return false ;
+    // Adding a check using the Chamilo system's white or black list.
+    if (!FileManager::filter_extension($sExtension)) {
+        return false;
+    }
 
-	return true ;
+    return true;
 }
 
-function IsAllowedType( $resourceType )
+function IsAllowedType($resourceType)
 {
-	global $Config ;
-	if ( !in_array( $resourceType, $Config['ConfigAllowedTypes'] ) )
-		return false ;
+    global $Config;
+    if (!in_array($resourceType, $Config['ConfigAllowedTypes'])) {
+        return false;
+    }
 
-	return true ;
+    return true;
 }
 
-function IsAllowedCommand( $sCommand )
+function IsAllowedCommand($sCommand)
 {
-	global $Config ;
+    global $Config;
 
-	if ( !in_array( $sCommand, $Config['ConfigAllowedCommands'] ) )
-		return false ;
+    if (!in_array($sCommand, $Config['ConfigAllowedCommands'])) {
+        return false;
+    }
 
-	return true ;
+    return true;
 }
 
 function GetCurrentFolder()
 {
-	if (!isset($_GET)) {
-		global $_GET;
-	}
-	$sCurrentFolder	= isset( $_GET['CurrentFolder'] ) ? $_GET['CurrentFolder'] : '/' ;
-
-	// Check the current folder syntax (must begin and start with a slash).
-	if ( !preg_match( '|/$|', $sCurrentFolder ) )
-		$sCurrentFolder .= '/' ;
-	if ( strpos( $sCurrentFolder, '/' ) !== 0 )
-		$sCurrentFolder = '/' . $sCurrentFolder ;
-
-	// Ensure the folder path has no double-slashes
-	while ( strpos ($sCurrentFolder, '//') !== false ) {
-		$sCurrentFolder = str_replace ('//', '/', $sCurrentFolder) ;
-	}
-
-	// Check for invalid folder paths (..)
-	if ( strpos( $sCurrentFolder, '..' ) || strpos( $sCurrentFolder, "\\" ))
-		SendError( 102, '' ) ;
-
-	if ( preg_match(",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"\<\>\|]),", $sCurrentFolder))
-		SendError( 102, '' ) ;
-
-	return $sCurrentFolder ;
+    if (!isset($_GET)) {
+        global $_GET;
+    }
+    $sCurrentFolder = isset($_GET['CurrentFolder']) ? $_GET['CurrentFolder'] : '/';
+
+    // Check the current folder syntax (must begin and start with a slash).
+    if (!preg_match('|/$|', $sCurrentFolder)) {
+        $sCurrentFolder .= '/';
+    }
+    if (strpos($sCurrentFolder, '/') !== 0) {
+        $sCurrentFolder = '/'.$sCurrentFolder;
+    }
+
+    // Ensure the folder path has no double-slashes
+    while (strpos($sCurrentFolder, '//') !== false) {
+        $sCurrentFolder = str_replace('//', '/', $sCurrentFolder);
+    }
+
+    // Check for invalid folder paths (..)
+    if (strpos($sCurrentFolder, '..') || strpos($sCurrentFolder, "\\")) {
+        SendError(102, '');
+    }
+
+    if (preg_match(",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"\<\>\|]),", $sCurrentFolder)) {
+        SendError(102, '');
+    }
+
+    return $sCurrentFolder;
 }
 
 // Do a cleanup of the folder name to avoid possible problems
-function SanitizeFolderName( $sNewFolderName )
+function SanitizeFolderName($sNewFolderName)
 {
-	$sNewFolderName = stripslashes( $sNewFolderName ) ;
+    $sNewFolderName = stripslashes($sNewFolderName);
 
-	// Remove . \ / | : ? * " < >
-	$sNewFolderName = preg_replace( '/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFolderName ) ;
+    // Remove . \ / | : ? * " < >
+    $sNewFolderName = preg_replace('/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFolderName);
 
-	return $sNewFolderName ;
+    return $sNewFolderName;
 }
 
 // Do a cleanup of the file name to avoid possible problems
-function SanitizeFileName( $sNewFileName, $sMimeType = null )
+function SanitizeFileName($sNewFileName, $sMimeType = null)
 {
-	global $Config ;
+    global $Config;
 
-	if ( empty( $sMimeType ) )
-	{
-		$sNewFileName = stripslashes( $sNewFileName ) ;
-	}
-	else
-	{
-		$sNewFileName = add_ext_on_mime( stripslashes( $sNewFileName ), $sMimeType );
-	}
+    if (empty($sMimeType)) {
+        $sNewFileName = stripslashes($sNewFileName);
+    } else {
+        $sNewFileName = FileManager::add_ext_on_mime(stripslashes($sNewFileName), $sMimeType);
+    }
 
-	// Replace dots in the name with underscores (only one dot can be there... security issue).
-	if ( $Config['ForceSingleExtension'] )
-		$sNewFileName = preg_replace( '/\\.(?![^.]*$)/', '_', $sNewFileName ) ;
+    // Replace dots in the name with underscores (only one dot can be there... security issue).
+    if ($Config['ForceSingleExtension']) {
+        $sNewFileName = preg_replace('/\\.(?![^.]*$)/', '_', $sNewFileName);
+    }
 
-	// Remove \ / | : ? * " < >
-	//$sNewFileName = preg_replace( '/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFileName ) ;
-	$sNewFileName = replace_dangerous_char( $sNewFileName, 'strict' ) ;
+    // Remove \ / | : ? * " < >
+    //$sNewFileName = preg_replace( '/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFileName ) ;
+    $sNewFileName = replace_dangerous_char($sNewFileName, 'strict');
 
-	$sNewFileName = php2phps( $sNewFileName ) ;
+    $sNewFileName = FileManager::php2phps($sNewFileName);
 
-	return $sNewFileName ;
+    return $sNewFileName;
 }
 
 // This is the function that sends the results of the uploading process.
-function SendUploadResults( $errorNumber, $fileUrl = '', $fileName = '', $customMsg = '' )
+function SendUploadResults($errorNumber, $fileUrl = '', $fileName = '', $customMsg = '')
 {
-	// Minified version of the document.domain automatic fix script (#1919).
-	// The original script can be found at _dev/domain_fix_template.js
-	echo <<<EOF
+    // Minified version of the document.domain automatic fix script (#1919).
+    // The original script can be found at _dev/domain_fix_template.js
+    echo <<<EOF
 <script type="text/javascript">
 (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
 EOF;
 
-	if ($errorNumber && $errorNumber != 201) {
-		$fileUrl = "";
-		$fileName = "";
-	}
-
-	$rpl = array( '\\' => '\\\\', '"' => '\\"' ) ;
-	echo 'window.parent.OnUploadCompleted(' . $errorNumber . ',"' . strtr( $fileUrl, $rpl ) . '","' . strtr( $fileName, $rpl ) . '", "' . strtr( $customMsg, $rpl ) . '") ;' ;
-	echo '</script>' ;
-	exit ;
+    if ($errorNumber && $errorNumber != 201) {
+        $fileUrl = "";
+        $fileName = "";
+    }
+
+    $rpl = array('\\' => '\\\\', '"' => '\\"');
+    echo 'window.parent.OnUploadCompleted('.$errorNumber.',"'.strtr($fileUrl, $rpl).'","'.strtr(
+        $fileName,
+        $rpl
+    ).'", "'.strtr($customMsg, $rpl).'") ;';
+    echo '</script>';
+    exit;
 }
 
 ?>

+ 934 - 868
main/inc/lib/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php

@@ -7,7 +7,6 @@
  */
 
 require_once '../../../../../global.inc.php';
-require_once '../../../../fileUpload.lib.php';
 
 require_once('Files.php');
 require_once('Transform.php');
@@ -19,877 +18,944 @@ require_once('Transform.php');
  */
 class ImageManager
 {
-	/**
-	 * Configuration array.
-	 */
-	var $config;
-
-	/**
-	 * Array of directory information.
-	 */
-	var $dirs;
-
-	/**
-	 * Constructor. Create a new Image Manager instance.
-	 * @param array $config configuration array, see config.inc.php
-	 */
-	function ImageManager($config)
-	{
-		$this->config = $config;
-	}
-
-	/**
-	 * Get the base directory.
-	 * @return string base dir, see config.inc.php
-	 */
-	function getBaseDir()
-	{
-		Return $this->config['base_dir'];
-	}
-
-	/**
-	 * Get the base URL.
-	 * @return string base url, see config.inc.php
-	 */
-	function getBaseURL()
-	{
-		Return $this->config['base_url'];
-	}
-
-	function isValidBase()
-	{
-		return is_dir($this->getBaseDir());
-	}
-
-	/**
-	 * Get the tmp file prefix.
+    /**
+     * Configuration array.
+     */
+    var $config;
+
+    /**
+     * Array of directory information.
+     */
+    var $dirs;
+
+    /**
+     * Constructor. Create a new Image Manager instance.
+     * @param array $config configuration array, see config.inc.php
+     */
+    function ImageManager($config)
+    {
+        $this->config = $config;
+    }
+
+    /**
+     * Get the base directory.
+     * @return string base dir, see config.inc.php
+     */
+    function getBaseDir()
+    {
+        Return $this->config['base_dir'];
+    }
+
+    /**
+     * Get the base URL.
+     * @return string base url, see config.inc.php
+     */
+    function getBaseURL()
+    {
+        Return $this->config['base_url'];
+    }
+
+    function isValidBase()
+    {
+        return is_dir($this->getBaseDir());
+    }
+
+    /**
+     * Get the tmp file prefix.
      * @return string tmp file prefix.
-	 */
-	function getTmpPrefix()
-	{
-		Return $this->config['tmp_prefix'];
-	}
-
-	/**
-	 * Get the sub directories in the base dir.
-	 * Each array element contain
-	 * the relative path (relative to the base dir) as key and the
-	 * full path as value.
-	 * @return array of sub directries
-	 * <code>array('path name' => 'full directory path', ...)</code>
-	 */
-	function getDirs()
-	{
-		if(is_null($this->dirs))
-		{
-			$dirs = $this->_dirs($this->getBaseDir(),'/');
-			ksort($dirs);
-
-			$this->dirs = $dirs;
-		}
-		return $this->dirs;
-	}
-
-	/**
-	 * Recursively travese the directories to get a list
-	 * of accessable directories.
-	 * @param string $base the full path to the current directory
-	 * @param string $path the relative path name
-	 * @return array of accessiable sub-directories
-	 * <code>array('path name' => 'full directory path', ...)</code>
-	 */
-	function _dirs($base, $path)
-	{
-		$base = Files::fixPath($base);
-		$dirs = array();
-
-		if (!$this->isValidBase())
-			return $dirs;
-
-		$d = @dir($base);
-
-		$in_group = api_is_in_group();
-		if ($in_group)
-		{
-			$group_properties = GroupManager::get_group_properties($_SESSION['_gid']);
-			$group_directory = explode('/', $group_properties['directory']);
-			$group_directory = $group_directory[count($group_directory) - 1];
-		}
-
-		$user_id = api_get_user_id();
-		while (false !== ($entry = $d->read())) {
-			//If it is a directory, and it doesn't start with
-			// a dot, and if is it not the thumbnail directory
-			if(is_dir($base.$entry)
-				&& substr($entry,0,1) != '.'
-				&& strpos($entry, '_DELETED_') === false
-				&& strpos($entry, 'chat_files') === false
-				&& strpos($entry, 'css') === false
-				&& strpos($entry, 'HotPotatoes_files') === false
-				&& ($in_group || (!$in_group && strpos($entry, '_groupdocs') === false))
-				&& !$this->isThumbDir($entry))
-			{
-				$relative = Files::fixPath($path.$entry);
-				$fullpath = Files::fixPath($base.$entry);
-
-				if ($in_group && strpos($fullpath, '_groupdocs') !== false && strpos($fullpath, $group_directory) === false) {
-					continue;
-				}
-				global $_course;
-				if (!empty($_course)) {
-					$base_dir = substr($fullpath, 0, strpos($fullpath,'/document/')+9); //
-					$new_dir  = substr($fullpath, strlen($base_dir),-1); //
-					$doc_id = DocumentManager::get_document_id($_course, $new_dir);
-					$visible_status= api_get_item_visibility($_course,TOOL_DOCUMENT,$doc_id);
-				}
-
-				//Teachers can access to hidden files and directories as they can in the tool documents
-			    /*
-				if ($visible_status=='0' || $visible_status=='-1') {
-					continue;
-				}
-				*/
-
-				/* if (strpos($fullpath, '/shared_folder/') !== false) {
-					if (!preg_match('/.*\/shared_folder\/$/', $fullpath)) {
-						//all students can see the shared_folder
-						if (strpos($fullpath, '/shared_folder/sf_user_'.$user_id.'/') !== false) {
-							continue;
-						}
-					}
-				}
-				*/
-				$dirs[$relative] = $fullpath;
-				$dirs = array_merge($dirs, $this->_dirs($fullpath, $relative));
-			}
-		}
-		$d->close();
-
-		Return $dirs;
-	}
-
-	/**
-	 * Get all the files and directories of a relative path.
-	 * @param string $path relative path to be base path.
-	 * @return array of file and path information.
-	 * <code>array(0=>array('relative'=>'fullpath',...), 1=>array('filename'=>fileinfo array(),...)</code>
-	 * fileinfo array: <code>array('url'=>'full url',
-	 *                       'relative'=>'relative to base',
-	 *                        'fullpath'=>'full file path',
-	 *                        'image'=>imageInfo array() false if not image,
-	 *                        'stat' => filestat)</code>
-	 */
-	function getFiles($path) {
-		$files = array();
-		$dirs = array();
-
-		if (!$this->isValidBase())
-			return array($files,$dirs);
-
-		$path = Files::fixPath($path);
-		$base = Files::fixPath($this->getBaseDir());
-
-		$fullpath = Files::makePath($base,$path);
-
-		$d = @dir($fullpath);
-
-		if (empty($d)) {
-			$path = Files::fixPath('/');
-			$base = Files::fixPath($this->getBaseDir());
-			$fullpath = Files::makePath($base,$path);
-			$d = @dir($fullpath);
-		}
-
-
-		$in_group = api_is_in_group();
-		$user_id = api_get_user_id();
-
-		// check templates files in bd
-		$tbl_system_template = Database :: get_main_table(TABLE_MAIN_SYSTEM_TEMPLATE);
-
-		$sql = "SELECT image FROM $tbl_system_template ";
-		$res = Database::query($sql);
-
-		$files_templates = array();
-
-		while ($row = Database::fetch_row($res)) {
-			$files_templates[] = $row[0];
-		}
-
-		while (false !== ($entry = $d->read())) {
-			if (in_array($entry,$files_templates)) continue;
-			if (substr($entry,0,1) != '.'          //not a dot file or directory
-				&& strpos($entry, '_DELETED_') === false
-				&& strpos($entry, 'chat_files') === false
-				&& strpos($entry, 'css') === false
-				&& strpos($entry, 'HotPotatoes_files') === false
-				&& ($in_group || (!$in_group && strpos($entry, '_groupdocs') === false)))
-			{
-				$is_dir = is_dir($fullpath.$entry);
-				if ($is_dir) {
-					$dir_entry = Files::fixPath($fullpath.$entry);
-					/*
-					if (strpos($dir_entry, '/shared_folder/') !== false)
-					{
-						if (!preg_match('/.*\/shared_folder\/$/', $dir_entry))
-						{
-							//all students can see the shared_folder
-							if (strpos($dir_entry, '/shared_folder/sf_user_'.$user_id.'/') === true)
-							{
-								continue;
-							}
-						}
-					}
-					*/
-				}
-
-				if ($is_dir && !$this->isThumbDir($entry)) {
-				    global $_course;
-					if (isset($_course) && !empty($_course) && isset($_course['code'])) {
-						//checking visibility
-						$base_dir = substr($dir_entry, 0, strpos($dir_entry,'/document/')+9);
-						$new_dir  = substr($dir_entry, strlen($base_dir),-1); //
-						$doc_id = DocumentManager::get_document_id($_course, $new_dir );
-						$visible_status= api_get_item_visibility($_course,TOOL_DOCUMENT,$doc_id);
-					}
-
-					//Teachers can access to hidden files and directories as they can in the tool documents
-					/*
-					if ($visible_status=='0' || $visible_status=='-1') {
-						continue;
-					}
-					*/
-					$relative = Files::fixPath($path.$entry);
-					$full = Files::fixPath($fullpath.$entry);
-					$count = $this->countFiles($full);
-					$dirs[$relative] = array('fullpath'=>$full,'entry'=>$entry,'count'=>$count);
-				} else if(is_file($fullpath.$entry) && !$this->isThumb($entry) && !$this->isTmpFile($entry)) {
-					$img = $this->getImageInfo($fullpath.$entry);
-					if(!(!is_array($img)&&$this->config['validate_images'])) {
-					    global $_course;
-
-					    if (!empty($_course) && isset($_course['code'])) {
-							//checking visibility
-							$base_dir = substr($fullpath.$entry, 0, strpos($fullpath.$entry,'/document/')+9);
-							$new_dir  = substr($fullpath.$entry, strlen($base_dir));
-							$doc_id = DocumentManager::get_document_id($_course, $new_dir);
-							$visible_status = api_get_item_visibility($_course, TOOL_DOCUMENT, $doc_id);
-						}
-
-						//Teachers can access to hidden files and directories as they can in the tool documents
-					    /*
-						if ($visible_status=='0' || $visible_status=='-1') {
-							continue;
-						}
-						*/
-
-						$file['url'] = Files::makePath($this->config['base_url'], $path).$entry;
-						$file['relative'] = $path.$entry;
-						$file['fullpath'] = $fullpath.$entry;
-						$file['image'] = $img;
-						$file['stat'] = stat($fullpath.$entry);
-						$files[$entry] = $file;
-					}
-				}
-			}
-		}
-		$d->close();
-		ksort($dirs);
-		ksort($files);
-		return array($dirs, $files);
-	}
-
-	/**
-	 * Count the number of files and directories in a given folder
-	 * minus the thumbnail folders and thumbnails.
-	 */
-	function countFiles($path)
-	{
-		$total = 0;
-
-		if(is_dir($path))
-		{
-			$d = @dir($path);
-
-			while (false !== ($entry = $d->read()))
-			{
-				//echo $entry."<br />";
-				if (substr($entry, 0, 1) != '.'
-					&& !$this->isThumbDir($entry)
-					&& !$this->isTmpFile($entry)
-					&& !$this->isThumb($entry))
-				{
-					$total++;
-				}
-			}
-			$d->close();
-		}
-		return $total;
-	}
-
-	/**
-	 * Get image size information.
-	 * @param string $file the image file
-	 * @return array of getImageSize information,
-	 *  false if the file is not an image.
-	 */
-	function getImageInfo($file)
-	{
-		Return @getImageSize($file);
-	}
-
-	/**
-	 * Check if the file contains the thumbnail prefix.
-	 * @param string $file filename to be checked
-	 * @return true if the file contains the thumbnail prefix, false otherwise.
-	 */
-	function isThumb($file)
-	{
-		$len = strlen($this->config['thumbnail_prefix']);
-		if(substr($file,0,$len)==$this->config['thumbnail_prefix'])
-			Return true;
-		else
-			Return false;
-	}
-
-	/**
-	 * Check if the given directory is a thumbnail directory.
-	 * @param string $entry directory name
-	 * @return true if it is a thumbnail directory, false otherwise
-	 */
-	function isThumbDir($entry)
-	{
-		if (!$this->config['thumbnail_dir']
-			|| strlen(trim($this->config['thumbnail_dir'])) == 0)
-			Return false;
-		else
-			Return ($entry == $this->config['thumbnail_dir']);
-	}
-
-	/**
-	 * Check if the given file is a tmp file.
-	 * @param string $file file name
-	 * @return boolean true if it is a tmp file, false otherwise
-	 */
-	function isTmpFile($file)
-	{
-		$len = strlen($this->config['tmp_prefix']);
-		if(substr($file,0,$len)==$this->config['tmp_prefix'])
-			Return true;
-		else
-			Return false;
-	}
-
-	/**
-	 * For a given image file, get the respective thumbnail filename
-	 * no file existence check is done.
-	 * @param string $fullpathfile the full path to the image file
-	 * @return string of the thumbnail file
-	 */
-	function getThumbName($fullpathfile)
-	{
-		$path_parts = pathinfo($fullpathfile);
-
-		$thumbnail = $this->config['thumbnail_prefix'].$path_parts['basename'];
-
-		if ($this->config['safe_mode']
-			|| strlen(trim($this->config['thumbnail_dir'])) == 0)
-		{
-			Return Files::makeFile($path_parts['dirname'],$thumbnail);
-		}
-		else
-		{
-			if(strlen(trim($this->config['thumbnail_dir'])) > 0)
-			{
-				$path = Files::makePath($path_parts['dirname'],$this->config['thumbnail_dir']);
-				if(!is_dir($path))
-					Files::createFolder($path);
-				Return Files::makeFile($path,$thumbnail);
-			}
-			else //should this ever happen?
-			{
-				//error_log('ImageManager: Error in creating thumbnail name');
-			}
-		}
-	}
-
-	/**
-	 * Similar to getThumbName, but returns the URL, base on the
-	 * given base_url in config.inc.php
-	 * @param string $relative the relative image file name,
-	 * relative to the base_dir path
-	 * @return string the url of the thumbnail
-	 */
-	function getThumbURL($relative)
-	{
-		$path_parts = pathinfo($relative);
-		$thumbnail = $this->config['thumbnail_prefix'].$path_parts['basename'];
-		if($path_parts['dirname']=='\\') $path_parts['dirname']='/';
-
-		if ($this->config['safe_mode']
-			|| strlen(trim($this->config['thumbnail_dir'])) == 0)
-		{
-			$path = Files::fixPath($path_parts['dirname']);
-			$url_path = Files::makePath($this->getBaseURL(), $path);
-			Return Files::makeFile($url_path,$thumbnail);
-		}
-		else
-		{
-			if(strlen(trim($this->config['thumbnail_dir'])) > 0)
-			{
-				$path = Files::makePath($path_parts['dirname'],$this->config['thumbnail_dir']);
-				$url_path = Files::makePath($this->getBaseURL(), $path);
-				Return Files::makeFile($url_path,$thumbnail);
-			}
-			else //should this ever happen?
-			{
-				//error_log('ImageManager: Error in creating thumbnail url');
-			}
-
-		}
-	}
-
-	/**
-	 * Check if the given path is part of the subdirectories
-	 * under the base_dir.
-	 * @param string $path the relative path to be checked
-	 * @return boolean true if the path exists, false otherwise
-	 */
-	function validRelativePath($path)
-	{
-		$dirs = $this->getDirs();
-		if($path == '/' || $path == '')
-			Return true;
-		//check the path given in the url against the
-		//list of paths in the system.
-		for($i = 0; $i < count($dirs); $i++)
-		{
-			$key = key($dirs);
-			//we found the path
-			if($key == $path)
-				Return true;
-
-			next($dirs);
-		}
-		Return false;
-	}
-
-	/**
-	 * Process uploaded files, assumes the file is in
-	 * $_FILES['upload'] and $_POST['dir'] is set.
-	 * The dir must be relative to the base_dir and exists.
-	 * If 'validate_images' is set to true, only file with
-	 * image dimensions will be accepted.
-	 * @return null
-	 */
-	function processUploads() {
-		if (!$this->isValidBase())
-			return;
-
-		$relative = null;
-		if (isset($_POST['dir']))
-			$relative = rawurldecode($_POST['dir']);
-		else
-			return;
-
-		//check for the file, and must have valid relative path
-		if(isset($_FILES['upload']) && $this->validRelativePath($relative)) {
-			return $this->_processFiles($relative, $_FILES['upload']);
-		}
-	}
-
-	/**
-	 * Process upload files. The file must be an
-	 * uploaded file. If 'validate_images' is set to
-	 * true, only images will be processed. Any duplicate
-	 * file will be renamed. See Files::copyFile for details
-	 * on renaming.
-	 * @param string $relative the relative path where the file
-	 * should be copied to.
-	 * @param array $file the uploaded file from $_FILES
-	 * @return boolean true if the file was processed successfully,
-	 * false otherwise
-	 */
-	function _processFiles($relative, $file)
-	{
-		global $_course;
-		if($file['error']!=0) {
-			return false;
-		}
-
-		if(!is_file($file['tmp_name'])) {
-			return false;
-		}
-
-		if(!is_uploaded_file($file['tmp_name'])) {
-			Files::delFile($file['tmp_name']);
-			return false;
-		}
-
-		$file['name'] = replace_dangerous_char($file['name'], 'strict');
-		$file_name = $file['name'];
-		$extension = explode('.', $file_name);
-		$count = count($extension);
-		if ($count == 1) {
-			$extension = '';
-		} else {
-			$extension = strtolower($extension[$count - 1]);
-		}
-
-		// Checking for image by file extension first, using the configuration file.
-		if (!in_array($extension, $this->config['accepted_extensions'])) {
-			Files::delFile($file['tmp_name']);
-			return false;
-		}
-
-		// Second, filtering using a special function of the system.
-		$result = filter_extension($file_name);
-		if (($result == 0) || ($file_name != $file['name'])) {
-			Files::delFile($file['tmp_name']);
-			return false;
-		}
-
-		// Checking for a valid image by reading binary file (partially in most cases).
-		if ($this->config['validate_images']) {
-			$imgInfo = @getImageSize($file['tmp_name']);
-			if(!is_array($imgInfo)) {
-				Files::delFile($file['tmp_name']);
-				return false;
-			}
-		}
-
-		//now copy the file
-		$path = Files::makePath($this->getBaseDir(),$relative);
-		$result = Files::copyFile($file['tmp_name'], $path, $file['name']);
-
-		//no copy error
-		if (!is_int($result)) {
-
-	   	    if (isset($_course) && !empty($_course) && isset($_course['code'])) {
-				//adding the document to the DB
-				global $to_group_id;
-
-				// looking for the /document/ folder
-				$document_path = substr($path, strpos($path,'/document/')+9, strlen($path)); //   /shared_folder/4/name
-				$document_path.= $result;
-
-				$chamiloFile = $file['name'];
-				$chamiloFileSize = $file['size'];
-				if(!empty($group_properties['directory'])) {
-					$chamiloFolder=$group_properties['directory'].$chamiloFolder;
-				}
-
-				$doc_id = add_document($_course, $document_path,'file', $chamiloFileSize , $chamiloFile);
-				$current_session_id = api_get_session_id();
-				api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(),$to_group_id,null,null,null,$current_session_id);//get Dokeos
-			}
-
-			/*
-			if (!(api_is_platform_admin() || api_is_course_admin())) {
-				//setting invisible by default for the students
-				api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id());
-			}
-			*/
-		   $dimensionsIndex = isset($_REQUEST['uploadSize']) ? $_REQUEST['uploadSize'] : 0;
-		   // If maximum size is specified, constrain image to it.
-           if ($this->config['maxWidth'][$dimensionsIndex] > 0 && $this->config['maxHeight'][$dimensionsIndex] > 0)
-           {
-			   $img = Image_Transform::factory(IMAGE_CLASS);
-			   $img->load($path . $result);
-
-			   // image larger than max dimensions?
-			   if ($img->img_x > $this->config['maxWidth'][$dimensionsIndex] || $img->img_y > $this->config['maxHeight'][$dimensionsIndex])
-			   {
-				   $percentage = min($this->config['maxWidth'][$dimensionsIndex] / $img->img_x, $this->config['maxHeight'][$dimensionsIndex] / $img->img_y);
-				   $img->scale($percentage);
-			   }
-
-			   $img->save($path . $result);
-			   $img->free();
-           }
-	   }
-
-		//delete tmp files.
-		Files::delFile($file['tmp_name']);
-		return false;
-	}
-
-	/**
-	 * Get the URL of the relative file.
-	 * basically appends the relative file to the
-	 * base_url given in config.inc.php
-	 * @param string $relative a file the relative to the base_dir
-	 * @return string the URL of the relative file.
-	 */
-	function getFileURL($relative)
-	{
-		Return Files::makeFile($this->getBaseURL(),$relative);
-	}
-
-	/**
-	 * Get the fullpath to a relative file.
-	 * @param string $relative the relative file.
-	 * @return string the full path, .ie. the base_dir + relative.
-	 */
-	function getFullPath($relative)
-	{
-		Return Files::makeFile($this->getBaseDir(),$relative);;
-	}
-
-	/**
-	 * Get the default thumbnail.
-	 * @return string default thumbnail, empty string if
-	 * the thumbnail doesn't exist.
-	 */
-	function getDefaultThumb()
-	{
-		if(is_file($this->config['default_thumbnail']))
-			Return $this->config['default_thumbnail'];
-		else
-			Return '';
-	}
-
-
-	/**
-	 * Get the thumbnail url to be displayed.
-	 * If the thumbnail exists, and it is up-to-date
-	 * the thumbnail url will be returns. If the
-	 * file is not an image, a default image will be returned.
-	 * If it is an image file, and no thumbnail exists or
-	 * the thumbnail is out-of-date (i.e. the thumbnail
-	 * modified time is less than the original file)
-	 * then a thumbs.php?img=filename.jpg is returned.
-	 * The thumbs.php url will generate a new thumbnail
-	 * on the fly. If the image is less than the dimensions
-	 * of the thumbnails, the image will be display instead.
-	 * @param string $relative the relative image file.
-	 * @return string the url of the thumbnail, be it
-	 * actually thumbnail or a script to generate the
-	 * thumbnail on the fly.
-	 */
-	function getThumbnail($relative)
-	{
-		$fullpath = Files::makeFile($this->getBaseDir(),$relative);
-
-		//not a file???
-		if(!is_file($fullpath))
-			Return $this->getDefaultThumb();
-
-		$imgInfo = @getImageSize($fullpath);
-
-		//not an image
-		if(!is_array($imgInfo))
-			Return $this->getDefaultThumb();
-
-		//the original image is smaller than thumbnails,
-		//so just return the url to the original image.
-		if ($imgInfo[0] <= $this->config['thumbnail_width']
-		 && $imgInfo[1] <= $this->config['thumbnail_height'])
-			Return $this->getFileURL($relative);
-
-		$thumbnail = $this->getThumbName($fullpath);
-
-		//check for thumbnails, if exists and
-		// it is up-to-date, return the thumbnail url
-		if(is_file($thumbnail))
-		{
-			if(filemtime($thumbnail) >= filemtime($fullpath))
-				Return $this->getThumbURL($relative);
-		}
-
-		//well, no thumbnail was found, so ask the thumbs.php
-		//to generate the thumbnail on the fly.
-		Return 'thumbs.php?img='.rawurlencode($relative);
-	}
-
-	/**
-	 * Delete and specified files.
-	 * @return boolean true if delete, false otherwise
-	 */
-	function deleteFiles()
-	{
-		if(isset($_GET['delf']))
-			$this->_delFile(rawurldecode($_GET['delf']));
-	}
-
-	/**
-	 * Delete and specified directories.
-	 * @return boolean true if delete, false otherwise
-	 */
-	function deleteDirs()
-	{
-		 if(isset($_GET['deld']))
-			return $this->_delDir(rawurldecode($_GET['deld']));
-		 else
-			 Return false;
-	}
-
-	/**
-	 * Delete the relative file, and any thumbnails.
-	 * @param string $relative the relative file.
-	 * @return boolean true if deleted, false otherwise.
-	 */
-	function _delFile($relative)
-	{
-		$fullpath = Files::makeFile($this->getBaseDir(),$relative);
-		//check that the file is an image
-		if ($this->config['validate_images'])
-		{
-			if(!is_array($this->getImageInfo($fullpath)))
-				return false; //hmmm not an Image!!???
-		}
-
-		$thumbnail = $this->getThumbName($fullpath);
-
-		if(Files::delFile($fullpath)){
-			//deleting from the DB
-			global $_course;
-			if (isset($_course) && !empty($_course) && isset($_course['code'])) {
-				$document_path = substr($fullpath, strpos($fullpath,'/document/')+9, strlen($fullpath)); //   /shared_folder/4/name
-				DocumentManager::delete_document($_course,$document_path,$fullpath);
-			}
-			Return Files::delFile($thumbnail);
-		}
-		else
-			Return false;
-	}
-
-	/**
-	 * Delete directories recursively.
-	 * @param string $relative the relative path to be deleted.
-	 * @return boolean true if deleted, false otherwise.
-	 */
-	function _delDir($relative)
-	{
-		$fullpath = Files::makePath($this->getBaseDir(),$relative);
-		//we can delete recursively	even if there are images in the dir
-
-		//if($this->countFiles($fullpath) <= 0) {
-		// now we use the default delete_document function
-		//return Files::delFolder($fullpath,true); //delete recursively.
-		global $_course;
-		if (isset($_course) && !empty($_course) && isset($_course['code'])) {
-			$path_dir = substr($fullpath, strpos($fullpath,'/document/')+9,-1); //
-			$base_dir  = substr($fullpath, 0, strlen($fullpath) - strlen($path_dir)); //
-			return DocumentManager::delete_document($_course,$path_dir,$base_dir);
-		}
-		else
-		{
-		    if($this->countFiles($fullpath) <= 0) {
-				return Files::delFolder($fullpath,true);
-		    }
-			else
-			{
-				Return false;
-			}
-
-		}
-		/*
-		}
-		else
-			Return false;
-		*/
-	}
-
-	/**
-	 * Create new directories.
-	 * If in safe_mode, nothing happens.
-	 * @return boolean true if created, false otherwise.
-	 */
-	function processNewDir()
-	{
-		if ($this->config['safe_mode'])
-			Return false;
-
-		if(isset($_GET['newDir']) && isset($_GET['dir']))
-		{
-			$newDir = rawurldecode($_GET['newDir']);
-			$dir = rawurldecode($_GET['dir']);
-			$path = Files::makePath($this->getBaseDir(),$dir);
-			$fullpath = Files::makePath($path, Files::escape($newDir));
-			if(is_dir($fullpath)) {
-				Return false;
-			} else {
-				//adding to the DB
-				// now the create_unexisting_directory will create the folder
-				//$result = Files::createFolder($fullpath);
+     */
+    function getTmpPrefix()
+    {
+        Return $this->config['tmp_prefix'];
+    }
+
+    /**
+     * Get the sub directories in the base dir.
+     * Each array element contain
+     * the relative path (relative to the base dir) as key and the
+     * full path as value.
+     * @return array of sub directries
+     * <code>array('path name' => 'full directory path', ...)</code>
+     */
+    function getDirs()
+    {
+        if (is_null($this->dirs)) {
+            $dirs = $this->_dirs($this->getBaseDir(), '/');
+            ksort($dirs);
+
+            $this->dirs = $dirs;
+        }
+
+        return $this->dirs;
+    }
+
+    /**
+     * Recursively travese the directories to get a list
+     * of accessable directories.
+     * @param string $base the full path to the current directory
+     * @param string $path the relative path name
+     * @return array of accessiable sub-directories
+     * <code>array('path name' => 'full directory path', ...)</code>
+     */
+    function _dirs($base, $path)
+    {
+        $base = Files::fixPath($base);
+        $dirs = array();
+
+        if (!$this->isValidBase()) {
+            return $dirs;
+        }
+
+        $d = @dir($base);
+
+        $in_group = api_is_in_group();
+        if ($in_group) {
+            $group_properties = GroupManager::get_group_properties($_SESSION['_gid']);
+            $group_directory = explode('/', $group_properties['directory']);
+            $group_directory = $group_directory[count($group_directory) - 1];
+        }
+
+        $user_id = api_get_user_id();
+        while (false !== ($entry = $d->read())) {
+            //If it is a directory, and it doesn't start with
+            // a dot, and if is it not the thumbnail directory
+            if (is_dir($base.$entry)
+                && substr($entry, 0, 1) != '.'
+                && strpos($entry, '_DELETED_') === false
+                && strpos($entry, 'chat_files') === false
+                && strpos($entry, 'css') === false
+                && strpos($entry, 'HotPotatoes_files') === false
+                && ($in_group || (!$in_group && strpos($entry, '_groupdocs') === false))
+                && !$this->isThumbDir($entry)
+            ) {
+                $relative = Files::fixPath($path.$entry);
+                $fullpath = Files::fixPath($base.$entry);
+
+                if ($in_group && strpos($fullpath, '_groupdocs') !== false && strpos(
+                    $fullpath,
+                    $group_directory
+                ) === false
+                ) {
+                    continue;
+                }
+                global $_course;
+                if (!empty($_course)) {
+                    $base_dir = substr($fullpath, 0, strpos($fullpath, '/document/') + 9); //
+                    $new_dir = substr($fullpath, strlen($base_dir), -1); //
+                    $doc_id = DocumentManager::get_document_id($_course, $new_dir);
+                    $visible_status = api_get_item_visibility($_course, TOOL_DOCUMENT, $doc_id);
+                }
+
+                //Teachers can access to hidden files and directories as they can in the tool documents
+                /*
+                if ($visible_status=='0' || $visible_status=='-1') {
+                    continue;
+                }
+                */
+
+                /* if (strpos($fullpath, '/shared_folder/') !== false) {
+                    if (!preg_match('/.*\/shared_folder\/$/', $fullpath)) {
+                        //all students can see the shared_folder
+                        if (strpos($fullpath, '/shared_folder/sf_user_'.$user_id.'/') !== false) {
+                            continue;
+                        }
+                    }
+                }
+                */
+                $dirs[$relative] = $fullpath;
+                $dirs = array_merge($dirs, $this->_dirs($fullpath, $relative));
+            }
+        }
+        $d->close();
+
+        Return $dirs;
+    }
+
+    /**
+     * Get all the files and directories of a relative path.
+     * @param string $path relative path to be base path.
+     * @return array of file and path information.
+     * <code>array(0=>array('relative'=>'fullpath',...), 1=>array('filename'=>fileinfo array(),...)</code>
+     * fileinfo array: <code>array('url'=>'full url',
+     *                       'relative'=>'relative to base',
+     *                        'fullpath'=>'full file path',
+     *                        'image'=>imageInfo array() false if not image,
+     *                        'stat' => filestat)</code>
+     */
+    function getFiles($path)
+    {
+        $files = array();
+        $dirs = array();
+
+        if (!$this->isValidBase()) {
+            return array($files, $dirs);
+        }
+
+        $path = Files::fixPath($path);
+        $base = Files::fixPath($this->getBaseDir());
+
+        $fullpath = Files::makePath($base, $path);
+
+        $d = @dir($fullpath);
+
+        if (empty($d)) {
+            $path = Files::fixPath('/');
+            $base = Files::fixPath($this->getBaseDir());
+            $fullpath = Files::makePath($base, $path);
+            $d = @dir($fullpath);
+        }
+
+
+        $in_group = api_is_in_group();
+        $user_id = api_get_user_id();
+
+        // check templates files in bd
+        $tbl_system_template = Database :: get_main_table(TABLE_MAIN_SYSTEM_TEMPLATE);
+
+        $sql = "SELECT image FROM $tbl_system_template ";
+        $res = Database::query($sql);
+
+        $files_templates = array();
+
+        while ($row = Database::fetch_row($res)) {
+            $files_templates[] = $row[0];
+        }
+
+        while (false !== ($entry = $d->read())) {
+            if (in_array($entry, $files_templates)) {
+                continue;
+            }
+            if (substr($entry, 0, 1) != '.' //not a dot file or directory
+                && strpos($entry, '_DELETED_') === false
+                && strpos($entry, 'chat_files') === false
+                && strpos($entry, 'css') === false
+                && strpos($entry, 'HotPotatoes_files') === false
+                && ($in_group || (!$in_group && strpos($entry, '_groupdocs') === false))
+            ) {
+                $is_dir = is_dir($fullpath.$entry);
+                if ($is_dir) {
+                    $dir_entry = Files::fixPath($fullpath.$entry);
+                    /*
+                    if (strpos($dir_entry, '/shared_folder/') !== false)
+                    {
+                        if (!preg_match('/.*\/shared_folder\/$/', $dir_entry))
+                        {
+                            //all students can see the shared_folder
+                            if (strpos($dir_entry, '/shared_folder/sf_user_'.$user_id.'/') === true)
+                            {
+                                continue;
+                            }
+                        }
+                    }
+                    */
+                }
+
+                if ($is_dir && !$this->isThumbDir($entry)) {
+                    global $_course;
+                    if (isset($_course) && !empty($_course) && isset($_course['code'])) {
+                        //checking visibility
+                        $base_dir = substr($dir_entry, 0, strpos($dir_entry, '/document/') + 9);
+                        $new_dir = substr($dir_entry, strlen($base_dir), -1); //
+                        $doc_id = DocumentManager::get_document_id($_course, $new_dir);
+                        $visible_status = api_get_item_visibility($_course, TOOL_DOCUMENT, $doc_id);
+                    }
+
+                    //Teachers can access to hidden files and directories as they can in the tool documents
+                    /*
+                    if ($visible_status=='0' || $visible_status=='-1') {
+                        continue;
+                    }
+                    */
+                    $relative = Files::fixPath($path.$entry);
+                    $full = Files::fixPath($fullpath.$entry);
+                    $count = $this->countFiles($full);
+                    $dirs[$relative] = array('fullpath' => $full, 'entry' => $entry, 'count' => $count);
+                } else {
+                    if (is_file($fullpath.$entry) && !$this->isThumb($entry) && !$this->isTmpFile($entry)) {
+                        $img = $this->getImageInfo($fullpath.$entry);
+                        if (!(!is_array($img) && $this->config['validate_images'])) {
+                            global $_course;
+
+                            if (!empty($_course) && isset($_course['code'])) {
+                                //checking visibility
+                                $base_dir = substr($fullpath.$entry, 0, strpos($fullpath.$entry, '/document/') + 9);
+                                $new_dir = substr($fullpath.$entry, strlen($base_dir));
+                                $doc_id = DocumentManager::get_document_id($_course, $new_dir);
+                                $visible_status = api_get_item_visibility($_course, TOOL_DOCUMENT, $doc_id);
+                            }
+
+                            //Teachers can access to hidden files and directories as they can in the tool documents
+                            /*
+                            if ($visible_status=='0' || $visible_status=='-1') {
+                                continue;
+                            }
+                            */
+
+                            $file['url'] = Files::makePath($this->config['base_url'], $path).$entry;
+                            $file['relative'] = $path.$entry;
+                            $file['fullpath'] = $fullpath.$entry;
+                            $file['image'] = $img;
+                            $file['stat'] = stat($fullpath.$entry);
+                            $files[$entry] = $file;
+                        }
+                    }
+                }
+            }
+        }
+        $d->close();
+        ksort($dirs);
+        ksort($files);
+
+        return array($dirs, $files);
+    }
+
+    /**
+     * Count the number of files and directories in a given folder
+     * minus the thumbnail folders and thumbnails.
+     */
+    function countFiles($path)
+    {
+        $total = 0;
+
+        if (is_dir($path)) {
+            $d = @dir($path);
+
+            while (false !== ($entry = $d->read())) {
+                //echo $entry."<br />";
+                if (substr($entry, 0, 1) != '.'
+                    && !$this->isThumbDir($entry)
+                    && !$this->isTmpFile($entry)
+                    && !$this->isThumb($entry)
+                ) {
+                    $total++;
+                }
+            }
+            $d->close();
+        }
+
+        return $total;
+    }
+
+    /**
+     * Get image size information.
+     * @param string $file the image file
+     * @return array of getImageSize information,
+     *  false if the file is not an image.
+     */
+    function getImageInfo($file)
+    {
+        Return @getImageSize($file);
+    }
+
+    /**
+     * Check if the file contains the thumbnail prefix.
+     * @param string $file filename to be checked
+     * @return true if the file contains the thumbnail prefix, false otherwise.
+     */
+    function isThumb($file)
+    {
+        $len = strlen($this->config['thumbnail_prefix']);
+        if (substr($file, 0, $len) == $this->config['thumbnail_prefix']) {
+            Return true;
+        } else {
+            Return false;
+        }
+    }
+
+    /**
+     * Check if the given directory is a thumbnail directory.
+     * @param string $entry directory name
+     * @return true if it is a thumbnail directory, false otherwise
+     */
+    function isThumbDir($entry)
+    {
+        if (!$this->config['thumbnail_dir']
+            || strlen(trim($this->config['thumbnail_dir'])) == 0
+        ) {
+            Return false;
+        } else {
+            Return ($entry == $this->config['thumbnail_dir']);
+        }
+    }
+
+    /**
+     * Check if the given file is a tmp file.
+     * @param string $file file name
+     * @return boolean true if it is a tmp file, false otherwise
+     */
+    function isTmpFile($file)
+    {
+        $len = strlen($this->config['tmp_prefix']);
+        if (substr($file, 0, $len) == $this->config['tmp_prefix']) {
+            Return true;
+        } else {
+            Return false;
+        }
+    }
+
+    /**
+     * For a given image file, get the respective thumbnail filename
+     * no file existence check is done.
+     * @param string $fullpathfile the full path to the image file
+     * @return string of the thumbnail file
+     */
+    function getThumbName($fullpathfile)
+    {
+        $path_parts = pathinfo($fullpathfile);
+
+        $thumbnail = $this->config['thumbnail_prefix'].$path_parts['basename'];
+
+        if ($this->config['safe_mode']
+            || strlen(trim($this->config['thumbnail_dir'])) == 0
+        ) {
+            Return Files::makeFile($path_parts['dirname'], $thumbnail);
+        } else {
+            if (strlen(trim($this->config['thumbnail_dir'])) > 0) {
+                $path = Files::makePath($path_parts['dirname'], $this->config['thumbnail_dir']);
+                if (!is_dir($path)) {
+                    Files::createFolder($path);
+                }
+
+                Return Files::makeFile($path, $thumbnail);
+            } else //should this ever happen?
+            {
+                //error_log('ImageManager: Error in creating thumbnail name');
+            }
+        }
+    }
+
+    /**
+     * Similar to getThumbName, but returns the URL, base on the
+     * given base_url in config.inc.php
+     * @param string $relative the relative image file name,
+     * relative to the base_dir path
+     * @return string the url of the thumbnail
+     */
+    function getThumbURL($relative)
+    {
+        $path_parts = pathinfo($relative);
+        $thumbnail = $this->config['thumbnail_prefix'].$path_parts['basename'];
+        if ($path_parts['dirname'] == '\\') {
+            $path_parts['dirname'] = '/';
+        }
+
+        if ($this->config['safe_mode']
+            || strlen(trim($this->config['thumbnail_dir'])) == 0
+        ) {
+            $path = Files::fixPath($path_parts['dirname']);
+            $url_path = Files::makePath($this->getBaseURL(), $path);
+
+            Return Files::makeFile($url_path, $thumbnail);
+        } else {
+            if (strlen(trim($this->config['thumbnail_dir'])) > 0) {
+                $path = Files::makePath($path_parts['dirname'], $this->config['thumbnail_dir']);
+                $url_path = Files::makePath($this->getBaseURL(), $path);
+
+                Return Files::makeFile($url_path, $thumbnail);
+            } else //should this ever happen?
+            {
+                //error_log('ImageManager: Error in creating thumbnail url');
+            }
+
+        }
+    }
+
+    /**
+     * Check if the given path is part of the subdirectories
+     * under the base_dir.
+     * @param string $path the relative path to be checked
+     * @return boolean true if the path exists, false otherwise
+     */
+    function validRelativePath($path)
+    {
+        $dirs = $this->getDirs();
+        if ($path == '/' || $path == '') {
+            Return true;
+        }
+        //check the path given in the url against the
+        //list of paths in the system.
+        for ($i = 0; $i < count($dirs); $i++) {
+            $key = key($dirs);
+            //we found the path
+            if ($key == $path) {
+                Return true;
+            }
+
+            next($dirs);
+        }
+
+        Return false;
+    }
+
+    /**
+     * Process uploaded files, assumes the file is in
+     * $_FILES['upload'] and $_POST['dir'] is set.
+     * The dir must be relative to the base_dir and exists.
+     * If 'validate_images' is set to true, only file with
+     * image dimensions will be accepted.
+     * @return null
+     */
+    function processUploads()
+    {
+        if (!$this->isValidBase()) {
+            return;
+        }
+
+        $relative = null;
+        if (isset($_POST['dir'])) {
+            $relative = rawurldecode($_POST['dir']);
+        } else {
+            return;
+        }
+
+        //check for the file, and must have valid relative path
+        if (isset($_FILES['upload']) && $this->validRelativePath($relative)) {
+            return $this->_processFiles($relative, $_FILES['upload']);
+        }
+    }
+
+    /**
+     * Process upload files. The file must be an
+     * uploaded file. If 'validate_images' is set to
+     * true, only images will be processed. Any duplicate
+     * file will be renamed. See Files::copyFile for details
+     * on renaming.
+     * @param string $relative the relative path where the file
+     * should be copied to.
+     * @param array $file the uploaded file from $_FILES
+     * @return boolean true if the file was processed successfully,
+     * false otherwise
+     */
+    function _processFiles($relative, $file)
+    {
+        global $_course;
+        if ($file['error'] != 0) {
+            return false;
+        }
+
+        if (!is_file($file['tmp_name'])) {
+            return false;
+        }
+
+        if (!is_uploaded_file($file['tmp_name'])) {
+            Files::delFile($file['tmp_name']);
+
+            return false;
+        }
+
+        $file['name'] = replace_dangerous_char($file['name'], 'strict');
+        $file_name = $file['name'];
+        $extension = explode('.', $file_name);
+        $count = count($extension);
+        if ($count == 1) {
+            $extension = '';
+        } else {
+            $extension = strtolower($extension[$count - 1]);
+        }
+
+        // Checking for image by file extension first, using the configuration file.
+        if (!in_array($extension, $this->config['accepted_extensions'])) {
+            Files::delFile($file['tmp_name']);
+
+            return false;
+        }
+
+        // Second, filtering using a special function of the system.
+        $result = FileManager::filter_extension($file_name);
+        if (($result == 0) || ($file_name != $file['name'])) {
+            Files::delFile($file['tmp_name']);
+
+            return false;
+        }
+
+        // Checking for a valid image by reading binary file (partially in most cases).
+        if ($this->config['validate_images']) {
+            $imgInfo = @getImageSize($file['tmp_name']);
+            if (!is_array($imgInfo)) {
+                Files::delFile($file['tmp_name']);
+
+                return false;
+            }
+        }
+
+        //now copy the file
+        $path = Files::makePath($this->getBaseDir(), $relative);
+        $result = Files::copyFile($file['tmp_name'], $path, $file['name']);
+
+        //no copy error
+        if (!is_int($result)) {
+
+            if (isset($_course) && !empty($_course) && isset($_course['code'])) {
+                //adding the document to the DB
+                global $to_group_id;
+
+                // looking for the /document/ folder
+                $document_path = substr(
+                    $path,
+                    strpos($path, '/document/') + 9,
+                    strlen($path)
+                ); //   /shared_folder/4/name
+                $document_path .= $result;
+
+                $chamiloFile = $file['name'];
+                $chamiloFileSize = $file['size'];
+                if (!empty($group_properties['directory'])) {
+                    $chamiloFolder = $group_properties['directory'].$chamiloFolder;
+                }
+
+                $doc_id = FileManager::add_document($_course, $document_path, 'file', $chamiloFileSize, $chamiloFile);
+                $current_session_id = api_get_session_id();
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $doc_id,
+                    'DocumentAdded',
+                    api_get_user_id(),
+                    $to_group_id,
+                    null,
+                    null,
+                    null,
+                    $current_session_id
+                ); //get Dokeos
+            }
+
+            /*
+            if (!(api_is_platform_admin() || api_is_course_admin())) {
+                //setting invisible by default for the students
+                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id());
+            }
+            */
+            $dimensionsIndex = isset($_REQUEST['uploadSize']) ? $_REQUEST['uploadSize'] : 0;
+            // If maximum size is specified, constrain image to it.
+            if ($this->config['maxWidth'][$dimensionsIndex] > 0 && $this->config['maxHeight'][$dimensionsIndex] > 0) {
+                $img = Image_Transform::factory(IMAGE_CLASS);
+                $img->load($path.$result);
+
+                // image larger than max dimensions?
+                if ($img->img_x > $this->config['maxWidth'][$dimensionsIndex] || $img->img_y > $this->config['maxHeight'][$dimensionsIndex]) {
+                    $percentage = min(
+                        $this->config['maxWidth'][$dimensionsIndex] / $img->img_x,
+                        $this->config['maxHeight'][$dimensionsIndex] / $img->img_y
+                    );
+                    $img->scale($percentage);
+                }
+
+                $img->save($path.$result);
+                $img->free();
+            }
+        }
+
+        //delete tmp files.
+        Files::delFile($file['tmp_name']);
+
+        return false;
+    }
+
+    /**
+     * Get the URL of the relative file.
+     * basically appends the relative file to the
+     * base_url given in config.inc.php
+     * @param string $relative a file the relative to the base_dir
+     * @return string the URL of the relative file.
+     */
+    function getFileURL($relative)
+    {
+        Return Files::makeFile($this->getBaseURL(), $relative);
+    }
+
+    /**
+     * Get the fullpath to a relative file.
+     * @param string $relative the relative file.
+     * @return string the full path, .ie. the base_dir + relative.
+     */
+    function getFullPath($relative)
+    {
+        Return Files::makeFile($this->getBaseDir(), $relative);
+        ;
+    }
+
+    /**
+     * Get the default thumbnail.
+     * @return string default thumbnail, empty string if
+     * the thumbnail doesn't exist.
+     */
+    function getDefaultThumb()
+    {
+        if (is_file($this->config['default_thumbnail'])) {
+            Return $this->config['default_thumbnail'];
+        } else {
+            Return '';
+        }
+    }
+
+
+    /**
+     * Get the thumbnail url to be displayed.
+     * If the thumbnail exists, and it is up-to-date
+     * the thumbnail url will be returns. If the
+     * file is not an image, a default image will be returned.
+     * If it is an image file, and no thumbnail exists or
+     * the thumbnail is out-of-date (i.e. the thumbnail
+     * modified time is less than the original file)
+     * then a thumbs.php?img=filename.jpg is returned.
+     * The thumbs.php url will generate a new thumbnail
+     * on the fly. If the image is less than the dimensions
+     * of the thumbnails, the image will be display instead.
+     * @param string $relative the relative image file.
+     * @return string the url of the thumbnail, be it
+     * actually thumbnail or a script to generate the
+     * thumbnail on the fly.
+     */
+    function getThumbnail($relative)
+    {
+        $fullpath = Files::makeFile($this->getBaseDir(), $relative);
+
+        //not a file???
+        if (!is_file($fullpath)) {
+            Return $this->getDefaultThumb();
+        }
+
+        $imgInfo = @getImageSize($fullpath);
+
+        //not an image
+        if (!is_array($imgInfo)) {
+            Return $this->getDefaultThumb();
+        }
+
+        //the original image is smaller than thumbnails,
+        //so just return the url to the original image.
+        if ($imgInfo[0] <= $this->config['thumbnail_width']
+            && $imgInfo[1] <= $this->config['thumbnail_height']
+        ) {
+            Return $this->getFileURL($relative);
+        }
+
+        $thumbnail = $this->getThumbName($fullpath);
+
+        //check for thumbnails, if exists and
+        // it is up-to-date, return the thumbnail url
+        if (is_file($thumbnail)) {
+            if (filemtime($thumbnail) >= filemtime($fullpath)) {
+                Return $this->getThumbURL($relative);
+            }
+        }
+
+        //well, no thumbnail was found, so ask the thumbs.php
+        //to generate the thumbnail on the fly.
+        Return 'thumbs.php?img='.rawurlencode($relative);
+    }
+
+    /**
+     * Delete and specified files.
+     * @return boolean true if delete, false otherwise
+     */
+    function deleteFiles()
+    {
+        if (isset($_GET['delf'])) {
+            $this->_delFile(rawurldecode($_GET['delf']));
+        }
+    }
+
+    /**
+     * Delete and specified directories.
+     * @return boolean true if delete, false otherwise
+     */
+    function deleteDirs()
+    {
+        if (isset($_GET['deld'])) {
+            return $this->_delDir(rawurldecode($_GET['deld']));
+        } else {
+            Return false;
+        }
+    }
+
+    /**
+     * Delete the relative file, and any thumbnails.
+     * @param string $relative the relative file.
+     * @return boolean true if deleted, false otherwise.
+     */
+    function _delFile($relative)
+    {
+        $fullpath = Files::makeFile($this->getBaseDir(), $relative);
+        //check that the file is an image
+        if ($this->config['validate_images']) {
+            if (!is_array($this->getImageInfo($fullpath))) {
+                return false;
+            } //hmmm not an Image!!???
+        }
+
+        $thumbnail = $this->getThumbName($fullpath);
+
+        if (Files::delFile($fullpath)) {
+            //deleting from the DB
+            global $_course;
+            if (isset($_course) && !empty($_course) && isset($_course['code'])) {
+                $document_path = substr(
+                    $fullpath,
+                    strpos($fullpath, '/document/') + 9,
+                    strlen($fullpath)
+                ); //   /shared_folder/4/name
+                DocumentManager::delete_document($_course, $document_path, $fullpath);
+            }
+
+            Return Files::delFile($thumbnail);
+        } else {
+            Return false;
+        }
+    }
+
+    /**
+     * Delete directories recursively.
+     * @param string $relative the relative path to be deleted.
+     * @return boolean true if deleted, false otherwise.
+     */
+    function _delDir($relative)
+    {
+        $fullpath = Files::makePath($this->getBaseDir(), $relative);
+        //we can delete recursively	even if there are images in the dir
+
+        //if($this->countFiles($fullpath) <= 0) {
+        // now we use the default delete_document function
+        //return Files::delFolder($fullpath,true); //delete recursively.
+        global $_course;
+        if (isset($_course) && !empty($_course) && isset($_course['code'])) {
+            $path_dir = substr($fullpath, strpos($fullpath, '/document/') + 9, -1); //
+            $base_dir = substr($fullpath, 0, strlen($fullpath) - strlen($path_dir)); //
+            return DocumentManager::delete_document($_course, $path_dir, $base_dir);
+        } else {
+            if ($this->countFiles($fullpath) <= 0) {
+                return Files::delFolder($fullpath, true);
+            } else {
+                Return false;
+            }
+
+        }
+        /*
+        }
+        else
+            Return false;
+        */
+    }
+
+    /**
+     * Create new directories.
+     * If in safe_mode, nothing happens.
+     * @return boolean true if created, false otherwise.
+     */
+    function processNewDir()
+    {
+        if ($this->config['safe_mode']) {
+            Return false;
+        }
+
+        if (isset($_GET['newDir']) && isset($_GET['dir'])) {
+            $newDir = rawurldecode($_GET['newDir']);
+            $dir = rawurldecode($_GET['dir']);
+            $path = Files::makePath($this->getBaseDir(), $dir);
+            $fullpath = Files::makePath($path, Files::escape($newDir));
+            if (is_dir($fullpath)) {
+                Return false;
+            } else {
+                //adding to the DB
+                // now the FileManager::create_unexisting_directory will create the folder
+                //$result = Files::createFolder($fullpath);
 
                 global $_course;
                 if (isset($_course) && !empty($_course) && isset($_course['code'])) {
-                //@todo make this str to functions
-					$base_dir = substr($path, 0, strpos($path,'/document/')+9); //
-					$new_dir  = substr($fullpath, strlen($base_dir),-1); //
-					$created_dir = create_unexisting_directory($_course, api_get_user_id(), api_get_session_id(), 0,0, $base_dir, $new_dir,$newDir);
-					$doc_id = DocumentManager::get_document_id($_course, $new_dir );
-					$current_session_id = api_get_session_id();
-					api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id(),null,null,null,null,$current_session_id);
-				} else {
-				 	return Files::createFolder($fullpath);
-				}
-				return true;
-			}
-		}
-	}
-
-	/**
-	 * Do some graphic library method checkings
-	 * @param string $library the graphics library, GD, NetPBM, or IM.
-	 * @param string $method the method to check.
-	 * @return boolean true if able, false otherwise.
-	 */
-	function validGraphicMethods($library,$method)
-	{
-		switch ($library)
-		{
-			case 'GD':
-				return $this->_checkGDLibrary($method);
-				break;
-			case 'NetPBM':
-				return $this->_checkNetPBMLibrary($method);
-				break;
-			case 'IM':
-				return $this->_checkIMLibrary($method);
-		}
-		return false;
-	}
-
-	function _checkIMLibrary($method)
-	{
-		//ImageMagick goes throught 1 single executable
-		if(is_file(Files::fixPath(IMAGE_TRANSFORM_LIB_PATH).'convert'))
-			return true;
-		else
-			return false;
-	}
-
-	/**
-	 * Check the GD library functionality.
-	 * @param string $library the graphics library, GD, NetPBM, or IM.
-	 * @return boolean true if able, false otherwise.
-	 */
-	function _checkGDLibrary($method)
-	{
-		$errors = array();
-		switch($method)
-		{
-			case 'create':
-				$errors['createjpeg'] = function_exists('imagecreatefromjpeg');
-				$errors['creategif'] = function_exists('imagecreatefromgif');
-				$errors['createpng'] = function_exists('imagecreatefrompng');
-				break;
-			case 'modify':
-				$errors['create'] = function_exists('ImageCreateTrueColor') || function_exists('ImageCreate');
-				$errors['copy'] = function_exists('ImageCopyResampled') || function_exists('ImageCopyResized');
-				break;
-			case 'save':
-				$errors['savejpeg'] = function_exists('imagejpeg');
-				$errors['savegif'] = function_exists('imagegif');
-				$errors['savepng'] = function_exists('imagepng');
-				break;
-		}
-
-		return $errors;
-	}
+                    //@todo make this str to functions
+                    $base_dir = substr($path, 0, strpos($path, '/document/') + 9); //
+                    $new_dir = substr($fullpath, strlen($base_dir), -1); //
+                    $created_dir = FileManager::create_unexisting_directory(
+                        $_course,
+                        api_get_user_id(),
+                        api_get_session_id(),
+                        0,
+                        0,
+                        $base_dir,
+                        $new_dir,
+                        $newDir
+                    );
+                    $doc_id = DocumentManager::get_document_id($_course, $new_dir);
+                    $current_session_id = api_get_session_id();
+                    api_item_property_update(
+                        $_course,
+                        TOOL_DOCUMENT,
+                        $doc_id,
+                        'invisible',
+                        api_get_user_id(),
+                        null,
+                        null,
+                        null,
+                        null,
+                        $current_session_id
+                    );
+                } else {
+                    return Files::createFolder($fullpath);
+                }
+
+                return true;
+            }
+        }
+    }
+
+    /**
+     * Do some graphic library method checkings
+     * @param string $library the graphics library, GD, NetPBM, or IM.
+     * @param string $method the method to check.
+     * @return boolean true if able, false otherwise.
+     */
+    function validGraphicMethods($library, $method)
+    {
+        switch ($library) {
+            case 'GD':
+                return $this->_checkGDLibrary($method);
+                break;
+            case 'NetPBM':
+                return $this->_checkNetPBMLibrary($method);
+                break;
+            case 'IM':
+                return $this->_checkIMLibrary($method);
+        }
+        return false;
+    }
+
+    function _checkIMLibrary($method)
+    {
+        //ImageMagick goes throught 1 single executable
+        if (is_file(Files::fixPath(IMAGE_TRANSFORM_LIB_PATH).'convert')) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Check the GD library functionality.
+     * @param string $library the graphics library, GD, NetPBM, or IM.
+     * @return boolean true if able, false otherwise.
+     */
+    function _checkGDLibrary($method)
+    {
+        $errors = array();
+        switch ($method) {
+            case 'create':
+                $errors['createjpeg'] = function_exists('imagecreatefromjpeg');
+                $errors['creategif'] = function_exists('imagecreatefromgif');
+                $errors['createpng'] = function_exists('imagecreatefrompng');
+                break;
+            case 'modify':
+                $errors['create'] = function_exists('ImageCreateTrueColor') || function_exists('ImageCreate');
+                $errors['copy'] = function_exists('ImageCopyResampled') || function_exists('ImageCopyResized');
+                break;
+            case 'save':
+                $errors['savejpeg'] = function_exists('imagejpeg');
+                $errors['savegif'] = function_exists('imagegif');
+                $errors['savepng'] = function_exists('imagepng');
+                break;
+        }
+
+        return $errors;
+    }
 }
 
 ?>

+ 76 - 44
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_create_folder.php

@@ -10,7 +10,7 @@
  * @author Juan Carlos Ra�a
  * @since 18/January/2009
  */
-require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
+require_once(dirname(__FILE__).DIRECTORY_SEPARATOR."inc".DIRECTORY_SEPARATOR."config.php");
 //@ob_start(); //Disabled for integration with Chamilo
 //displayArray($_POST); //Disabled for integration with Chamilo
 //writeInfo(@ob_get_clean()); //Disabled for integration with Chamilo
@@ -20,7 +20,11 @@ $info = "";
 /* 	$_POST['new_folder'] = substr(md5(time()), 1, 5);
   $_POST['currentFolderPath'] = "../../uploaded/"; */
 $_POST['new_folder'] = htmlentities($_POST['new_folder'], ENT_QUOTES); //Chamilo improve security
-$_POST['new_folder'] = str_replace(' ', '_', $_POST['new_folder']); //Interaction with Chamilo. Because fix long names. See: ajaxfilemanager/inc/class.manager.php
+$_POST['new_folder'] = str_replace(
+    ' ',
+    '_',
+    $_POST['new_folder']
+); //Interaction with Chamilo. Because fix long names. See: ajaxfilemanager/inc/class.manager.php
 $_POST['currentFolderPath'] = htmlentities($_POST['currentFolderPath'], ENT_QUOTES); //Chamilo improve security
 
 if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_NEWFOLDER) {
@@ -29,55 +33,83 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_NEWFOLDER) {
     $error = ERR_FOLDER_NAME_EMPTY;
 } elseif (!preg_match("/^[a-zA-Z0-9_\- ]+$/", $_POST['new_folder'])) {
     $error = ERR_FOLDER_FORMAT;
-} else if (empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath'])) {
-    $error = ERR_FOLDER_PATH_NOT_ALLOWED;
-} elseif (file_exists(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder'])) {
-    $error = ERR_FOLDER_EXISTS;
 } else {
-    include_once CLASS_FILE;
-    $file = new file();
-    if ($file->mkdir(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder'], 0775)) {
-        include_once CLASS_MANAGER;
-        $manager = new manager(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder'], false);
-        $pathInfo = $manager->getFolderInfo(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder']);
+    if (empty($_POST['currentFolderPath']) || !isUnderRoot($_POST['currentFolderPath'])) {
+        $error = ERR_FOLDER_PATH_NOT_ALLOWED;
+    } elseif (file_exists(addTrailingSlash($_POST['currentFolderPath']).$_POST['new_folder'])) {
+        $error = ERR_FOLDER_EXISTS;
+    } else {
+        include_once CLASS_FILE;
+        $file = new file();
+        if ($file->mkdir(addTrailingSlash($_POST['currentFolderPath']).$_POST['new_folder'], 0775)) {
+            include_once CLASS_MANAGER;
+            $manager = new manager(addTrailingSlash($_POST['currentFolderPath']).$_POST['new_folder'], false);
+            $pathInfo = $manager->getFolderInfo(addTrailingSlash($_POST['currentFolderPath']).$_POST['new_folder']);
 
-        //bridge to Chamilo
-        if (!empty($_course['path'])) {
-            //only inside courses
-            $mainPath = '../../../../../../../courses/' . $_course['path'] . '/document/'; //get Chamilo
-            $fullPath = $_POST['currentFolderPath'] . $_POST['new_folder']; //get Ajaxfilemanager
-            $chamiloPath = substr($fullPath, strlen($mainPath) - strlen($fullPath) - 1);
-            $_POST['new_folder'] = str_replace('_', ' ', $_POST['new_folder']); //Restore for interaction with Chamilo. Because fix long names. See: ajaxfilemanager/inc/class.manager.php
-            $chamiloFile = $_POST['new_folder']; //get Ajaxfilemanager
+            //bridge to Chamilo
+            if (!empty($_course['path'])) {
+                //only inside courses
+                $mainPath = '../../../../../../../courses/'.$_course['path'].'/document/'; //get Chamilo
+                $fullPath = $_POST['currentFolderPath'].$_POST['new_folder']; //get Ajaxfilemanager
+                $chamiloPath = substr($fullPath, strlen($mainPath) - strlen($fullPath) - 1);
+                $_POST['new_folder'] = str_replace(
+                    '_',
+                    ' ',
+                    $_POST['new_folder']
+                ); //Restore for interaction with Chamilo. Because fix long names. See: ajaxfilemanager/inc/class.manager.php
+                $chamiloFile = $_POST['new_folder']; //get Ajaxfilemanager
 
-            $doc_id = add_document($_course, $chamiloPath, 'folder', 0, $chamiloFile); //get Chamilo
-            $current_session_id = api_get_session_id(); //get Chamilo
-            api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
-            api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
-        }
-        // end bridge to Chamilo
+                $doc_id = FileManager::add_document($_course, $chamiloPath, 'folder', 0, $chamiloFile); //get Chamilo
+                $current_session_id = api_get_session_id(); //get Chamilo
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $doc_id,
+                    'FolderCreated',
+                    api_get_user_id(),
+                    $to_group_id,
+                    null,
+                    null,
+                    null,
+                    $current_session_id
+                ); //get Chamilo
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $doc_id,
+                    'invisible',
+                    api_get_user_id(),
+                    $to_group_id,
+                    null,
+                    null,
+                    null,
+                    $current_session_id
+                ); //get Chamilo
+            }
+            // end bridge to Chamilo
 
-        foreach ($pathInfo as $k => $v) {
-            switch ($k) {
-                case "ctime";
-                case "mtime":
-                case "atime":
-                    $v = date(DATE_TIME_FORMAT, $v);
-                    break;
-                case 'name':
-                    $info .= sprintf(", %s:'%s'", 'short_name', shortenFileName($v));
-                    break;
-                case 'cssClass':
-                    $v = 'folderEmpty';
-                    break;
+            foreach ($pathInfo as $k => $v) {
+                switch ($k) {
+                    case "ctime";
+                    case "mtime":
+                    case "atime":
+                        $v = date(DATE_TIME_FORMAT, $v);
+                        break;
+                    case 'name':
+                        $info .= sprintf(", %s:'%s'", 'short_name', shortenFileName($v));
+                        break;
+                    case 'cssClass':
+                        $v = 'folderEmpty';
+                        break;
+                }
+                $info .= sprintf(", %s:'%s'", $k, $v);
             }
-            $info .= sprintf(", %s:'%s'", $k, $v);
+        } else {
+            $error = ERR_FOLDER_CREATION_FAILED;
         }
-    } else {
-        $error = ERR_FOLDER_CREATION_FAILED;
+        //$error = "For security reason, folder creation function has been disabled.";
     }
-    //$error = "For security reason, folder creation function has been disabled.";
 }
-echo "error:'" . $error . "'";
+echo "error:'".$error."'";
 echo $info;
 echo "}";

+ 161 - 22
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_paste.php

@@ -82,9 +82,14 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                          */
                         if (!empty($_course['path'])) {
 
-                            $mainPath = getParentFolderPath($folderInfo['path']); // from ajaxfilemanager sample ../../../../../../../courses/TEST/document/
+                            $mainPath = getParentFolderPath(
+                                $folderInfo['path']
+                            ); // from ajaxfilemanager sample ../../../../../../../courses/TEST/document/
                             $fullPath = $tem['final_path']; // from ajaxfilemanager sample ../../../../../../../courses/TEST/document/icons/book_highlight.jpg
-                            $chamiloFolder = substr($fullPath, strlen($mainPath) - strlen($fullPath) - 1); // sample /icons/book_highlight.jpg or /icons
+                            $chamiloFolder = substr(
+                                $fullPath,
+                                strlen($mainPath) - strlen($fullPath) - 1
+                            ); // sample /icons/book_highlight.jpg or /icons
                             $chamiloFile = $tem['name']; //get ajaxmanager
                             $chamiloFileSize = filesize($fullPath); //get ajaxmanager
                             if (!empty($group_properties['directory'])) {
@@ -95,7 +100,11 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                 $full_old_path = $doc; // get from ajaxfilemanager sample ../../../../../../../courses/TEST/document/book_highlight.jpg or if you select a folder: ../../../../../../../courses/TEST/document/trainer/
                                 if (is_dir($full_old_path)) {
                                     //update first folder
-                                    $old_path = substr($full_old_path, strlen($mainPath) - strlen($full_old_path) - 1, -1);
+                                    $old_path = substr(
+                                        $full_old_path,
+                                        strlen($mainPath) - strlen($full_old_path) - 1,
+                                        -1
+                                    );
                                     if (!empty($group_properties['directory'])) {
                                         $old_path = $group_properties['directory'].$old_path; //get Chamilo
                                     }
@@ -105,7 +114,18 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                     $curdirpath = $new_path;
                                     $doc_id = DocumentManager::get_document_id($_course, $curdirpath); //Chamilo
                                     $current_session_id = api_get_session_id();
-                                    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderMoved', api_get_user_id(), $to_group_id, null, null, null, $current_session_id);
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $doc_id,
+                                        'FolderMoved',
+                                        api_get_user_id(),
+                                        $to_group_id,
+                                        null,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    );
                                     // update database: inside subdirectories and files
                                     $course_dir = $_course['path']."/document"; //get Chamilo
                                     $sys_course_path = api_get_path(SYS_COURSE_PATH); //get Chamilo
@@ -140,13 +160,20 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                         //Sample $item is C:/xampp/htdocs/chamilo/courses/TEST/document/books/book_highlight.jpg
                                         $file_orig = basename($item);
                                         if ($file_orig[0] != '.' && !in_array($invisibleFileNames)) {
-                                            $source_item = substr($item, (strlen($base_work_dir) - strlen($item))); // sample /books/book_highlight.jpg or /books
+                                            $source_item = substr(
+                                                $item,
+                                                (strlen($base_work_dir) - strlen($item))
+                                            ); // sample /books/book_highlight.jpg or /books
                                             $target_item = $source_item;
                                             $chamiloFolder = $target_item;
                                             $chamiloFile = basename($target_item);
                                             //
                                             if (is_dir($item)) {
-                                                $old_path = substr($full_old_path, strlen($mainPath) - strlen($full_old_path) - 1, -1);
+                                                $old_path = substr(
+                                                    $full_old_path,
+                                                    strlen($mainPath) - strlen($full_old_path) - 1,
+                                                    -1
+                                                );
                                                 if (!empty($group_properties['directory'])) {
                                                     $old_path = $group_properties['directory'].$old_path; //get Chamilo
                                                 }
@@ -154,11 +181,28 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                                 $dbTable = Database::get_course_table(TABLE_DOCUMENT); //Chamilo
                                                 FileManager::update_db_info('update', $old_path, $new_path); //Chamilo
                                                 $curdirpath = $new_path;
-                                                $doc_id = DocumentManager::get_document_id($_course, $curdirpath); //Chamilo
+                                                $doc_id = DocumentManager::get_document_id(
+                                                    $_course,
+                                                    $curdirpath
+                                                ); //Chamilo
                                                 $current_session_id = api_get_session_id();
-                                                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderMoved', api_get_user_id(), $to_group_id, null, null, null, $current_session_id);
+                                                api_item_property_update(
+                                                    $_course,
+                                                    TOOL_DOCUMENT,
+                                                    $doc_id,
+                                                    'FolderMoved',
+                                                    api_get_user_id(),
+                                                    $to_group_id,
+                                                    null,
+                                                    null,
+                                                    null,
+                                                    $current_session_id
+                                                );
                                             } elseif (is_file($item)) {
-                                                $old_path = substr($full_old_path, strlen($mainPath) - strlen($full_old_path) - 1);
+                                                $old_path = substr(
+                                                    $full_old_path,
+                                                    strlen($mainPath) - strlen($full_old_path) - 1
+                                                );
                                                 if (!empty($group_properties['directory'])) {
                                                     $old_path = $group_properties['directory'].$old_path; //get Chamilo
                                                 }
@@ -167,9 +211,23 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                                 FileManager::update_db_info('update', $old_path, $new_path); //Chamilo
                                                 //update items
                                                 $curdirpath = $new_path;
-                                                $doc_id = DocumentManager::get_document_id($_course, $curdirpath); //Chamilo
+                                                $doc_id = DocumentManager::get_document_id(
+                                                    $_course,
+                                                    $curdirpath
+                                                ); //Chamilo
                                                 $current_session_id = api_get_session_id();
-                                                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentMoved', api_get_user_id(), $to_group_id, null, null, null, $current_session_id);
+                                                api_item_property_update(
+                                                    $_course,
+                                                    TOOL_DOCUMENT,
+                                                    $doc_id,
+                                                    'DocumentMoved',
+                                                    api_get_user_id(),
+                                                    $to_group_id,
+                                                    null,
+                                                    null,
+                                                    null,
+                                                    $current_session_id
+                                                );
                                             }
                                         }
                                     }
@@ -186,14 +244,42 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                     $curdirpath = $new_path;
                                     $doc_id = DocumentManager::get_document_id($_course, $curdirpath);
                                     $current_session_id = api_get_session_id();
-                                    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentMoved', api_get_user_id(), $to_group_id, null, null, null, $current_session_id);
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $doc_id,
+                                        'DocumentMoved',
+                                        api_get_user_id(),
+                                        $to_group_id,
+                                        null,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    );
                                 }
                             } else {
                                 $current_session_id = api_get_session_id();
                                 if ($tem['type'] == "folder") {
                                     //add to database the first folder to target
-                                    $doc_id = add_document($_course, $chamiloFolder, 'folder', $chamiloFileSize, $chamiloFile); //get Chamilo
-                                    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
+                                    $doc_id = FileManager::add_document(
+                                        $_course,
+                                        $chamiloFolder,
+                                        'folder',
+                                        $chamiloFileSize,
+                                        $chamiloFile
+                                    ); //get Chamilo
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $doc_id,
+                                        'FolderCreated',
+                                        api_get_user_id(),
+                                        $to_group_id,
+                                        null,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    ); //get Chamilo
                                     // add to database inside subdirectories and files
 
                                     $course_dir = $_course['path']."/document"; //get Chamilo
@@ -229,24 +315,78 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                                         //Sample $item is C:/xampp/htdocs/chamilo/courses/TEST/document/books/book_highlight.jpg
                                         $file_orig = basename($item);
                                         if ($file_orig[0] != '.' && !in_array($invisibleFileNames)) {
-                                            $source_item = substr($item, (strlen($base_work_dir) - strlen($item))); // sample /books/book_highlight.jpg or /books
+                                            $source_item = substr(
+                                                $item,
+                                                (strlen($base_work_dir) - strlen($item))
+                                            ); // sample /books/book_highlight.jpg or /books
                                             $target_item = $source_item;
                                             $chamiloFolder = $target_item;
                                             $chamiloFile = basename($target_item);
                                             //
                                             if (is_dir($item)) {
-                                                $doc_id = add_document($_course, $chamiloFolder, 'folder', $chamiloFileSize, $chamiloFile); //get Chamilo
-                                                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
+                                                $doc_id = FileManager::add_document(
+                                                    $_course,
+                                                    $chamiloFolder,
+                                                    'folder',
+                                                    $chamiloFileSize,
+                                                    $chamiloFile
+                                                ); //get Chamilo
+                                                api_item_property_update(
+                                                    $_course,
+                                                    TOOL_DOCUMENT,
+                                                    $doc_id,
+                                                    'FolderCreated',
+                                                    api_get_user_id(),
+                                                    $to_group_id,
+                                                    null,
+                                                    null,
+                                                    null,
+                                                    $current_session_id
+                                                ); //get Chamilo
                                             } elseif (is_file($item)) {
                                                 $chamiloFileSize = filesize($item);
-                                                $doc_id = add_document($_course, $chamiloFolder, 'file', $chamiloFileSize, $chamiloFile); //get Chamilo
-                                                api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
+                                                $doc_id = FileManager::add_document(
+                                                    $_course,
+                                                    $chamiloFolder,
+                                                    'file',
+                                                    $chamiloFileSize,
+                                                    $chamiloFile
+                                                ); //get Chamilo
+                                                api_item_property_update(
+                                                    $_course,
+                                                    TOOL_DOCUMENT,
+                                                    $doc_id,
+                                                    'DocumentAdded',
+                                                    api_get_user_id(),
+                                                    $to_group_id,
+                                                    null,
+                                                    null,
+                                                    null,
+                                                    $current_session_id
+                                                ); //get Chamilo
                                             }
                                         }
                                     }
                                 } elseif ($tem['type'] == "file") {
-                                    $doc_id = add_document($_course, $chamiloFolder, 'file', $chamiloFileSize, $chamiloFile); //get Chamilo
-                                    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo
+                                    $doc_id = FileManager::add_document(
+                                        $_course,
+                                        $chamiloFolder,
+                                        'file',
+                                        $chamiloFileSize,
+                                        $chamiloFile
+                                    ); //get Chamilo
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $doc_id,
+                                        'DocumentAdded',
+                                        api_get_user_id(),
+                                        $to_group_id,
+                                        null,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    ); //get Chamilo
                                 }
                             }
                         }
@@ -258,7 +398,6 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                         }
 
 
-
                         $fileMoved[sizeof($fileMoved)] = $tem;
                         $tem = null;
                     }

+ 100 - 72
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_upload.php

@@ -7,95 +7,123 @@
  *
  */
 sleep(3);
-require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php";
+require_once dirname(__FILE__).DIRECTORY_SEPARATOR."inc".DIRECTORY_SEPARATOR."config.php";
 echo "{";
 $error = "";
 $info = "";
 
-include_once CLASS_UPLOAD ;
+include_once CLASS_UPLOAD;
 $upload = new Upload();
 
 $folder = base64_decode($_GET['folder']);
 //$folder = ($_GET['folder']);
 $upload->setInvalidFileExt(explode(",", CONFIG_UPLOAD_INVALID_EXTS));
-if(CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_UPLOAD) {
-	$error = SYS_DISABLED;
-} elseif(empty($folder) || !isUnderRoot($folder)) {
-	$error = ERR_FOLDER_PATH_NOT_ALLOWED;
-} else	if(!$upload->isFileUploaded('file')) {
-	$error = ERR_FILE_NOT_UPLOADED;
-}else if(!$upload->moveUploadedFile($folder)) {
-	$error = ERR_FILE_MOVE_FAILED;
-} elseif(!$upload->isPermittedFileExt(explode(",", CONFIG_UPLOAD_VALID_EXTS))) {
-	$error = ERR_FILE_TYPE_NOT_ALLOWED;
-} elseif(defined('CONFIG_UPLOAD_MAXSIZE') && CONFIG_UPLOAD_MAXSIZE && $upload->isSizeTooBig(CONFIG_UPLOAD_MAXSIZE)) {
-	 $error = sprintf(ERROR_FILE_TOO_BID, transformFileSize(CONFIG_UPLOAD_MAXSIZE));
+if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_UPLOAD) {
+    $error = SYS_DISABLED;
+} elseif (empty($folder) || !isUnderRoot($folder)) {
+    $error = ERR_FOLDER_PATH_NOT_ALLOWED;
 } else {
-	include_once(CLASS_FILE);
-	$path = $upload->getFilePath();
-	$obj = new file($path);
-	$tem = $obj->getFileInfo();
+    if (!$upload->isFileUploaded('file')) {
+        $error = ERR_FILE_NOT_UPLOADED;
+    } else {
+        if (!$upload->moveUploadedFile($folder)) {
+            $error = ERR_FILE_MOVE_FAILED;
+        } elseif (!$upload->isPermittedFileExt(explode(",", CONFIG_UPLOAD_VALID_EXTS))) {
+            $error = ERR_FILE_TYPE_NOT_ALLOWED;
+        } elseif (defined('CONFIG_UPLOAD_MAXSIZE') && CONFIG_UPLOAD_MAXSIZE && $upload->isSizeTooBig(
+            CONFIG_UPLOAD_MAXSIZE
+        )
+        ) {
+            $error = sprintf(ERROR_FILE_TOO_BID, transformFileSize(CONFIG_UPLOAD_MAXSIZE));
+        } else {
+            include_once(CLASS_FILE);
+            $path = $upload->getFilePath();
+            $obj = new file($path);
+            $tem = $obj->getFileInfo();
 
-	if (sizeof($tem)) {
-		include_once(CLASS_MANAGER);
-		$manager = new manager($upload->getFilePath(), false);
-		$fileType = $manager->getFileType($upload->getFileName());
-		foreach($fileType as $k=>$v) {
-			$tem[$k] = $v;
-		}
+            if (sizeof($tem)) {
+                include_once(CLASS_MANAGER);
+                $manager = new manager($upload->getFilePath(), false);
+                $fileType = $manager->getFileType($upload->getFileName());
+                foreach ($fileType as $k => $v) {
+                    $tem[$k] = $v;
+                }
 
-		$tem['path'] = backslashToSlash($path);
-		$tem['type'] = "file";
-		$tem['size'] = transformFileSize($tem['size']);
-		$tem['ctime'] = date(DATE_TIME_FORMAT, $tem['ctime']);
-		$tem['mtime'] = date(DATE_TIME_FORMAT, $tem['mtime']);
-		$tem['short_name'] = shortenFileName($tem['name']);
-		$tem['flag'] = 'noFlag';
+                $tem['path'] = backslashToSlash($path);
+                $tem['type'] = "file";
+                $tem['size'] = transformFileSize($tem['size']);
+                $tem['ctime'] = date(DATE_TIME_FORMAT, $tem['ctime']);
+                $tem['mtime'] = date(DATE_TIME_FORMAT, $tem['mtime']);
+                $tem['short_name'] = shortenFileName($tem['name']);
+                $tem['flag'] = 'noFlag';
 
-		/**
-		* Bridge to Chamilo documents tool
-		* @author Juan Carlos Raña Trabado
-		*/
+                /**
+                 * Bridge to Chamilo documents tool
+                 * @author Juan Carlos Raña Trabado
+                 */
 
-		if(!empty($_course['path'])) {
-			//only inside courses
-			$fullPath= $upload->getFilePath();		//get	ajaxmanager. Sample ../../../../../../../courses/TEST/document/Grupo_1_groupdocs/image.jpg
-			$folderInfo = $manager->getFolderInfo(); //get	ajaxmanager
-			$mainPath= getParentFolderPath($folderInfo['path']);//get	ajaxmanager. Sample ../../../../../../../courses/TEST/document/Grupo_1_groupdocs/
-			$chamiloFolder = substr($fullPath, strlen($mainPath)-strlen($fullPath)-1);
-			$chamiloFile = $tem['name'];	//get	ajaxmanager
-			$chamiloFileSize = filesize($fullPath); //get ajaxmanager
-			//get Chamilo
-			if(!empty($group_properties['directory'])) {
-				$chamiloFolder=$group_properties['directory'].$chamiloFolder;//get Chamilo
-			} else {
-				if(!api_is_allowed_to_edit()) {
-					$current_session_id = api_get_session_id();
-					if($current_session_id==0) {
-						$chamiloFolder='/shared_folder/sf_user_'.api_get_user_id().$chamiloFolder;
-					} else {
-						$chamiloFolder='/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id().$chamiloFolder;
-					}
-				}
-			}
+                if (!empty($_course['path'])) {
+                    //only inside courses
+                    $fullPath = $upload->getFilePath(
+                    ); //get	ajaxmanager. Sample ../../../../../../../courses/TEST/document/Grupo_1_groupdocs/image.jpg
+                    $folderInfo = $manager->getFolderInfo(); //get	ajaxmanager
+                    $mainPath = getParentFolderPath(
+                        $folderInfo['path']
+                    ); //get	ajaxmanager. Sample ../../../../../../../courses/TEST/document/Grupo_1_groupdocs/
+                    $chamiloFolder = substr($fullPath, strlen($mainPath) - strlen($fullPath) - 1);
+                    $chamiloFile = $tem['name']; //get	ajaxmanager
+                    $chamiloFileSize = filesize($fullPath); //get ajaxmanager
+                    //get Chamilo
+                    if (!empty($group_properties['directory'])) {
+                        $chamiloFolder = $group_properties['directory'].$chamiloFolder; //get Chamilo
+                    } else {
+                        if (!api_is_allowed_to_edit()) {
+                            $current_session_id = api_get_session_id();
+                            if ($current_session_id == 0) {
+                                $chamiloFolder = '/shared_folder/sf_user_'.api_get_user_id().$chamiloFolder;
+                            } else {
+                                $chamiloFolder = '/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id(
+                                ).$chamiloFolder;
+                            }
+                        }
+                    }
 
-			$doc_id = add_document($_course, $chamiloFolder,'file', $chamiloFileSize , $chamiloFile); //get Chamilo
-			$current_session_id = api_get_session_id();
-			api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(),$to_group_id,null,null,null,$current_session_id);//get Chamilo
+                    $doc_id = FileManager::add_document(
+                        $_course,
+                        $chamiloFolder,
+                        'file',
+                        $chamiloFileSize,
+                        $chamiloFile
+                    ); //get Chamilo
+                    $current_session_id = api_get_session_id();
+                    api_item_property_update(
+                        $_course,
+                        TOOL_DOCUMENT,
+                        $doc_id,
+                        'DocumentAdded',
+                        api_get_user_id(),
+                        $to_group_id,
+                        null,
+                        null,
+                        null,
+                        $current_session_id
+                    ); //get Chamilo
 
-		}
-		// end bridge
-		$obj->close();
-		foreach($tem as $k=>$v) {
-			$info .= sprintf(", %s:'%s'", $k, $v);
-		}
-		$info .= sprintf(", url:'%s'",  getFileUrl($path));
-		$info .= sprintf(", tipedit:'%s'",  TIP_DOC_RENAME);
-	} else {
-		$error = ERR_FILE_NOT_AVAILABLE;
-	}
+                }
+                // end bridge
+                $obj->close();
+                foreach ($tem as $k => $v) {
+                    $info .= sprintf(", %s:'%s'", $k, $v);
+                }
+                $info .= sprintf(", url:'%s'", getFileUrl($path));
+                $info .= sprintf(", tipedit:'%s'", TIP_DOC_RENAME);
+            } else {
+                $error = ERR_FILE_NOT_AVAILABLE;
+            }
+        }
+    }
 }
 
-echo "error:'" . $error . "'";
+echo "error:'".$error."'";
 echo $info;
 echo "}";

+ 558 - 559
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/class.upload.php

@@ -6,585 +6,584 @@
  * @since 22/April/2007
  *
  */
- require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';//from Dokeos
- class Upload {
-	var $fileType = ""; //the file type
-	var $originalFileName = "";
-	var $fileName = ""; //the file final name
-	var $fileExtension = "";
-	var $img_x = 0;
-	var $img_y = 0;
-	var $img_new_x = 0;
-	var $img_new_y = 0;
-	var $imgHandler = null;
-	var $fileBaseName = ""; //file name without the file extension and .
-	var $filePath = ""; //the file path which the file uploaded to
-	var $fileSize = 0;
-	var $validImageExts = array("gif", "jpg", "png");
-	var $errors = array();
-	var $_value  = null;  //an array holding the uploaded file details
-	var $dirPath = "";
-	var $invalidFileExt = array(); //var $invalidFileExt = array('php,inc,asp,aspx');
-	var $errCode = "";
-	var $safeMode;
-	var $uploadFileMode = 0755;
-	var $errorCodes = array(
-		0=>'the file uploaded with success',
-		1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini',
-		2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
-		3=>'The uploaded file was only partially uploaded',
-		4=>'No file was uploaded.',
-		6=>'Missing a temporary folder',
-		7=>'Failed to write file to disk',
-		8=>'File upload stopped by extension',
-		999=>'No error code avaiable',
-	);
-	
-
-	function Upload()
-	{
-		//doing nothing
-	}
-	
-	function isFileUploaded($indexInPost="file")
-	{
-		
-		$this->errCode = isset($_FILES[$indexInPost]['error'])?$_FILES[$indexInPost]['error']:999;
-		if((isset($_FILES[$indexInPost]['error']) && $_FILES[$indexInPost] == 0) ||
-		(!empty($_FILES[$indexInPost]['tmp_name']) && $_FILES[$indexInPost]['tmp_name'] != 'none')
-		)
-		{
-			$this->_value = $_FILES[$indexInPost];
-			$this->fileSize = @filesize($this->_value['tmp_name']);
-			$this->originalFileName = $this->_value['name'];
-			$this->fileType = $this->_value['type'];
-			
-			return true;
-		}else 
-		{
-			
-			array_push($this->errors, 'Unable to upload file');
-			return false;
-		}		
-	}
-	
-	function getErrorCodeMsg()
-	{
-		return (isset($this->errorCodes[$this->errCode])?$this->errorCodes[$this->errCode]:"");
-	}
-	/**
-	 * check if the uploaded file extension is allowed against the validFile Extension
-	 * or against the invalid extension list when the list of valid file extension is not set
-	 *
-	 * @param array $validFileExt
-	 * @return boolean
-	 */
-	function isPermittedFileExt($validFileExt = array())
-	{
-		$tem = array();
-
-		if(sizeof($validFileExt))
-		{
-			foreach($validFileExt as $k=>$v)
-			{
-				$tem[$k] = strtolower(trim($v));
-			}
-		}
-		$validFileExt = $tem;
-
-		if(sizeof($validFileExt) && sizeof($this->invalidFileExt))
-		{
-			foreach($validFileExt as  $k=>$ext)
-			{
-				if(array_search(strtolower($ext), $this->invalidFileExt) !== false)
-				{
-					unset($validFileExt[$k]);
-				}
-			}
-		}
-		
-	
-
-		
-		if(sizeof($validFileExt))
-		{
-			if(array_search(strtolower($this->getFileExt()), $validFileExt) !== false)
-			{
-				return true;
-			}
-		}elseif(array_search(strtolower($this->getFileExt()), $this->invalidFileExt) === false)
-		{
-			return true;
-		}
-
-		
-		$this->deleteUploadedFile();
-		return false;
-		
-	}
-	/**
-	 * check if the uploaded file size is too big
-	 *
-	 * @param integer $maxSize
-	 */
-	function isSizeTooBig($maxSize="")
-	{
-		if($this->fileSize > $maxSize)
-		{
-			$this->deleteUploadedFile();
-			return true;
-		}else 
-		{
-			return false;
-		}
-	}
-	/**
-	 * set the invali file extensions
-	 *
-	 * @param array $invalidFileExt
-	 */
-	function setInvalidFileExt($invalidFileExt=array())
-	{
-		$tem = array();
-		if(sizeof($invalidFileExt))
-		{
-			foreach($invalidFileExt as $k=>$v)
-			{
-				$tem[$k]= strtolower(trim($v));
-			}
-		}
-		
-		$this->invalidFileExt = $tem;
-	}
-	/**
-	 * get file type
-	 *
-	 * @return string
-	 */
-	function getFileType()
-	{
-		return $this->fileType;
-	}
-	/**
-	 * get a file extension
-	 *
-	 * @param string $fileName the path to a file or just the file name
-	 */	
-	function getFileExt()
-	{
-		//return strtolower(substr(strrchr($this->fileName, "."), 1));
-		return substr(strrchr($this->originalFileName, "."), 1);
-	}
-	/**
-		 * move the uploaded file to a specific location
-		 *
-		 * @param string $dest  the path to the directory which the uploaded file will be moved to
-		 * @param string $fileBaseName the base name which the uploaded file will be renamed to
-		 * @param unknown_type $overwrite
-		 * @return unknown
-		 */
-	function moveUploadedFile($dest, $fileBaseName = '', $overwrite=false)
-	{
-		//ensure the directory path ending with /
-		if ($dest != ''  && substr($dest, -1) != '/') {
-			$dest .= '/';
-		}
-		$this->dirPath = $dest;
-		$fileName =  basename($this->_value['name']);
-
-		$dotIndex = strrpos($fileName, '.');
-		$this->fileExtension = '';
-		if(is_int($dotIndex))
-		{
-			$this->fileExtension = substr($fileName, $dotIndex);
-			$this->fileBaseName = substr($fileName, 0, $dotIndex);
-		}
-		if(!empty($fileBaseName))
-		{
-			$this->fileBaseName = $fileBaseName;
-		}
-		$this->fileBaseName=disable_dangerous_file(replace_dangerous_char(str_replace(' ','_',$this->fileBaseName),'strict'));// Juan Carlos Raña replace space by _ because fix long names. See: ajaxfilemanager/inc/class.manager.php. And add cleaning from Chamilo replace_dangerous_char() and disable_dangerous_file()
-		$fileName = $this->fileBaseName . $this->fileExtension;
-		$filePath = $dest . $fileName;
-
-		if(!$overwrite && file_exists($filePath) && is_file($filePath))
-		{//rename
-
-			$counter = 0;
-			while(file_exists($dest.$fileName) && is_file($dest .$fileName))
-			{
-				$counter++;
-				$fileName = $this->fileBaseName.'_'.$counter.$this->fileExtension;
-			}
-			$this->fileBaseName .= "_" . $counter;
-
-		}
-
-		if (@move_uploaded_file($this->_value['tmp_name'], $dest . $fileName)) {
-			@chmod($dest . $fileName, $this->uploadFileMode);
-			$this->fileName = $fileName;
-			$this->filePath = $dest . $fileName;
-			return true;
-		} else {
-			return false;
-		}
-	}
-
-
-	/**
-		 * check if the uploaded is permitted to upload
-		 *
-		 * @param mixed $invalidImageExts invalid image extension
-		 * @param bool $delete force to delete the uploaded file
-		 */	
-	function isImage($invalidImageExts = array(), $delete = true)
-	{
-		if(!is_array($invalidImageExts) && !empty($invalidImageExts))
-		{
-			$invalidImageExts = explode(",", $invalidImageExts);
-		}
-		foreach ($invalidImageExts as $k=>$v)
-		{
-			$invalidImageExts[$k] = strtolower(trim($v));
-		}
-		foreach ($this->validImageExts as $k=>$v)
-		{
-			$ValidImageExts[$k] = strtolower(trim($v));
-		}
-		if(sizeof($invalidImageExts))
-		{
-			foreach ($ValidImageExts as $k=>$v)
-			{
-				if(array_search(strtolower($v), $invalidImageExts) !== false)
-				{
-					unset($ValidImageExts[$k]);
-				}
-			}
-		}
-		if(array_search(strtolower($this->getFileExt()), $ValidImageExts)!==false)
-		{
-			$this->_get_image_details($this->filePath);
-			if(!empty($this->fileType))
-			{
-				return true;
-			}
-		}else
-		{
-			if($delete)
-			{
-				$this->deleteUploadedFile();
-			}
-		}
-
-		array($this->errors, "This file is not a image type file.");
-		return false;
-	}
-
-	/**
+class Upload
+{
+    var $fileType = ""; //the file type
+    var $originalFileName = "";
+    var $fileName = ""; //the file final name
+    var $fileExtension = "";
+    var $img_x = 0;
+    var $img_y = 0;
+    var $img_new_x = 0;
+    var $img_new_y = 0;
+    var $imgHandler = null;
+    var $fileBaseName = ""; //file name without the file extension and .
+    var $filePath = ""; //the file path which the file uploaded to
+    var $fileSize = 0;
+    var $validImageExts = array("gif", "jpg", "png");
+    var $errors = array();
+    var $_value = null; //an array holding the uploaded file details
+    var $dirPath = "";
+    var $invalidFileExt = array(); //var $invalidFileExt = array('php,inc,asp,aspx');
+    var $errCode = "";
+    var $safeMode;
+    var $uploadFileMode = 0755;
+    var $errorCodes = array(
+        0 => 'the file uploaded with success',
+        1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
+        2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
+        3 => 'The uploaded file was only partially uploaded',
+        4 => 'No file was uploaded.',
+        6 => 'Missing a temporary folder',
+        7 => 'Failed to write file to disk',
+        8 => 'File upload stopped by extension',
+        999 => 'No error code avaiable',
+    );
+
+
+    function Upload()
+    {
+        //doing nothing
+    }
+
+    function isFileUploaded($indexInPost = "file")
+    {
+
+        $this->errCode = isset($_FILES[$indexInPost]['error']) ? $_FILES[$indexInPost]['error'] : 999;
+        if ((isset($_FILES[$indexInPost]['error']) && $_FILES[$indexInPost] == 0) ||
+            (!empty($_FILES[$indexInPost]['tmp_name']) && $_FILES[$indexInPost]['tmp_name'] != 'none')
+        ) {
+            $this->_value = $_FILES[$indexInPost];
+            $this->fileSize = @filesize($this->_value['tmp_name']);
+            $this->originalFileName = $this->_value['name'];
+            $this->fileType = $this->_value['type'];
+
+            return true;
+        } else {
+
+            array_push($this->errors, 'Unable to upload file');
+
+            return false;
+        }
+    }
+
+    function getErrorCodeMsg()
+    {
+        return (isset($this->errorCodes[$this->errCode]) ? $this->errorCodes[$this->errCode] : "");
+    }
+
+    /**
+     * check if the uploaded file extension is allowed against the validFile Extension
+     * or against the invalid extension list when the list of valid file extension is not set
+     *
+     * @param array $validFileExt
+     * @return boolean
+     */
+    function isPermittedFileExt($validFileExt = array())
+    {
+        $tem = array();
+
+        if (sizeof($validFileExt)) {
+            foreach ($validFileExt as $k => $v) {
+                $tem[$k] = strtolower(trim($v));
+            }
+        }
+        $validFileExt = $tem;
+
+        if (sizeof($validFileExt) && sizeof($this->invalidFileExt)) {
+            foreach ($validFileExt as $k => $ext) {
+                if (array_search(strtolower($ext), $this->invalidFileExt) !== false) {
+                    unset($validFileExt[$k]);
+                }
+            }
+        }
+
+
+        if (sizeof($validFileExt)) {
+            if (array_search(strtolower($this->getFileExt()), $validFileExt) !== false) {
+                return true;
+            }
+        } elseif (array_search(strtolower($this->getFileExt()), $this->invalidFileExt) === false) {
+            return true;
+        }
+
+
+        $this->deleteUploadedFile();
+
+        return false;
+
+    }
+
+    /**
+     * check if the uploaded file size is too big
+     *
+     * @param integer $maxSize
+     */
+    function isSizeTooBig($maxSize = "")
+    {
+        if ($this->fileSize > $maxSize) {
+            $this->deleteUploadedFile();
+
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * set the invali file extensions
+     *
+     * @param array $invalidFileExt
+     */
+    function setInvalidFileExt($invalidFileExt = array())
+    {
+        $tem = array();
+        if (sizeof($invalidFileExt)) {
+            foreach ($invalidFileExt as $k => $v) {
+                $tem[$k] = strtolower(trim($v));
+            }
+        }
+
+        $this->invalidFileExt = $tem;
+    }
+
+    /**
+     * get file type
+     *
+     * @return string
+     */
+    function getFileType()
+    {
+        return $this->fileType;
+    }
+
+    /**
+     * get a file extension
+     *
+     * @param string $fileName the path to a file or just the file name
+     */
+    function getFileExt()
+    {
+        //return strtolower(substr(strrchr($this->fileName, "."), 1));
+        return substr(strrchr($this->originalFileName, "."), 1);
+    }
+
+    /**
+     * move the uploaded file to a specific location
+     *
+     * @param string $dest  the path to the directory which the uploaded file will be moved to
+     * @param string $fileBaseName the base name which the uploaded file will be renamed to
+     * @param unknown_type $overwrite
+     * @return unknown
+     */
+    function moveUploadedFile($dest, $fileBaseName = '', $overwrite = false)
+    {
+        //ensure the directory path ending with /
+        if ($dest != '' && substr($dest, -1) != '/') {
+            $dest .= '/';
+        }
+        $this->dirPath = $dest;
+        $fileName = basename($this->_value['name']);
+
+        $dotIndex = strrpos($fileName, '.');
+        $this->fileExtension = '';
+        if (is_int($dotIndex)) {
+            $this->fileExtension = substr($fileName, $dotIndex);
+            $this->fileBaseName = substr($fileName, 0, $dotIndex);
+        }
+        if (!empty($fileBaseName)) {
+            $this->fileBaseName = $fileBaseName;
+        }
+        // Juan Carlos Raña replace space by _ because fix long names. See: ajaxfilemanager/inc/class.manager.php.
+        //And add cleaning from Chamilo replace_dangerous_char() and FileManage::disable_dangerous_file()
+        $this->fileBaseName = FileManager::disable_dangerous_file(
+            replace_dangerous_char(str_replace(' ', '_', $this->fileBaseName), 'strict')
+        );
+        $fileName = $this->fileBaseName.$this->fileExtension;
+        $filePath = $dest.$fileName;
+
+        if (!$overwrite && file_exists($filePath) && is_file($filePath)) { //rename
+
+            $counter = 0;
+            while (file_exists($dest.$fileName) && is_file($dest.$fileName)) {
+                $counter++;
+                $fileName = $this->fileBaseName.'_'.$counter.$this->fileExtension;
+            }
+            $this->fileBaseName .= "_".$counter;
+
+        }
+
+        if (@move_uploaded_file($this->_value['tmp_name'], $dest.$fileName)) {
+            @chmod($dest.$fileName, $this->uploadFileMode);
+            $this->fileName = $fileName;
+            $this->filePath = $dest.$fileName;
+
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+
+    /**
+     * check if the uploaded is permitted to upload
+     *
+     * @param mixed $invalidImageExts invalid image extension
+     * @param bool $delete force to delete the uploaded file
+     */
+    function isImage($invalidImageExts = array(), $delete = true)
+    {
+        if (!is_array($invalidImageExts) && !empty($invalidImageExts)) {
+            $invalidImageExts = explode(",", $invalidImageExts);
+        }
+        foreach ($invalidImageExts as $k => $v) {
+            $invalidImageExts[$k] = strtolower(trim($v));
+        }
+        foreach ($this->validImageExts as $k => $v) {
+            $ValidImageExts[$k] = strtolower(trim($v));
+        }
+        if (sizeof($invalidImageExts)) {
+            foreach ($ValidImageExts as $k => $v) {
+                if (array_search(strtolower($v), $invalidImageExts) !== false) {
+                    unset($ValidImageExts[$k]);
+                }
+            }
+        }
+        if (array_search(strtolower($this->getFileExt()), $ValidImageExts) !== false) {
+            $this->_get_image_details($this->filePath);
+            if (!empty($this->fileType)) {
+                return true;
+            }
+        } else {
+            if ($delete) {
+                $this->deleteUploadedFile();
+            }
+        }
+
+        array($this->errors, "This file is not a image type file.");
+
+        return false;
+    }
+
+    /**
      * Resize the Image in the X and/or Y direction
      * If either is 0 it will be scaled proportionally
      *
      * @access public
      *
-     * @param mixed $new_x 
-     * @param mixed $new_y 
+     * @param mixed $new_x
+     * @param mixed $new_y
      * @param string $thumb_suffix
      *
      * @return mixed none or PEAR_error
      */
-	function resize($filePath, $thumb_suffix="", $new_x = 0, $new_y = 0)
-	{
-		
-		if(empty($filePath))
-		{
-			$filePath = $this->dirPath . $this->fileBaseName . $thumb_suffix  . $this->fileExtension;
-		}
-		// 0 means keep original size
-		if ($this->img_x > $this->img_y)
-		$new_y = intval($new_y/$this->img_x*$this->img_y);
-		else if ($this->img_y > $this->img_x)
-		$new_x = intval($new_x/$this->img_y*$this->img_x);
-		// Now do the library specific resizing.
-		return $this->_resize($filePath,$new_x, $new_y);
-	} // End resize
-
-	/**
+    function resize($filePath, $thumb_suffix = "", $new_x = 0, $new_y = 0)
+    {
+
+        if (empty($filePath)) {
+            $filePath = $this->dirPath.$this->fileBaseName.$thumb_suffix.$this->fileExtension;
+        }
+        // 0 means keep original size
+        if ($this->img_x > $this->img_y) {
+            $new_y = intval($new_y / $this->img_x * $this->img_y);
+        } else {
+            if ($this->img_y > $this->img_x) {
+                $new_x = intval($new_x / $this->img_y * $this->img_x);
+            }
+        }
+
+        // Now do the library specific resizing.
+        return $this->_resize($filePath, $new_x, $new_y);
+    } // End resize
+
+    /**
      * resize the image and return the thumbnail image  details array("width"=>, "height"=>, "name")
      *
-     * @param string $fileName 
+     * @param string $fileName
      * @param int $new_x the thumbnail width
      * @param int $new_y the thumbnail height
      * @return unknown
      */
-	function _resize($fileName, $new_x, $new_y) {
-		$functionName = 'ImageCreateFrom' . $this->fileType;
-
-
-		if(function_exists($functionName))
-		{
-			$this->imgHandler = $functionName($this->filePath);
-		}else
-		{
-			array_push($this->errors, $functionName . " function is unavailable");
-			return false;
-		}
-
-		if(function_exists('ImageCreateTrueColor')){
-			$new_img =ImageCreateTrueColor($new_x,$new_y);
-		} else {
-			$new_img =ImageCreate($new_x,$new_y);
-		}
-		if(function_exists('ImageCopyResampled')){
-			ImageCopyResampled($new_img, $this->imgHandler, 0, 0, 0, 0, $new_x, $new_y, $this->img_x, $this->img_y);
-		} else {
-			ImageCopyResized($new_img, $this->imgHandler, 0, 0, 0, 0, $new_x, $new_y, $this->img_x, $this->img_y);
-		}
-		if($this->_imageSave($new_img, $fileName, 80))
-		{
-			return array("width"=>$new_x, "height"=>$new_y, "name"=>basename($fileName));
-		}else
-		{
-
-			array_push($this->errors, "Unable to resize the image");
-			return false;
-		}
-
-	}
-	/**
-		 * save the thumbnail file and destroy the opened image
-		 *
-		 * @param resource $newImageHandler
-		 * @param string $fileName
-		 * @param int $quality
-		 * @return boolean
-		 */
-	function _imageSave($newImageHandler, $fileName, $quality = 90)
-	{
-		$functionName = 'image' . $this->fileType;
-		if($functionName($newImageHandler, $fileName, $quality))
-		{
-			imagedestroy($newImageHandler);
-			return true;
-		}else
-		{
-			imagedestroy($newImageHandler);
-			array_push($this->errors, "Unable to save the thumbnail file.");
-			return false;
-		}
-
-	}
-	/**
+    function _resize($fileName, $new_x, $new_y)
+    {
+        $functionName = 'ImageCreateFrom'.$this->fileType;
+
+
+        if (function_exists($functionName)) {
+            $this->imgHandler = $functionName($this->filePath);
+        } else {
+            array_push($this->errors, $functionName." function is unavailable");
+
+            return false;
+        }
+
+        if (function_exists('ImageCreateTrueColor')) {
+            $new_img = ImageCreateTrueColor($new_x, $new_y);
+        } else {
+            $new_img = ImageCreate($new_x, $new_y);
+        }
+        if (function_exists('ImageCopyResampled')) {
+            ImageCopyResampled($new_img, $this->imgHandler, 0, 0, 0, 0, $new_x, $new_y, $this->img_x, $this->img_y);
+        } else {
+            ImageCopyResized($new_img, $this->imgHandler, 0, 0, 0, 0, $new_x, $new_y, $this->img_x, $this->img_y);
+        }
+        if ($this->_imageSave($new_img, $fileName, 80)) {
+            return array("width" => $new_x, "height" => $new_y, "name" => basename($fileName));
+        } else {
+
+            array_push($this->errors, "Unable to resize the image");
+
+            return false;
+        }
+
+    }
+
+    /**
+     * save the thumbnail file and destroy the opened image
+     *
+     * @param resource $newImageHandler
+     * @param string $fileName
+     * @param int $quality
+     * @return boolean
+     */
+    function _imageSave($newImageHandler, $fileName, $quality = 90)
+    {
+        $functionName = 'image'.$this->fileType;
+        if ($functionName($newImageHandler, $fileName, $quality)) {
+            imagedestroy($newImageHandler);
+
+            return true;
+        } else {
+            imagedestroy($newImageHandler);
+            array_push($this->errors, "Unable to save the thumbnail file.");
+
+            return false;
+        }
+
+    }
+
+    /**
      *
      * @access public
      * @return void
      */
-	function _get_image_details($image)
-	{
-
-		//echo $image;
-		$data = @GetImageSize($image);
-		#1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order,
-		# 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC
-		if (is_array($data)){
-			switch($data[2]){
-				case 1:
-					$type = 'gif';
-					break;
-				case 2:
-					$type = 'jpeg';
-					break;
-				case 3:
-					$type = 'png';
-					break;
-				case 4:
-					$type = 'swf';
-					break;
-				case 5:
-					$type = 'psd';
-				case 6:
-					$type = 'bmp';
-				case 7:
-				case 8:
-					$type = 'tiff';
-				default:
-					array_push($this->errors, "We do not recognize this image format");
-
-			}
-			$this->img_x = $data[0];
-			$this->img_y = $data[1];
-			$this->fileType = $type;
-
-			return true;
-		} else {
-			array_push($this->errors, "Cannot fetch image or images details.");
-			return null;
-		}
-	}
-	/**
-	 * caculate the thumbnail details from the original image file 
-	 *
-	 * @param string $originalImageName  
-	 * @param int $originaleImageWidth
-	 * @param int $originalImageHeight
-	 * @param string $thumbnailSuffix
-	 * @param int $thumbnailWidth
-	 * @param int $thumbnailHeight
-	 * @return array array("name"=>"image name", "width"=>"image width", "height"=>"image height")
-	 */
-	function getThumbInfo($originalImageName, $originaleImageWidth, $originalImageHeight, $thumbnailSuffix, $thumbnailWidth, $thumbnailHeight)
-	{
-		$outputs = array("name"=>"", "width"=>0, "height"=>0);
-		$thumbnailWidth	= intval($thumbnailWidth);
-		$thumbnailHeight = intval($thumbnailHeight);
-		if(!empty($originalImageName) && !empty($originaleImageWidth) && !empty($originalImageHeight))
-		{
-			$dotIndex = strrpos($originalImageName, '.');
-			//begin to get the thumbnail image name
-			$fileExtension = '';
-			$fileBaseName = '';
-			if(is_int($dotIndex))
-			{
-				$fileExtension = substr($originalImageName, $dotIndex);
-				$fileBaseName = substr($originalImageName, 0, $dotIndex);
-			}
-			$outputs['name'] = $fileBaseName . $thumbnailSuffix . $fileExtension;
-			//start to get the thumbnail width & height
-			if($thumbnailWidth < 1 && $thumbnailHeight < 1)
-			{
-				$thumbnailWidth =$originaleImageWidth;
-				$thumbnailHeight = $originalImageHeight;
-			}elseif($thumbnailWidth < 1)
-			{
-				$thumbnailWidth = floor($thumbnailHeight / $originalImageHeight * $originaleImageWidth);
-
-			}elseif($thumbnailHeight < 1)
-			{
-				$thumbnailHeight = floor($thumbnailWidth / $originaleImageWidth * $originalImageHeight);
-			}else
-			{
-				$scale = min($thumbnailWidth/$originaleImageWidth, $thumbnailHeight/$originalImageHeight);
-				$thumbnailWidth = floor($scale*$originaleImageWidth);
-				$thumbnailHeight = floor($scale*$originalImageHeight);
-			}
-			$outputs['width'] = $thumbnailWidth;
-			$outputs['height'] = $thumbnailHeight;
-		}
-		return $outputs;
-
-	}
-	
-
-	/**
+    function _get_image_details($image)
+    {
+
+        //echo $image;
+        $data = @GetImageSize($image);
+        #1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order,
+        # 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC
+        if (is_array($data)) {
+            switch ($data[2]) {
+                case 1:
+                    $type = 'gif';
+                    break;
+                case 2:
+                    $type = 'jpeg';
+                    break;
+                case 3:
+                    $type = 'png';
+                    break;
+                case 4:
+                    $type = 'swf';
+                    break;
+                case 5:
+                    $type = 'psd';
+                case 6:
+                    $type = 'bmp';
+                case 7:
+                case 8:
+                    $type = 'tiff';
+                default:
+                    array_push($this->errors, "We do not recognize this image format");
+
+            }
+            $this->img_x = $data[0];
+            $this->img_y = $data[1];
+            $this->fileType = $type;
+
+            return true;
+        } else {
+            array_push($this->errors, "Cannot fetch image or images details.");
+
+            return null;
+        }
+    }
+
+    /**
+     * caculate the thumbnail details from the original image file
+     *
+     * @param string $originalImageName
+     * @param int $originaleImageWidth
+     * @param int $originalImageHeight
+     * @param string $thumbnailSuffix
+     * @param int $thumbnailWidth
+     * @param int $thumbnailHeight
+     * @return array array("name"=>"image name", "width"=>"image width", "height"=>"image height")
+     */
+    function getThumbInfo(
+        $originalImageName,
+        $originaleImageWidth,
+        $originalImageHeight,
+        $thumbnailSuffix,
+        $thumbnailWidth,
+        $thumbnailHeight
+    ) {
+        $outputs = array("name" => "", "width" => 0, "height" => 0);
+        $thumbnailWidth = intval($thumbnailWidth);
+        $thumbnailHeight = intval($thumbnailHeight);
+        if (!empty($originalImageName) && !empty($originaleImageWidth) && !empty($originalImageHeight)) {
+            $dotIndex = strrpos($originalImageName, '.');
+            //begin to get the thumbnail image name
+            $fileExtension = '';
+            $fileBaseName = '';
+            if (is_int($dotIndex)) {
+                $fileExtension = substr($originalImageName, $dotIndex);
+                $fileBaseName = substr($originalImageName, 0, $dotIndex);
+            }
+            $outputs['name'] = $fileBaseName.$thumbnailSuffix.$fileExtension;
+            //start to get the thumbnail width & height
+            if ($thumbnailWidth < 1 && $thumbnailHeight < 1) {
+                $thumbnailWidth = $originaleImageWidth;
+                $thumbnailHeight = $originalImageHeight;
+            } elseif ($thumbnailWidth < 1) {
+                $thumbnailWidth = floor($thumbnailHeight / $originalImageHeight * $originaleImageWidth);
+
+            } elseif ($thumbnailHeight < 1) {
+                $thumbnailHeight = floor($thumbnailWidth / $originaleImageWidth * $originalImageHeight);
+            } else {
+                $scale = min($thumbnailWidth / $originaleImageWidth, $thumbnailHeight / $originalImageHeight);
+                $thumbnailWidth = floor($scale * $originaleImageWidth);
+                $thumbnailHeight = floor($scale * $originalImageHeight);
+            }
+            $outputs['width'] = $thumbnailWidth;
+            $outputs['height'] = $thumbnailHeight;
+        }
+
+        return $outputs;
+
+    }
+
+
+    /**
      * get the uploaded file
      */
-	function deleteUploadedFile()
-	{
-		@unlink($this->filePath);
-	}
-	/**
-	 * destroy the tmp file
-	 *
-	 */
-	function finish()
-	{
-		@unlink($this->_value['tmp_name']);
-	}
-	
-	function displayError()
-	{
-		if(sizeof($this->errors))
-		{
-			echo "<pre>";
-			print_r($this->errors);
-			echo "</pre>";
-		}
-	}
-	/**
-	 * get the path which the file uploaded to
-	 *
-	 */
-	function getFilePath()
-	{
-		return $this->filePath;
-	}
-	/**
-	 * return the directory path witch the file uploaded to
-	 *
-	 * @return unknown
-	 */
-	function getDirPath()
-	{
-		return $this->dirPath;
-	}
-	
-	function getFileBaseName()
-	{
-		return $this->fileBaseName;
-	}
-	
-	function getFileName()
-	{
-		return $this->fileName;
-	}
-	/**
-	 * get image width
-	 *
-	 * @return integer
-	 */
-	function getImageWidth()
-	{
-		return $this->img_x;
-	}
-	/**
-	 * get image height
-	 *
-	 * @return integer
-	 */
-	function getImageHeight()
-	{
-		return $this->img_y;
-	}
-	/**
-	 * get uploaded file size
-	 *
-	 * @return string
-	 */
-	function getFileSize()
-	{
-		return $this->fileSize;
-	}
-	/**
-	 * delete the uploaded image file & associated thumnails
-	 *
-	 * @param string $dirPath
-	 * @param string $originalImageName
-	 * @param string $arrayThumbnailSuffix
-	 */
-	function deleteFileAndThumbs($dirPath, $originalImageName, $arrayThumbnailSuffix)
-	{
-		//ensure the directory path ending with /
-		if ($dirPath != ''  && substr($dirPath, -1) != '/') {
-			$dirPath .= '/';
-		}			
-		if(!empty($originalImageName) && file_exists($dirPath . $originalImageName) && is_file($dirPath . $originalImageName))
-		{
-			@unlink($dirPath . $originalImageName);
-			foreach($arrayThumbnailSuffix as $v)
-			{
-				$dotIndex = strrpos($originalImageName, '.');
-				//begin to get the thumbnail image name
-				$fileExtension = '';
-				$fileBaseName = '';
-				if(is_int($dotIndex))
-				{
-					$fileExtension = substr($originalImageName, $dotIndex);
-					$fileBaseName = substr($originalImageName, 0, $dotIndex);
-				}
-				@unlink($dirPath . $fileBaseName . $v . $fileExtension);			
-			}			
-		}
-	
-
-	}
+    function deleteUploadedFile()
+    {
+        @unlink($this->filePath);
+    }
+
+    /**
+     * destroy the tmp file
+     *
+     */
+    function finish()
+    {
+        @unlink($this->_value['tmp_name']);
+    }
+
+    function displayError()
+    {
+        if (sizeof($this->errors)) {
+            echo "<pre>";
+            print_r($this->errors);
+            echo "</pre>";
+        }
+    }
+
+    /**
+     * get the path which the file uploaded to
+     *
+     */
+    function getFilePath()
+    {
+        return $this->filePath;
+    }
+
+    /**
+     * return the directory path witch the file uploaded to
+     *
+     * @return unknown
+     */
+    function getDirPath()
+    {
+        return $this->dirPath;
+    }
+
+    function getFileBaseName()
+    {
+        return $this->fileBaseName;
+    }
+
+    function getFileName()
+    {
+        return $this->fileName;
+    }
+
+    /**
+     * get image width
+     *
+     * @return integer
+     */
+    function getImageWidth()
+    {
+        return $this->img_x;
+    }
+
+    /**
+     * get image height
+     *
+     * @return integer
+     */
+    function getImageHeight()
+    {
+        return $this->img_y;
+    }
+
+    /**
+     * get uploaded file size
+     *
+     * @return string
+     */
+    function getFileSize()
+    {
+        return $this->fileSize;
+    }
+
+    /**
+     * delete the uploaded image file & associated thumnails
+     *
+     * @param string $dirPath
+     * @param string $originalImageName
+     * @param string $arrayThumbnailSuffix
+     */
+    function deleteFileAndThumbs($dirPath, $originalImageName, $arrayThumbnailSuffix)
+    {
+        //ensure the directory path ending with /
+        if ($dirPath != '' && substr($dirPath, -1) != '/') {
+            $dirPath .= '/';
+        }
+        if (!empty($originalImageName) && file_exists($dirPath.$originalImageName) && is_file(
+            $dirPath.$originalImageName
+        )
+        ) {
+            @unlink($dirPath.$originalImageName);
+            foreach ($arrayThumbnailSuffix as $v) {
+                $dotIndex = strrpos($originalImageName, '.');
+                //begin to get the thumbnail image name
+                $fileExtension = '';
+                $fileBaseName = '';
+                if (is_int($dotIndex)) {
+                    $fileExtension = substr($originalImageName, $dotIndex);
+                    $fileBaseName = substr($originalImageName, 0, $dotIndex);
+                }
+                @unlink($dirPath.$fileBaseName.$v.$fileExtension);
+            }
+        }
+
+
+    }
 }
+
 ?>

+ 102 - 63
main/inc/lib/fckeditor/repository.php

@@ -1,16 +1,16 @@
 <?php
 /**
- *	Chamilo LMS
+ *    Chamilo LMS
  *
- *	For a full list of contributors, see "credits.txt".
- *	The full license can be read in "license.txt".
+ *    For a full list of contributors, see "credits.txt".
+ *    The full license can be read in "license.txt".
  *
- *	This program is free software; you can redistribute it and/or
- *	modify it under the terms of the GNU General Public License
- *	as published by the Free Software Foundation; either version 2
- *	of the License, or (at your option) any later version.
+ *    This program is free software; you can redistribute it and/or
+ *    modify it under the terms of the GNU General Public License
+ *    as published by the Free Software Foundation; either version 2
+ *    of the License, or (at your option) any later version.
  *
- *	See the GNU General Public License for more details.
+ *    See the GNU General Public License for more details.
  */
 
 /**
@@ -19,83 +19,122 @@
  * @since 31/December/2008
  */
 
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-
 $permissions_for_new_directories = api_get_permissions_for_new_directories();
 $permissions_for_new_files = api_get_permissions_for_new_files();
 
 if (!empty($_course['path'])) {
-	require_once api_get_path(LIBRARY_PATH).'document.lib.php';
-	require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
+    require_once api_get_path(LIBRARY_PATH).'document.lib.php';
+    require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
 
     // Get the Chamilo session properties. Before ajaximagemanager!!!
-    $to_group_id = !empty($_SESSION['_gid']) ? $_SESSION['_gid'] : 0 ;
-	$group_properties = GroupManager::get_group_properties($_SESSION['_gid']);
-	$is_user_in_group = GroupManager::is_user_in_group($_user['user_id'],$_SESSION['_gid']);
+    $to_group_id = !empty($_SESSION['_gid']) ? $_SESSION['_gid'] : 0;
+    $group_properties = GroupManager::get_group_properties($_SESSION['_gid']);
+    $is_user_in_group = GroupManager::is_user_in_group($_user['user_id'], $_SESSION['_gid']);
 }
 
-$my_path = UserManager::get_user_picture_path_by_id(api_get_user_id(),'system');
+$my_path = UserManager::get_user_picture_path_by_id(api_get_user_id(), 'system');
 $user_folder = $my_path['dir'].'my_files/';
 
 // Sanity checks for Chamilo.
 
 // Creation of a user owned folder if it does not exist.
 if (!file_exists($user_folder)) {
-	// A recursive call of mkdir function.
-	@mkdir($user_folder, $permissions_for_new_directories, true);
+    // A recursive call of mkdir function.
+    @mkdir($user_folder, $permissions_for_new_directories, true);
 }
 
 // Creation of repository used by paltform administrators if it does not exist.
 if (api_is_platform_admin()) {
-	$homepage_folder = api_get_path(SYS_PATH).'home/default_platform_document/';
-	if (!file_exists($homepage_folder)) {
-		@mkdir($homepage_folder, $permissions_for_new_directories);
-	}
+    $homepage_folder = api_get_path(SYS_PATH).'home/default_platform_document/';
+    if (!file_exists($homepage_folder)) {
+        @mkdir($homepage_folder, $permissions_for_new_directories);
+    }
 }
 
 
 // Create course shared folders
 if (api_is_in_course()) {
-	$course_dir      = $_course['path'].'/document';
-	$sys_course_path = api_get_path(SYS_COURSE_PATH);
-	$base_work_dir   = $sys_course_path.$course_dir;
-	$current_session_id = api_get_session_id();
-	$userinfo = Database::get_user_info_from_id(api_get_user_id());
+    $course_dir = $_course['path'].'/document';
+    $sys_course_path = api_get_path(SYS_COURSE_PATH);
+    $base_work_dir = $sys_course_path.$course_dir;
+    $current_session_id = api_get_session_id();
+    $userinfo = Database::get_user_info_from_id(api_get_user_id());
 
-	if($current_session_id==0){
-		//Create shared folder. Necessary for courses recycled. Allways session_id should be zero. Allway should be created from a base course, never from a session.
-		if (!file_exists($base_work_dir.'/shared_folder')) {
-			$usf_dir_title = get_lang('SharedFolder');
-			$usf_dir_name = '/shared_folder';
-			$to_group_id = 0;
-			$visibility = 0;
-			create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
-		}
-		// Create dynamic user shared folder
-		if (!file_exists($base_work_dir.'/shared_folder/sf_user_'.api_get_user_id())) {
-				$usf_dir_title = api_get_person_name($_user['firstName'], $_user['lastName']);
-				$usf_dir_name = '/shared_folder/sf_user_'.api_get_user_id();
-				$to_group_id = 0;
-				$visibility = 1;
-				create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
-		}
-	}
-	else{
-			//Create shared folder session
-			if (!file_exists($base_work_dir.'/shared_folder_session_'.$current_session_id)) {
-				$usf_dir_title = get_lang('SharedFolder').' ('.api_get_session_name($current_session_id).')';
-				$usf_dir_name = '/shared_folder_session_'.$current_session_id;
-				$to_group_id = 0;
-				$visibility = 0;
-				create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
-			}
-			//Create dynamic user shared folder into a shared folder session
-			if (!file_exists($base_work_dir.'/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id())) {
-				$usf_dir_title = api_get_person_name($_user['firstName'], $_user['lastName']).'('.api_get_session_name($current_session_id).')';
-				$usf_dir_name = '/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id();
-				$to_group_id = 0;
-				$visibility = 1;
-				create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $usf_dir_name, $usf_dir_title, $visibility);
-			}
-	}
+    if ($current_session_id == 0) {
+        //Create shared folder. Necessary for courses recycled. Allways session_id should be zero. Allway should be created from a base course, never from a session.
+        if (!file_exists($base_work_dir.'/shared_folder')) {
+            $usf_dir_title = get_lang('SharedFolder');
+            $usf_dir_name = '/shared_folder';
+            $to_group_id = 0;
+            $visibility = 0;
+            FileManager::create_unexisting_directory(
+                $_course,
+                $_user['user_id'],
+                api_get_session_id(),
+                $to_group_id,
+                $to_user_id,
+                $base_work_dir,
+                $usf_dir_name,
+                $usf_dir_title,
+                $visibility
+            );
+        }
+        // Create dynamic user shared folder
+        if (!file_exists($base_work_dir.'/shared_folder/sf_user_'.api_get_user_id())) {
+            $usf_dir_title = api_get_person_name($_user['firstName'], $_user['lastName']);
+            $usf_dir_name = '/shared_folder/sf_user_'.api_get_user_id();
+            $to_group_id = 0;
+            $visibility = 1;
+            FileManager::create_unexisting_directory(
+                $_course,
+                $_user['user_id'],
+                api_get_session_id(),
+                $to_group_id,
+                $to_user_id,
+                $base_work_dir,
+                $usf_dir_name,
+                $usf_dir_title,
+                $visibility
+            );
+        }
+    } else {
+        //Create shared folder session
+        if (!file_exists($base_work_dir.'/shared_folder_session_'.$current_session_id)) {
+            $usf_dir_title = get_lang('SharedFolder').' ('.api_get_session_name($current_session_id).')';
+            $usf_dir_name = '/shared_folder_session_'.$current_session_id;
+            $to_group_id = 0;
+            $visibility = 0;
+            FileManager::create_unexisting_directory(
+                $_course,
+                $_user['user_id'],
+                api_get_session_id(),
+                $to_group_id,
+                $to_user_id,
+                $base_work_dir,
+                $usf_dir_name,
+                $usf_dir_title,
+                $visibility
+            );
+        }
+        //Create dynamic user shared folder into a shared folder session
+        if (!file_exists($base_work_dir.'/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id())) {
+            $usf_dir_title = api_get_person_name($_user['firstName'], $_user['lastName']).'('.api_get_session_name(
+                $current_session_id
+            ).')';
+            $usf_dir_name = '/shared_folder_session_'.$current_session_id.'/sf_user_'.api_get_user_id();
+            $to_group_id = 0;
+            $visibility = 1;
+            FileManager::create_unexisting_directory(
+                $_course,
+                $_user['user_id'],
+                api_get_session_id(),
+                $to_group_id,
+                $to_user_id,
+                $base_work_dir,
+                $usf_dir_name,
+                $usf_dir_title,
+                $visibility
+            );
+        }
+    }
 }

+ 0 - 661
main/inc/lib/fileManage.lib.php

@@ -1,661 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- *	This is the file manage library for Chamilo.
- *	Include/require it in your code to use its functionality.
- *	@package chamilo.library
- */
-
-/**
-	This class contains functions that you can access statically.
-
-	FileManager::list_all_directories($path)
-	FileManager::list_all_files($dir_array)
-	FileManager::compat_load_file($file_name)
-	FileManager::set_default_settings($upload_path, $filename, $filetype="file", $glued_table, $default_visibility='v')
-
-	@author Roan Embrechts
-	@version 1.1, July 2004
- *	@package chamilo.library
-*/
-class FileManager
-{
-    /**
-     * Update the file or directory path in the document db document table
-     *
-     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
-     * @param  - action (string) - action type require : 'delete' or 'update'
-     * @param  - old_path (string) - old path info stored to change
-     * @param  - new_path (string) - new path info to substitute
-     * @desc Update the file or directory path in the document db document table
-     *
-     */
-    static function update_db_info($action, $old_path, $new_path = '') {
-        $dbTable = Database::get_course_table(TABLE_DOCUMENT);
-        $course_id = api_get_course_int_id();
-
-        /* DELETE */
-        if ($action == 'delete') {
-
-            $old_path = Database::escape_string($old_path);
-            $to_delete = "WHERE c_id = $course_id AND path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
-            $query = "DELETE FROM $dbTable " . $to_delete;
-
-            $result = Database::query("SELECT id FROM $dbTable " . $to_delete);
-
-            if (Database::num_rows($result)) {
-                require_once api_get_path(INCLUDE_PATH).'../metadata/md_funcs.php';
-                $mdStore = new mdstore(TRUE);  // create if needed
-
-                $md_type = (substr($dbTable, -13) == 'scormdocument') ? 'Scorm' : 'Document';
-
-                while ($row = Database::fetch_array($result)) {
-                    $eid = $md_type . '.' . $row['id'];
-                    $mdStore->mds_delete($eid);
-                    $mdStore->mds_delete_offspring($eid);
-                }
-            }
-        }
-
-        /* UPDATE */
-
-        if ($action == 'update') {
-            if ($new_path[0] == '.') $new_path = substr($new_path, 1);
-            $new_path = str_replace('//', '/', $new_path);
-
-            // Attempt to update	- tested & working for root	dir
-            $new_path = Database::escape_string($new_path);
-            $query = "UPDATE $dbTable
-            SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
-            WHERE c_id = $course_id AND path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
-        }
-        Database::query($query);
-    }
-
-    /**
-     * Cheks a file or a directory actually exist at this location
-     *
-     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
-     * @param  - file_path (string) - path of the presume existing file or dir
-     * @return - boolean TRUE if the file or the directory exists
-     *           boolean FALSE otherwise.
-     */
-    static function check_name_exist($file_path) {
-        clearstatcache();
-        $save_dir = getcwd();
-        if (!is_dir(dirname($file_path))) {
-            return false;
-        }
-        chdir(dirname($file_path));
-        $file_name = basename($file_path);
-
-        if (file_exists($file_name)) {
-            chdir($save_dir);
-            return true;
-        } else {
-            chdir($save_dir);
-            return false;
-        }
-    }
-
-    /**
-     * Deletes a file or a directory
-     *
-     * @author - Hugues Peeters
-     * @param  - $file (String) - the path of file or directory to delete
-     * @return - bolean - true if the delete succeed
-     *           bolean - false otherwise.
-     * @see    - delete() uses check_name_exist() and removeDir() functions
-     */
-    static function my_delete($file) {
-        if (self::check_name_exist($file)) {
-            if (is_file($file)) { // FILE CASE
-                unlink($file);
-                return true;
-            } elseif (is_dir($file)) { // DIRECTORY CASE
-                self::removeDir($file);
-                return true;
-            }
-        } else {
-            return false; // no file or directory to delete
-        }
-    }
-
-    /**
-     * Removes a directory recursively
-     *
-     * @returns true if OK, otherwise false
-     *
-     * @author Amary <MasterNES@aol.com> (from Nexen.net)
-     * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
-     *
-     * @param string	$dir		directory to remove
-     */
-    static function removeDir($dir) {
-        if (!@$opendir = opendir($dir)) {
-            return false;
-        }
-
-        while ($readdir = readdir($opendir)) {
-            if ($readdir != '..' && $readdir != '.') {
-                if (is_file($dir.'/'.$readdir)) {
-                    if (!@unlink($dir.'/'.$readdir)) {
-                        return false;
-                    }
-                } elseif (is_dir($dir.'/'.$readdir)) {
-                    if (!self::removeDir($dir.'/'.$readdir)) {
-                        return false;
-                    }
-                }
-            }
-        }
-
-        closedir($opendir);
-
-        if (!@rmdir($dir)) {
-            return false;
-        }
-
-        return true;
-    }
-
-
-    /**
-     * Return true if folder is empty
-     * @author : hubert.borderiou@grenet.fr
-     * @param string $in_folder : folder path on disk
-     * @return 1 if folder is empty, 0 otherwise
-    */
-
-    static function folder_is_empty($in_folder) {
-        $tab_folder_content = scandir($in_folder);
-        $folder_is_empty = 0;
-        if ((count($tab_folder_content) == 2 && in_array(".", $tab_folder_content) && in_array("..", $tab_folder_content)) || (count($tab_folder_content) < 2)) {
-            $folder_is_empty = 1;
-        }
-        return $folder_is_empty;
-    }
-
-
-    /**
-     * Renames a file or a directory
-     *
-     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
-     * @param  - $file_path (string) - complete path of the file or the directory
-     * @param  - $new_file_name (string) - new name for the file or the directory
-     * @return - boolean - true if succeed
-     *         - boolean - false otherwise
-     * @see    - rename() uses the check_name_exist() and php2phps() functions
-     */
-    static function my_rename($file_path, $new_file_name) {
-
-        $save_dir = getcwd();
-        $path = dirname($file_path);
-        $old_file_name = basename($file_path);
-
-        $new_file_name = replace_dangerous_char($new_file_name);
-
-        // If no extension, take the old one
-        if ((strpos($new_file_name, '.') === false) && ($dotpos = strrpos($old_file_name, '.'))) {
-            $new_file_name .= substr($old_file_name, $dotpos);
-        }
-
-        // Note: still possible: 'xx.yy' -rename-> '.yy' -rename-> 'zz'
-        // This is useful for folder names, where otherwise '.' would be sticky
-
-        // Extension PHP is not allowed, change to PHPS
-        $new_file_name = php2phps($new_file_name);
-
-        if ($new_file_name == $old_file_name) {
-            return $old_file_name;
-        }
-
-        if (strtolower($new_file_name) != strtolower($old_file_name) && self::check_name_exist($path.'/'.$new_file_name)) {
-            return false;
-        }
-        // On a Windows server, it would be better not to do the above check
-        // because it succeeds for some new names resembling the old name.
-        // But on Unix/Linux the check must be done because rename overwrites.
-
-        chdir($path);
-        $res = rename($old_file_name, $new_file_name) ? $new_file_name : false;
-        chdir($save_dir);
-        return $res;
-    }
-
-    /**
-     * Moves a file or a directory to an other area
-     *
-     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
-     * @param  - $source (String) - the path of file or directory to move
-     * @param  - $target (String) - the path of the new area
-     * @return - bolean - true if the move succeed
-     *           bolean - false otherwise.
-     * @see    - move() uses check_name_exist() and copyDirTo() functions
-     */
-    static function move($source, $target) {
-
-        if (self::check_name_exist($source)) {
-            $file_name = basename($source);
-
-            if (self::check_name_exist($target.'/'.$file_name)) {
-                return false;
-            } else {
-                /* File case */
-                if (is_file($source)) {
-                    copy($source , $target.'/'.$file_name);
-                    unlink($source);
-                    return true;
-                } elseif (is_dir($source)) {
-                    /* Directory case */
-                    // Check to not copy the directory inside itself
-                    if (ereg('^'.$source.'/', $target.'/')) { // TODO: ereg() function is deprecated in PHP 5.3
-                        return false;
-                    } else {
-                        self::copyDirTo($source, $target);
-                        return true;
-                    }
-                }
-            }
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * Moves a directory and its content to an other area
-     *
-     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
-     * @param  - $orig_dir_path (string) - the path of the directory to move
-     * @param  - $destination (string) - the path of the new area
-     * @return - no return
-     */
-    static function copyDirTo($orig_dir_path, $destination, $move = true) {
-
-        $save_dir = getcwd();
-        // Extract directory name - create it at destination - update destination trail
-        $dir_name = basename($orig_dir_path);
-        if (is_dir($orig_dir_path)) {
-            mkdir($destination.'/'.$dir_name, api_get_permissions_for_new_directories());
-            $destination_trail = $destination.'/'.$dir_name;
-            if (is_dir($destination)) {
-                chdir ($orig_dir_path) ;
-                $handle = opendir($orig_dir_path);
-
-                while ($element = readdir($handle)) {
-                    if ($element == '.' || $element == '..') {
-                        continue; // Skip the current and parent directories
-                    } elseif (is_file($element)) {
-                        copy($element, $destination_trail.'/'.$element);
-
-                        if ($move) {
-                            unlink($element) ;
-                        }
-                    } elseif (is_dir($element)) {
-                        $dir_to_copy[] = $orig_dir_path.'/'.$element;
-                    }
-                }
-
-                closedir($handle) ;
-
-                if (sizeof($dir_to_copy) > 0) {
-                    foreach ($dir_to_copy as $this_dir) {
-                        self::copyDirTo($this_dir, $destination_trail, $move); // Recursivity
-                    }
-                }
-
-                if ($move) {
-                    rmdir($orig_dir_path) ;
-                }
-                chdir($save_dir);
-            }
-        }
-    }
-
-    /* NOTE: These functions batch is used to automatically build HTML forms
-     * with a list of the directories contained on the course Directory.
-     *
-     * From a thechnical point of view, form_dir_lists calls sort_dir wich calls index_dir
-     */
-
-    /**
-     * Gets all the directories and subdirectories
-     * contented in a given directory
-     *
-     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
-     * @param  - path (string) - directory path of the one to index
-     * @return - an array containing the path of all the subdirectories
-     */
-    static function index_dir($path) {
-        $dir_array = array();
-        $save_dir = getcwd();
-        if (is_dir($path)){
-            chdir($path);
-            $handle = opendir($path);
-            // Reads directory content end record subdirectoies names in $dir_array
-            if ($handle !== false) {
-                while ($element = readdir($handle)) {
-                    if ($element == '.' || $element == '..') continue; // Skip the current and parent directories
-                    if (is_dir($element)) $dir_array[] = $path.'/'.$element;
-                }
-                closedir($handle) ;
-            }
-            // Recursive operation if subdirectories exist
-            $dir_number = sizeof($dir_array);
-            if ($dir_number > 0) {
-                for ($i = 0 ; $i < $dir_number ; $i++) {
-                    $sub_dir_array = self::index_dir($dir_array[$i]); // Function recursivity
-                    $dir_array  =  array_merge((array)$dir_array, (array)$sub_dir_array); // Data merge
-                }
-            }
-        }
-        chdir($save_dir) ;
-        return $dir_array ;
-    }
-
-    /**
-     * Indexes all the directories and subdirectories
-     * contented in a given directory, and sort them alphabetically
-     *
-     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
-     * @param  - path (string) - directory path of the one to index
-     * @return - an array containing the path of all the subdirectories sorted
-     *           false, if there is no directory
-     * @see    - index_and_sort_dir uses the index_dir() function
-     */
-    static function index_and_sort_dir($path) {
-        $dir_list = self::index_dir($path);
-        if ($dir_list) {
-            natsort($dir_list);
-            return $dir_list;
-        }
-        return false;
-    }
-
-
-    /**
-     * Extracting extention of a filename
-     *
-     * @returns array
-     * @param 	string	$filename 		filename
-     */
-    static function getextension($filename) {
-        $bouts = explode('.', $filename);
-        return array(array_pop($bouts), implode('.', $bouts));
-    }
-
-    /**
-     * Calculation size of a directory
-     *
-     * @returns integer size
-     * @param 	string	$path path to size
-     * @param 	boolean $recursive if true , include subdir in total
-     */
-    static function dirsize($root, $recursive = true) {
-        $dir = @opendir($root);
-        $size = 0;
-        while ($file = @readdir($dir)) {
-            if (!in_array($file, array('.', '..'))) {
-                if (is_dir($root.'/'.$file)) {
-                    $size += $recursive ? dirsize($root.'/'.$file) : 0;
-                } else {
-                    $size += @filesize($root.'/'.$file);
-                }
-            }
-        }
-        @closedir($dir);
-        return $size;
-    }
-
-	/**
-		Returns a list of all directories, except the base dir,
-		of the current course. This function uses recursion.
-
-		Convention: the parameter $path does not end with a slash.
-
-		@author Roan Embrechts
-		@version 1.0.1
-	*/
-	static function list_all_directories($path) {
-
-		$result_array = array();
-		if (is_dir($path)) {
-			$save_dir = getcwd();
-			chdir($path);
-			$handle = opendir($path);
-			while ($element = readdir($handle)) {
-				if ($element == '.' || $element == '..') continue; // Skip the current and parent directories
-				if (is_dir($element)) {
-					$dir_array[] = $path.'/'.$element;
-				}
-			}
-			closedir($handle);
-			// Recursive operation if subdirectories exist
-			$dir_number = sizeof($dir_array);
-			if ($dir_number > 0) {
-				for ($i = 0 ; $i < $dir_number ; $i++) {
-					$sub_dir_array = FileManager::list_all_directories($dir_array[$i]); // Function recursivity
-					if (is_array($dir_array) && is_array($sub_dir_array)) {
-						$dir_array  =  array_merge($dir_array, $sub_dir_array); // Data merge
-					}
-				}
-			}
-			$result_array  =  $dir_array;
-			chdir($save_dir) ;
-		}
-		return $result_array ;
-	}
-
-	/**
-		This function receives a list of directories.
-		It returns a list of all files in these directories
-
-		@author Roan Embrechts
-		@version 1.0
-	*/
-	function list_all_files($dir_array) {
-
-		$element_array = array();
-		if (is_dir($dir_array)) {
-
-			$save_dir = getcwd();
-			foreach ($dir_array as $directory) {
-				chdir($directory);
-				$handle = opendir($directory);
-			   	while ($element = readdir($handle)) {
-					if ($element == '.' || $element == '..' || $element == '.htaccess') continue; // Skip the current and parent directories
-					if (!is_dir($element)) {
-						$element_array[] = $directory.'/'.$element;
-					}
-				}
-				closedir($handle);
-				chdir('..');
-				chdir($save_dir);
-			}
-		}
-		return $element_array;
-	}
-
-	/**
-		Loads contents of file $filename into memory and returns them as a string.
-		Function kept for compatibility with older PHP versions.
-		Function is binary safe (is needed on Windows)
-	*/
-	function compat_load_file($file_name) {
-		$buffer = '';
-		if (file_exists($file_name)) {
-			$fp = fopen($file_name, 'rb');
-			$buffer = fread ($fp, filesize($file_name));
-			fclose ($fp);
-		}
-		return $buffer;
-	}
-
-	/**
-	 * Adds file/folder to document table in database
-	 * improvement from set_default_settings (see below):
-	 * take all info from function parameters
-	 * no global variables needed
-	 *
-	 * NOTE $glued_table should already have backticks around it
-	 * (get it from the database library, and it is done automatically)
-	 *
-	 * @param	path, filename, filetype,
-				$glued_table, default_visibility
-
-	 * action:	Adds an entry to the document table with the default settings.
-	 * @author	Olivier Cauberghe <olivier.cauberghe@ugent.be>
-	 * @author	Roan Embrechts
-	 * @version 1.2
-	 */
-	function set_default_settings($upload_path, $filename, $filetype = 'file', $glued_table, $default_visibility = 'v') {
-		if (!$default_visibility) $default_visibility = 'v';
-
-		// Make sure path is not wrongly formed
-		$upload_path = !empty($upload_path) ? "/$upload_path" : '';
-
-		$endchar = substr($filename, strlen($filename) - 1, 1);
-		if ($endchar == "\\" || $endchar == '/') {
-			$filename = substr($filename, 0, strlen($filename) - 1);
-		}
-
-		$full_file_name = $upload_path.'/'.$filename;
-		//$upload_path = str_replace("//", '/', $upload_path);
-		$full_file_name = str_replace("//", '/', $full_file_name);
-
-		$sql_query = "SELECT count(*) as number_existing FROM $glued_table WHERE path='$full_file_name'";
-		$sql_result = Database::query($sql_query);
-		$result = Database::fetch_array($sql_result);
-		// Determine which query to execute
-		if ($result['number_existing'] > 0) {
-			// Entry exists, update
-			$query = "UPDATE $glued_table SET path='$full_file_name',visibility='$default_visibility', filetype='$filetype' WHERE path='$full_file_name'";
-		} else {
-			// No entry exists, create new one
-			$query = "INSERT INTO $glued_table (path,visibility,filetype) VALUES('$full_file_name','$default_visibility','$filetype')";
-		}
-		Database::query($query);
-	}
-
-    function choose_image($file_name)
-    {
-        static $type, $image;
-
-        /* TABLES INITIALISATION */
-        if (!$type || !$image)
-        {
-            $type['word'      ] = array('doc', 'dot',  'rtf', 'mcw',  'wps', 'psw', 'docm', 'docx', 'dotm',  'dotx');
-            $type['web'       ] = array('htm', 'html', 'htx', 'xml',  'xsl',  'php', 'xhtml');
-            $type['image'     ] = array('gif', 'jpg',  'png', 'bmp',  'jpeg', 'tif', 'tiff');
-            $type['image_vect'] = array('svg','svgz');
-            $type['audio'     ] = array('wav', 'mid',  'mp2', 'mp3',  'midi', 'sib', 'amr', 'kar', 'oga','au','wma');
-            $type['video'     ] = array('mp4', 'mov',  'rm',  'pls',  'mpg',  'mpeg', 'm2v', 'm4v', 'flv', 'f4v', 'avi', 'wmv', 'asf', '3gp','ogv','ogg','ogx','webm');
-            $type['excel'     ] = array('xls', 'xlt',  'xls', 'xlt', 'pxl', 'xlsx', 'xlsm', 'xlam', 'xlsb', 'xltm', 'xltx');
-            $type['compressed'] = array('zip', 'tar',  'rar', 'gz');
-            $type['code'      ] = array('js',  'cpp',  'c',   'java', 'phps', 'jsp', 'asp', 'aspx', 'cfm');
-            $type['acrobat'   ] = array('pdf');
-            $type['powerpoint'] = array('ppt', 'pps', 'pptm', 'pptx', 'potm', 'potx', 'ppam', 'ppsm', 'ppsx');
-            $type['flash'     ] = array('fla', 'swf');
-            $type['text'      ] = array('txt','log');
-            $type['oo_writer' ] = array('odt', 'ott', 'sxw', 'stw');
-            $type['oo_calc'   ] = array('ods', 'ots', 'sxc', 'stc');
-            $type['oo_impress'] = array('odp', 'otp', 'sxi', 'sti');
-            $type['oo_draw'   ] = array('odg', 'otg', 'sxd', 'std');
-            $type['epub'      ] = array('epub');
-            $type['java'      ] = array('class','jar');
-            $type['freemind'  ] = array('mm');
-
-            $image['word'      ] = 'word.gif';
-            $image['web'       ] = 'file_html.gif';
-            $image['image'     ] = 'file_image.gif';
-            $image['image_vect'] = 'file_svg.png';
-            $image['audio'     ] = 'file_sound.gif';
-            $image['video'     ] = 'film.gif';
-            $image['excel'     ] = 'excel.gif';
-            $image['compressed'] = 'file_zip.gif';
-            $image['code'      ] = 'icons/22/mime_code.png';
-            $image['acrobat'   ] = 'file_pdf.gif';
-            $image['powerpoint'] = 'powerpoint.gif';
-            $image['flash'     ] = 'file_flash.gif';
-            $image['text'      ] = 'icons/22/mime_text.png';
-            $image['oo_writer' ] = 'file_oo_writer.gif';
-            $image['oo_calc'   ] = 'file_oo_calc.gif';
-            $image['oo_impress'] = 'file_oo_impress.gif';
-            $image['oo_draw'   ] = 'file_oo_draw.gif';
-            $image['epub'      ] = 'file_epub.gif';
-            $image['java'      ] = 'file_java.png';
-            $image['freemind'  ] = 'file_freemind.png';
-        }
-
-        /* FUNCTION CORE */
-        $extension = array();
-        if (!is_array($file_name)) {
-            if (preg_match('/\.([[:alnum:]]+)(\?|$)/', $file_name, $extension)) {
-                $extension[1] = strtolower($extension[1]);
-
-                foreach ($type as $generic_type => $extension_list)
-                {
-                    if (in_array($extension[1], $extension_list))
-                    {
-                        return $image[$generic_type];
-                    }
-                }
-            }
-        }
-        return 'defaut.gif';
-    }
-
-    /**
-     * Transform the file path to a URL.
-     *
-     * @param  - $file_path (string) - Relative local path of the file on the hard disk
-     * @return - Relative url
-     */
-    function format_url($file_path)
-    {
-        $path_component = explode('/', $file_path);
-        $path_component = array_map('rawurlencode', $path_component);
-        return implode('/', $path_component);
-    }
-
-    /**
-     * Calculates the total size of a directory by adding the sizes (that
-     * are stored in the database) of all files & folders in this directory.
-     *
-     * @param 	string  $path
-     * @param 	boolean $can_see_invisible
-     * @return 	Total size
-     */
-    function get_total_folder_size($path, $can_see_invisible = false) {
-        $table_itemproperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
-        $table_document 	= Database::get_course_table(TABLE_DOCUMENT);
-        $tool_document 		= TOOL_DOCUMENT;
-
-        $course_id 			= api_get_course_int_id();
-        $session_id         = api_get_session_id();
-        $session_condition  = api_get_session_condition($session_id, true, true, 'props.id_session');
-
-        $visibility_rule = ' props.visibility ' . ($can_see_invisible ? '<> 2' : '= 1');
-
-        $sql = "SELECT SUM(table1.size) FROM (
-                    SELECT size FROM $table_itemproperty AS props, $table_document AS docs
-                    WHERE 	docs.c_id 	= $course_id AND
-                            docs.id 	= props.ref AND
-                            docs.path LIKE '$path/%' AND
-                            props.c_id 	= $course_id AND
-                            props.tool 	= '$tool_document' AND
-                            $visibility_rule
-                            $session_condition
-                    GROUP BY ref
-                ) as table1";
-
-        $result = Database::query($sql);
-        if ($result && Database::num_rows($result) != 0) {
-            $row = Database::fetch_row($result);
-            return $row[0] == null ? 0 : $row[0];
-        } else {
-            return 0;
-        }
-    }
-}

+ 2127 - 0
main/inc/lib/fileManager.lib.php

@@ -0,0 +1,2127 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+/**
+ *    This is the file manage library for Chamilo.
+ *    Include/require it in your code to use its functionality.
+ * @package chamilo.library
+ */
+
+/**
+This class contains functions that you can access statically.
+
+FileManager::list_all_directories($path)
+FileManager::list_all_files($dir_array)
+FileManager::compat_load_file($file_name)
+FileManager::set_default_settings($upload_path, $filename, $filetype="file", $glued_table, $default_visibility='v')
+
+@author Roan Embrechts
+@version 1.1, July 2004
+ * @package chamilo.library
+ */
+class FileManager
+{
+    /**
+     * Update the file or directory path in the document db document table
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - action (string) - action type require : 'delete' or 'update'
+     * @param  - old_path (string) - old path info stored to change
+     * @param  - new_path (string) - new path info to substitute
+     * @desc Update the file or directory path in the document db document table
+     *
+     */
+    static function update_db_info($action, $old_path, $new_path = '')
+    {
+        $dbTable = Database::get_course_table(TABLE_DOCUMENT);
+        $course_id = api_get_course_int_id();
+
+        /* DELETE */
+        if ($action == 'delete') {
+
+            $old_path = Database::escape_string($old_path);
+            $to_delete = "WHERE c_id = $course_id AND path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
+            $query = "DELETE FROM $dbTable ".$to_delete;
+
+            $result = Database::query("SELECT id FROM $dbTable ".$to_delete);
+
+            if (Database::num_rows($result)) {
+                require_once api_get_path(INCLUDE_PATH).'../metadata/md_funcs.php';
+                $mdStore = new mdstore(true); // create if needed
+
+                $md_type = (substr($dbTable, -13) == 'scormdocument') ? 'Scorm' : 'Document';
+
+                while ($row = Database::fetch_array($result)) {
+                    $eid = $md_type.'.'.$row['id'];
+                    $mdStore->mds_delete($eid);
+                    $mdStore->mds_delete_offspring($eid);
+                }
+            }
+        }
+
+        /* UPDATE */
+
+        if ($action == 'update') {
+            if ($new_path[0] == '.') {
+                $new_path = substr($new_path, 1);
+            }
+            $new_path = str_replace('//', '/', $new_path);
+
+            // Attempt to update	- tested & working for root	dir
+            $new_path = Database::escape_string($new_path);
+            $query = "UPDATE $dbTable
+            SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
+            WHERE c_id = $course_id AND path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
+        }
+        Database::query($query);
+    }
+
+    /**
+     * Cheks a file or a directory actually exist at this location
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - file_path (string) - path of the presume existing file or dir
+     * @return - boolean TRUE if the file or the directory exists
+     *           boolean FALSE otherwise.
+     */
+    static function check_name_exist($file_path)
+    {
+        clearstatcache();
+        $save_dir = getcwd();
+        if (!is_dir(dirname($file_path))) {
+            return false;
+        }
+        chdir(dirname($file_path));
+        $file_name = basename($file_path);
+
+        if (file_exists($file_name)) {
+            chdir($save_dir);
+
+            return true;
+        } else {
+            chdir($save_dir);
+
+            return false;
+        }
+    }
+
+    /**
+     * Deletes a file or a directory
+     *
+     * @author - Hugues Peeters
+     * @param  - $file (String) - the path of file or directory to delete
+     * @return - bolean - true if the delete succeed
+     *           bolean - false otherwise.
+     * @see    - delete() uses check_name_exist() and removeDir() functions
+     */
+    static function my_delete($file)
+    {
+        if (self::check_name_exist($file)) {
+            if (is_file($file)) { // FILE CASE
+                unlink($file);
+
+                return true;
+            } elseif (is_dir($file)) { // DIRECTORY CASE
+                self::removeDir($file);
+
+                return true;
+            }
+        } else {
+            return false; // no file or directory to delete
+        }
+    }
+
+    /**
+     * Removes a directory recursively
+     *
+     * @returns true if OK, otherwise false
+     *
+     * @author Amary <MasterNES@aol.com> (from Nexen.net)
+     * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
+     *
+     * @param string    $dir        directory to remove
+     */
+    static function removeDir($dir)
+    {
+        if (!@$opendir = opendir($dir)) {
+            return false;
+        }
+
+        while ($readdir = readdir($opendir)) {
+            if ($readdir != '..' && $readdir != '.') {
+                if (is_file($dir.'/'.$readdir)) {
+                    if (!@unlink($dir.'/'.$readdir)) {
+                        return false;
+                    }
+                } elseif (is_dir($dir.'/'.$readdir)) {
+                    if (!self::removeDir($dir.'/'.$readdir)) {
+                        return false;
+                    }
+                }
+            }
+        }
+
+        closedir($opendir);
+
+        if (!@rmdir($dir)) {
+            return false;
+        }
+
+        return true;
+    }
+
+
+    /**
+     * Return true if folder is empty
+     * @author : hubert.borderiou@grenet.fr
+     * @param string $in_folder : folder path on disk
+     * @return 1 if folder is empty, 0 otherwise
+     */
+
+    static function folder_is_empty($in_folder)
+    {
+        $tab_folder_content = scandir($in_folder);
+        $folder_is_empty = 0;
+        if ((count($tab_folder_content) == 2 && in_array(".", $tab_folder_content) && in_array(
+            "..",
+            $tab_folder_content
+        )) || (count($tab_folder_content) < 2)
+        ) {
+            $folder_is_empty = 1;
+        }
+
+        return $folder_is_empty;
+    }
+
+
+    /**
+     * Renames a file or a directory
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - $file_path (string) - complete path of the file or the directory
+     * @param  - $new_file_name (string) - new name for the file or the directory
+     * @return - boolean - true if succeed
+     *         - boolean - false otherwise
+     * @see    - rename() uses the check_name_exist() and php2phps() functions
+     */
+    static function my_rename($file_path, $new_file_name)
+    {
+
+        $save_dir = getcwd();
+        $path = dirname($file_path);
+        $old_file_name = basename($file_path);
+
+        $new_file_name = replace_dangerous_char($new_file_name);
+
+        // If no extension, take the old one
+        if ((strpos($new_file_name, '.') === false) && ($dotpos = strrpos($old_file_name, '.'))) {
+            $new_file_name .= substr($old_file_name, $dotpos);
+        }
+
+        // Note: still possible: 'xx.yy' -rename-> '.yy' -rename-> 'zz'
+        // This is useful for folder names, where otherwise '.' would be sticky
+
+        // Extension PHP is not allowed, change to PHPS
+        $new_file_name = self::php2phps($new_file_name);
+
+        if ($new_file_name == $old_file_name) {
+            return $old_file_name;
+        }
+
+        if (strtolower($new_file_name) != strtolower($old_file_name) && self::check_name_exist(
+            $path.'/'.$new_file_name
+        )
+        ) {
+            return false;
+        }
+        // On a Windows server, it would be better not to do the above check
+        // because it succeeds for some new names resembling the old name.
+        // But on Unix/Linux the check must be done because rename overwrites.
+
+        chdir($path);
+        $res = rename($old_file_name, $new_file_name) ? $new_file_name : false;
+        chdir($save_dir);
+
+        return $res;
+    }
+
+    /**
+     * Moves a file or a directory to an other area
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - $source (String) - the path of file or directory to move
+     * @param  - $target (String) - the path of the new area
+     * @return - bolean - true if the move succeed
+     *           bolean - false otherwise.
+     * @see    - move() uses check_name_exist() and copyDirTo() functions
+     */
+    static function move($source, $target)
+    {
+
+        if (self::check_name_exist($source)) {
+            $file_name = basename($source);
+
+            if (self::check_name_exist($target.'/'.$file_name)) {
+                return false;
+            } else {
+                /* File case */
+                if (is_file($source)) {
+                    copy($source, $target.'/'.$file_name);
+                    unlink($source);
+
+                    return true;
+                } elseif (is_dir($source)) {
+                    /* Directory case */
+                    // Check to not copy the directory inside itself
+                    if (ereg('^'.$source.'/', $target.'/')) { // TODO: ereg() function is deprecated in PHP 5.3
+                        return false;
+                    } else {
+                        self::copyDirTo($source, $target);
+
+                        return true;
+                    }
+                }
+            }
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Moves a directory and its content to an other area
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - $orig_dir_path (string) - the path of the directory to move
+     * @param  - $destination (string) - the path of the new area
+     * @return - no return
+     */
+    static function copyDirTo($orig_dir_path, $destination, $move = true)
+    {
+
+        $save_dir = getcwd();
+        // Extract directory name - create it at destination - update destination trail
+        $dir_name = basename($orig_dir_path);
+        if (is_dir($orig_dir_path)) {
+            mkdir($destination.'/'.$dir_name, api_get_permissions_for_new_directories());
+            $destination_trail = $destination.'/'.$dir_name;
+            if (is_dir($destination)) {
+                chdir($orig_dir_path);
+                $handle = opendir($orig_dir_path);
+
+                while ($element = readdir($handle)) {
+                    if ($element == '.' || $element == '..') {
+                        continue; // Skip the current and parent directories
+                    } elseif (is_file($element)) {
+                        copy($element, $destination_trail.'/'.$element);
+
+                        if ($move) {
+                            unlink($element);
+                        }
+                    } elseif (is_dir($element)) {
+                        $dir_to_copy[] = $orig_dir_path.'/'.$element;
+                    }
+                }
+
+                closedir($handle);
+
+                if (sizeof($dir_to_copy) > 0) {
+                    foreach ($dir_to_copy as $this_dir) {
+                        self::copyDirTo($this_dir, $destination_trail, $move); // Recursivity
+                    }
+                }
+
+                if ($move) {
+                    rmdir($orig_dir_path);
+                }
+                chdir($save_dir);
+            }
+        }
+    }
+
+    /* NOTE: These functions batch is used to automatically build HTML forms
+     * with a list of the directories contained on the course Directory.
+     *
+     * From a thechnical point of view, form_dir_lists calls sort_dir wich calls index_dir
+     */
+
+    /**
+     * Gets all the directories and subdirectories
+     * contented in a given directory
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - path (string) - directory path of the one to index
+     * @return - an array containing the path of all the subdirectories
+     */
+    static function index_dir($path)
+    {
+        $dir_array = array();
+        $save_dir = getcwd();
+        if (is_dir($path)) {
+            chdir($path);
+            $handle = opendir($path);
+            // Reads directory content end record subdirectoies names in $dir_array
+            if ($handle !== false) {
+                while ($element = readdir($handle)) {
+                    if ($element == '.' || $element == '..') {
+                        continue;
+                    } // Skip the current and parent directories
+                    if (is_dir($element)) {
+                        $dir_array[] = $path.'/'.$element;
+                    }
+                }
+                closedir($handle);
+            }
+            // Recursive operation if subdirectories exist
+            $dir_number = sizeof($dir_array);
+            if ($dir_number > 0) {
+                for ($i = 0; $i < $dir_number; $i++) {
+                    $sub_dir_array = self::index_dir($dir_array[$i]); // Function recursivity
+                    $dir_array = array_merge((array)$dir_array, (array)$sub_dir_array); // Data merge
+                }
+            }
+        }
+        chdir($save_dir);
+
+        return $dir_array;
+    }
+
+    /**
+     * Indexes all the directories and subdirectories
+     * contented in a given directory, and sort them alphabetically
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - path (string) - directory path of the one to index
+     * @return - an array containing the path of all the subdirectories sorted
+     *           false, if there is no directory
+     * @see    - index_and_sort_dir uses the index_dir() function
+     */
+    static function index_and_sort_dir($path)
+    {
+        $dir_list = self::index_dir($path);
+        if ($dir_list) {
+            natsort($dir_list);
+
+            return $dir_list;
+        }
+
+        return false;
+    }
+
+
+    /**
+     * Extracting extention of a filename
+     *
+     * @returns array
+     * @param     string    $filename         filename
+     */
+    static function getextension($filename)
+    {
+        $bouts = explode('.', $filename);
+
+        return array(array_pop($bouts), implode('.', $bouts));
+    }
+
+    /**
+     * Calculation size of a directory
+     *
+     * @returns integer size
+     * @param     string    $path path to size
+     * @param     boolean $recursive if true , include subdir in total
+     */
+    static function dirsize($root, $recursive = true)
+    {
+        $dir = @opendir($root);
+        $size = 0;
+        while ($file = @readdir($dir)) {
+            if (!in_array($file, array('.', '..'))) {
+                if (is_dir($root.'/'.$file)) {
+                    $size += $recursive ? dirsize($root.'/'.$file) : 0;
+                } else {
+                    $size += @filesize($root.'/'.$file);
+                }
+            }
+        }
+        @closedir($dir);
+
+        return $size;
+    }
+
+    /**
+    Returns a list of all directories, except the base dir,
+    of the current course. This function uses recursion.
+
+    Convention: the parameter $path does not end with a slash.
+
+    @author Roan Embrechts
+    @version 1.0.1
+     */
+    static function list_all_directories($path)
+    {
+
+        $result_array = array();
+        if (is_dir($path)) {
+            $save_dir = getcwd();
+            chdir($path);
+            $handle = opendir($path);
+            while ($element = readdir($handle)) {
+                if ($element == '.' || $element == '..') {
+                    continue;
+                } // Skip the current and parent directories
+                if (is_dir($element)) {
+                    $dir_array[] = $path.'/'.$element;
+                }
+            }
+            closedir($handle);
+            // Recursive operation if subdirectories exist
+            $dir_number = sizeof($dir_array);
+            if ($dir_number > 0) {
+                for ($i = 0; $i < $dir_number; $i++) {
+                    $sub_dir_array = self::list_all_directories($dir_array[$i]); // Function recursivity
+                    if (is_array($dir_array) && is_array($sub_dir_array)) {
+                        $dir_array = array_merge($dir_array, $sub_dir_array); // Data merge
+                    }
+                }
+            }
+            $result_array = $dir_array;
+            chdir($save_dir);
+        }
+
+        return $result_array;
+    }
+
+    /**
+    This function receives a list of directories.
+    It returns a list of all files in these directories
+
+    @author Roan Embrechts
+    @version 1.0
+     */
+    function list_all_files($dir_array)
+    {
+
+        $element_array = array();
+        if (is_dir($dir_array)) {
+
+            $save_dir = getcwd();
+            foreach ($dir_array as $directory) {
+                chdir($directory);
+                $handle = opendir($directory);
+                while ($element = readdir($handle)) {
+                    if ($element == '.' || $element == '..' || $element == '.htaccess') {
+                        continue;
+                    } // Skip the current and parent directories
+                    if (!is_dir($element)) {
+                        $element_array[] = $directory.'/'.$element;
+                    }
+                }
+                closedir($handle);
+                chdir('..');
+                chdir($save_dir);
+            }
+        }
+
+        return $element_array;
+    }
+
+    /**
+    Loads contents of file $filename into memory and returns them as a string.
+    Function kept for compatibility with older PHP versions.
+    Function is binary safe (is needed on Windows)
+     */
+    function compat_load_file($file_name)
+    {
+        $buffer = '';
+        if (file_exists($file_name)) {
+            $fp = fopen($file_name, 'rb');
+            $buffer = fread($fp, filesize($file_name));
+            fclose($fp);
+        }
+
+        return $buffer;
+    }
+
+    function choose_image($file_name)
+    {
+        static $type, $image;
+
+        /* TABLES INITIALISATION */
+        if (!$type || !$image) {
+            $type['word'] = array('doc', 'dot', 'rtf', 'mcw', 'wps', 'psw', 'docm', 'docx', 'dotm', 'dotx');
+            $type['web'] = array('htm', 'html', 'htx', 'xml', 'xsl', 'php', 'xhtml');
+            $type['image'] = array('gif', 'jpg', 'png', 'bmp', 'jpeg', 'tif', 'tiff');
+            $type['image_vect'] = array('svg', 'svgz');
+            $type['audio'] = array('wav', 'mid', 'mp2', 'mp3', 'midi', 'sib', 'amr', 'kar', 'oga', 'au', 'wma');
+            $type['video'] = array(
+                'mp4',
+                'mov',
+                'rm',
+                'pls',
+                'mpg',
+                'mpeg',
+                'm2v',
+                'm4v',
+                'flv',
+                'f4v',
+                'avi',
+                'wmv',
+                'asf',
+                '3gp',
+                'ogv',
+                'ogg',
+                'ogx',
+                'webm'
+            );
+            $type['excel'] = array('xls', 'xlt', 'xls', 'xlt', 'pxl', 'xlsx', 'xlsm', 'xlam', 'xlsb', 'xltm', 'xltx');
+            $type['compressed'] = array('zip', 'tar', 'rar', 'gz');
+            $type['code'] = array('js', 'cpp', 'c', 'java', 'phps', 'jsp', 'asp', 'aspx', 'cfm');
+            $type['acrobat'] = array('pdf');
+            $type['powerpoint'] = array('ppt', 'pps', 'pptm', 'pptx', 'potm', 'potx', 'ppam', 'ppsm', 'ppsx');
+            $type['flash'] = array('fla', 'swf');
+            $type['text'] = array('txt', 'log');
+            $type['oo_writer'] = array('odt', 'ott', 'sxw', 'stw');
+            $type['oo_calc'] = array('ods', 'ots', 'sxc', 'stc');
+            $type['oo_impress'] = array('odp', 'otp', 'sxi', 'sti');
+            $type['oo_draw'] = array('odg', 'otg', 'sxd', 'std');
+            $type['epub'] = array('epub');
+            $type['java'] = array('class', 'jar');
+            $type['freemind'] = array('mm');
+
+            $image['word'] = 'word.gif';
+            $image['web'] = 'file_html.gif';
+            $image['image'] = 'file_image.gif';
+            $image['image_vect'] = 'file_svg.png';
+            $image['audio'] = 'file_sound.gif';
+            $image['video'] = 'film.gif';
+            $image['excel'] = 'excel.gif';
+            $image['compressed'] = 'file_zip.gif';
+            $image['code'] = 'icons/22/mime_code.png';
+            $image['acrobat'] = 'file_pdf.gif';
+            $image['powerpoint'] = 'powerpoint.gif';
+            $image['flash'] = 'file_flash.gif';
+            $image['text'] = 'icons/22/mime_text.png';
+            $image['oo_writer'] = 'file_oo_writer.gif';
+            $image['oo_calc'] = 'file_oo_calc.gif';
+            $image['oo_impress'] = 'file_oo_impress.gif';
+            $image['oo_draw'] = 'file_oo_draw.gif';
+            $image['epub'] = 'file_epub.gif';
+            $image['java'] = 'file_java.png';
+            $image['freemind'] = 'file_freemind.png';
+        }
+
+        /* FUNCTION CORE */
+        $extension = array();
+        if (!is_array($file_name)) {
+            if (preg_match('/\.([[:alnum:]]+)(\?|$)/', $file_name, $extension)) {
+                $extension[1] = strtolower($extension[1]);
+
+                foreach ($type as $generic_type => $extension_list) {
+                    if (in_array($extension[1], $extension_list)) {
+                        return $image[$generic_type];
+                    }
+                }
+            }
+        }
+
+        return 'defaut.gif';
+    }
+
+    /**
+     * Transform the file path to a URL.
+     *
+     * @param  - $file_path (string) - Relative local path of the file on the hard disk
+     * @return - Relative url
+     */
+    function format_url($file_path)
+    {
+        $path_component = explode('/', $file_path);
+        $path_component = array_map('rawurlencode', $path_component);
+
+        return implode('/', $path_component);
+    }
+
+    /**
+     * Calculates the total size of a directory by adding the sizes (that
+     * are stored in the database) of all files & folders in this directory.
+     *
+     * @param     string  $path
+     * @param     boolean $can_see_invisible
+     * @return     Total size
+     */
+    static function get_total_folder_size($path, $can_see_invisible = false)
+    {
+        $table_itemproperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        $table_document = Database::get_course_table(TABLE_DOCUMENT);
+        $tool_document = TOOL_DOCUMENT;
+
+        $course_id = api_get_course_int_id();
+        $session_id = api_get_session_id();
+        $session_condition = api_get_session_condition($session_id, true, true, 'props.id_session');
+
+        $visibility_rule = ' props.visibility '.($can_see_invisible ? '<> 2' : '= 1');
+
+        $sql = "SELECT SUM(table1.size) FROM (
+                    SELECT size FROM $table_itemproperty AS props, $table_document AS docs
+                    WHERE 	docs.c_id 	= $course_id AND
+                            docs.id 	= props.ref AND
+                            docs.path LIKE '$path/%' AND
+                            props.c_id 	= $course_id AND
+                            props.tool 	= '$tool_document' AND
+                            $visibility_rule
+                            $session_condition
+                    GROUP BY ref
+                ) as table1";
+
+        $result = Database::query($sql);
+        if ($result && Database::num_rows($result) != 0) {
+            $row = Database::fetch_row($result);
+
+            return $row[0] == null ? 0 : $row[0];
+        } else {
+            return 0;
+        }
+    }
+
+    /**
+     * Changes the file name extension from .php to .phps
+     * Useful for securing a site.
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - file_name (string) name of a file
+     *
+     * @return string the filename phps'ized
+     */
+    static function php2phps($file_name)
+    {
+        return preg_replace('/\.(php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $file_name);
+    }
+
+    /**
+     * Renames .htaccess & .HTACCESS to htaccess.txt
+     *
+     * @param string $filename
+     * @return string
+     */
+    static function htaccess2txt($filename)
+    {
+        return str_replace(array('.htaccess', '.HTACCESS'), array('htaccess.txt', 'htaccess.txt'), $filename);
+    }
+
+    /**
+     * This function executes our safety precautions
+     * more functions can be added
+     *
+     * @param string $filename
+     * @return string
+     * @see FileManager::php2phps()
+     * @see htaccess2txt()
+     */
+    static function disable_dangerous_file($filename)
+    {
+        return self::htaccess2txt(self::php2phps($filename));
+    }
+
+    /**
+     * This function generates a unique name for a file on a given location. Filenames are changed to name_#.ext
+     *
+     * @param string $path
+     * @param string $name
+     * @return new unique name
+     */
+    static function unique_name($path, $name)
+    {
+        $ext = substr(strrchr($name, '.'), 0);
+        $name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name, $ext)));
+        $n = 0;
+        $unique = '';
+        while (file_exists($path.$name_no_ext.$unique.$ext)) {
+            $unique = '_'.++$n;
+        }
+
+        return $name_no_ext.$unique.$ext;
+    }
+
+    /**
+     * Returns the name without extension, used for the title
+     *
+     * @param string $name
+     * @return name without the extension
+     */
+    static function get_document_title($name)
+    {
+        // If they upload .htaccess...
+        $name = self::disable_dangerous_file($name);
+        $ext = substr(strrchr($name, '.'), 0);
+
+        return addslashes(substr($name, 0, strlen($name) - strlen(strstr($name, $ext))));
+    }
+
+    /**
+     * This function checks if the upload succeeded
+     *
+     * @param array $uploaded_file ($_FILES)
+     * @param bool $show_output
+     *
+     * @return true if upload succeeded
+     */
+    static function process_uploaded_file($uploaded_file, $show_output = true)
+    {
+        // Checking the error code sent with the file upload.
+
+        switch ($uploaded_file['error']) {
+            case 1:
+                // The uploaded file exceeds the upload_max_filesize directive in php.ini.
+                if ($show_output) {
+                    Display::display_error_message(
+                        get_lang('UplExceedMaxServerUpload').ini_get('upload_max_filesize')
+                    );
+                }
+
+                return false;
+            case 2:
+                // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
+                // Not used at the moment, but could be handy if we want to limit the size of an upload (e.g. image upload in html editor).
+                $max_file_size = intval($_POST['MAX_FILE_SIZE']);
+                if ($show_output) {
+                    Display::display_error_message(get_lang('UplExceedMaxPostSize').format_file_size($max_file_size));
+                }
+
+                return false;
+            case 3:
+                // The uploaded file was only partially uploaded.
+                if ($show_output) {
+                    Display::display_error_message(get_lang('UplPartialUpload').' '.get_lang('PleaseTryAgain'));
+                }
+
+                return false;
+            case 4:
+                // No file was uploaded.
+                if ($show_output) {
+                    Display::display_error_message(get_lang('UplNoFileUploaded').' '.get_lang('UplSelectFileFirst'));
+                }
+
+                return false;
+        }
+
+        if (!file_exists($uploaded_file['tmp_name'])) {
+            // No file was uploaded.
+            if ($show_output) {
+                Display::display_error_message(get_lang('UplUploadFailed'));
+            }
+
+            return false;
+        }
+
+        if (file_exists($uploaded_file['tmp_name'])) {
+            $filesize = filesize($uploaded_file['tmp_name']);
+            if (empty($filesize)) {
+                // No file was uploaded.
+                if ($show_output) {
+                    Display::display_error_message(get_lang('UplUploadFailedSizeIsZero'));
+                }
+
+                return false;
+            }
+        }
+
+        $course_id = api_get_course_id();
+        //Checking course quota if we are in a course
+
+        if (!empty($course_id)) {
+            $max_filled_space = DocumentManager::get_course_quota();
+            // Check if there is enough space to save the file
+            if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
+                if ($show_output) {
+                    Display::display_error_message(get_lang('UplNotEnoughSpace'));
+                }
+
+                return false;
+            }
+        }
+
+        // case 0: default: We assume there is no error, the file uploaded with success.
+        return true;
+    }
+
+    /**
+     * This function does the save-work for the documents.
+     * It handles the uploaded file and adds the properties to the database
+     * If unzip=1 and the file is a zipfile, it is extracted
+     * If we decide to save ALL kinds of documents in one database,
+     * we could extend this with a $type='document', 'scormdocument',...
+     *
+     * @param array $_course
+     * @param array $uploaded_file ($_FILES)
+     * @param string $base_work_dir
+     * @param string $upload_path
+     * @param int $user_id
+     * @param int $to_group_id, 0 for everybody
+     * @param int $to_user_id, NULL for everybody
+     * @param int $unzip 1/0
+     * @param string $what_if_file_exists overwrite, rename or warn if exists (default)
+     * @param boolean Optional output parameter. So far only use for unzip_uploaded_document function. If no output wanted on success, set to false.
+     * @return path of the saved file
+     */
+    static function handle_uploaded_document(
+        $_course,
+        $uploaded_file,
+        $base_work_dir,
+        $upload_path,
+        $user_id,
+        $to_group_id = 0,
+        $to_user_id = null,
+        $unzip = 0,
+        $what_if_file_exists = '',
+        $output = true
+    ) {
+        if (!$user_id) {
+            die('Not a valid user.');
+        }
+        // Strip slashes
+        $uploaded_file['name'] = stripslashes($uploaded_file['name']);
+        // Add extension to files without one (if possible)
+        $uploaded_file['name'] = self::add_ext_on_mime($uploaded_file['name'], $uploaded_file['type']);
+        $current_session_id = api_get_session_id();
+
+        //Just in case process_uploaded_file is not called
+        $max_filled_space = DocumentManager::get_course_quota();
+
+        // Check if there is enough space to save the file
+        if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
+            if ($output) {
+                Display::display_error_message(get_lang('UplNotEnoughSpace'));
+            }
+
+            return false;
+        }
+
+        // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
+        if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
+            return self::unzip_uploaded_document(
+                $uploaded_file,
+                $upload_path,
+                $base_work_dir,
+                $max_filled_space,
+                $output,
+                $to_group_id
+            );
+            //display_message('Unzipping file');
+        } elseif ($unzip == 1 && !preg_match(
+            '/.zip$/',
+            strtolower($uploaded_file['name'])
+        )
+        ) { // We can only unzip ZIP files (no gz, tar,...)
+            if ($output) {
+                Display::display_error_message(get_lang('UplNotAZip')." ".get_lang('PleaseTryAgain'));
+            }
+
+            return false;
+        } else {
+            // Clean up the name, only ASCII characters should stay. (and strict)
+            $clean_name = replace_dangerous_char($uploaded_file['name'], 'strict');
+
+            // No "dangerous" files
+            $clean_name = self::disable_dangerous_file($clean_name);
+
+            if (!self::filter_extension($clean_name)) {
+                if ($output) {
+                    Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
+                }
+
+                return false;
+            } else {
+                // Extension is good
+                //echo '<br />clean name = '.$clean_name;
+                //echo '<br />upload_path = '.$upload_path;
+                // If the upload path differs from / (= root) it will need a slash at the end
+                if ($upload_path != '/') {
+                    $upload_path = $upload_path.'/';
+                }
+                //echo '<br />upload_path = '.$upload_path;
+                $file_path = $upload_path.$clean_name;
+                //echo '<br />file path = '.$file_path;
+                // Full path to where we want to store the file with trailing slash
+                $where_to_save = $base_work_dir.$upload_path;
+                // At least if the directory doesn't exist, tell so
+                if (!is_dir($where_to_save)) {
+                    if ($output) {
+                        Display::display_error_message(get_lang('DestDirectoryDoesntExist').' ('.$upload_path.')');
+                    }
+
+                    return false;
+                }
+                //echo '<br />where to save = '.$where_to_save;
+                // Full path of the destination
+                $store_path = $where_to_save.$clean_name;
+                //echo '<br />store path = '.$store_path;
+                // Name of the document without the extension (for the title)
+                $document_name = self::get_document_title($uploaded_file['name']);
+                // Size of the uploaded file (in bytes)
+                $file_size = $uploaded_file['size'];
+
+                $files_perm = api_get_permissions_for_new_files();
+
+                // What to do if the target file exists
+                switch ($what_if_file_exists) {
+                    // Overwrite the file if it exists
+                    case 'overwrite':
+                        // Check if the target file exists, so we can give another message
+                        $file_exists = file_exists($store_path);
+                        if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
+                            chmod($store_path, $files_perm);
+                            if ($file_exists) {
+                                // UPDATE DATABASE
+                                $document_id = DocumentManager::get_document_id($_course, $file_path);
+
+                                if (is_numeric($document_id)) {
+                                    // Update filesize
+                                    self::update_existing_document($_course, $document_id, $uploaded_file['size']);
+
+                                    // Update document item_property
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $document_id,
+                                        'DocumentUpdated',
+                                        $user_id,
+                                        $to_group_id,
+                                        $to_user_id,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    );
+
+                                    //Redo visibility
+                                    api_set_default_visibility(TOOL_DOCUMENT, $document_id);
+                                }
+                                // If the file is in a folder, we need to update all parent folders
+                                self::item_property_update_on_folder($_course, $upload_path, $user_id);
+                                // Display success message with extra info to user
+                                if ($output) {
+                                    Display::display_confirmation_message(
+                                        get_lang('UplUploadSucceeded').'<br />'.$file_path.' '.get_lang(
+                                            'UplFileOverwritten'
+                                        ),
+                                        false
+                                    );
+                                }
+
+                                return $file_path;
+                            } else {
+                                // Put the document data in the database
+                                $document_id = self::add_document(
+                                    $_course,
+                                    $file_path,
+                                    'file',
+                                    $file_size,
+                                    $document_name,
+                                    null,
+                                    0,
+                                    true
+                                );
+                                if ($document_id) {
+                                    // Put the document in item_property update
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $document_id,
+                                        'DocumentAdded',
+                                        $user_id,
+                                        $to_group_id,
+                                        $to_user_id,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    );
+                                }
+                                // If the file is in a folder, we need to update all parent folders
+                                self::item_property_update_on_folder($_course, $upload_path, $user_id);
+                                // Display success message to user
+                                if ($output) {
+                                    Display::display_confirmation_message(
+                                        get_lang('UplUploadSucceeded').'<br />'.$file_path,
+                                        false
+                                    );
+                                }
+
+                                return $file_path;
+                            }
+                        } else {
+                            if ($output) {
+                                Display::display_error_message(get_lang('UplUnableToSaveFile'));
+                            }
+
+                            return false;
+                        }
+                        break;
+
+                    // Rename the file if it exists
+                    case 'rename':
+                        $new_name = unique_name($where_to_save, $clean_name);
+                        $store_path = $where_to_save.$new_name;
+                        $new_file_path = $upload_path.$new_name;
+
+                        if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
+
+                            chmod($store_path, $files_perm);
+
+                            // Put the document data in the database
+                            $document_id = self::add_document(
+                                $_course,
+                                $new_file_path,
+                                'file',
+                                $file_size,
+                                $document_name,
+                                null,
+                                0,
+                                true
+                            );
+                            if ($document_id) {
+                                // Update document item_property
+                                api_item_property_update(
+                                    $_course,
+                                    TOOL_DOCUMENT,
+                                    $document_id,
+                                    'DocumentAdded',
+                                    $user_id,
+                                    $to_group_id,
+                                    $to_user_id,
+                                    null,
+                                    null,
+                                    $current_session_id
+                                );
+                            }
+                            // If the file is in a folder, we need to update all parent folders
+                            self::item_property_update_on_folder($_course, $upload_path, $user_id);
+
+                            // Display success message to user
+                            if ($output) {
+                                Display::display_confirmation_message(
+                                    get_lang('UplUploadSucceeded').'<br />'.get_lang('UplFileSavedAs').$new_file_path,
+                                    false
+                                );
+                            }
+
+                            return $new_file_path;
+                        } else {
+                            if ($output) {
+                                Display::display_error_message(get_lang('UplUnableToSaveFile'));
+                            }
+
+                            return false;
+                        }
+                        break;
+
+                    // Only save the file if it doesn't exist or warn user if it does exist
+                    default:
+                        if (file_exists($store_path)) {
+                            if ($output) {
+                                Display::display_error_message($clean_name.' '.get_lang('UplAlreadyExists'));
+                            }
+                        } else {
+                            if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
+                                chmod($store_path, $files_perm);
+
+                                // Put the document data in the database
+                                $document_id = self::add_document(
+                                    $_course,
+                                    $file_path,
+                                    'file',
+                                    $file_size,
+                                    $document_name,
+                                    null,
+                                    0,
+                                    true
+                                );
+
+                                if ($document_id) {
+                                    // Update document item_property
+                                    api_item_property_update(
+                                        $_course,
+                                        TOOL_DOCUMENT,
+                                        $document_id,
+                                        'DocumentAdded',
+                                        $user_id,
+                                        $to_group_id,
+                                        $to_user_id,
+                                        null,
+                                        null,
+                                        $current_session_id
+                                    );
+                                }
+                                // If the file is in a folder, we need to update all parent folders
+                                self::item_property_update_on_folder($_course, $upload_path, $user_id);
+
+                                // Display success message to user
+                                if ($output) {
+                                    Display::display_confirmation_message(
+                                        get_lang('UplUploadSucceeded').'<br />'.$file_path,
+                                        false
+                                    );
+                                }
+
+                                return $file_path;
+                            } else {
+                                if ($output) {
+                                    Display::display_error_message(get_lang('UplUnableToSaveFile'));
+                                }
+
+                                return false;
+                            }
+                        }
+                        break;
+                }
+            }
+        }
+    }
+
+    /**
+     * Checks if there is enough place to add a file on a directory
+     * on the base of a maximum directory size allowed
+     * deprecated: use enough_space instead!
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - file_size (int) - size of the file in byte
+     * @param  - dir (string) - Path of the directory
+     *           whe the file should be added
+     * @param  - max_dir_space (int) - maximum size of the diretory in byte
+     * @return - boolean true if there is enough space,
+     *                boolean false otherwise
+     *
+     * @see    - enough_size() uses  dir_total_space() function
+     */
+    static function enough_size($file_size, $dir, $max_dir_space)
+    {
+        if ($max_dir_space) {
+            $already_filled_space = self::dir_total_space($dir);
+            if (($file_size + $already_filled_space) > $max_dir_space) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+
+    /**
+     * Computes the size already occupied by a directory and is subdirectories
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @param  - dir_path (string) - size of the file in byte
+     * @return - int - return the directory size in bytes
+     */
+    static function dir_total_space($dir_path)
+    {
+
+        $save_dir = getcwd();
+        chdir($dir_path);
+        $handle = opendir($dir_path);
+
+        while ($element = readdir($handle)) {
+            if ($element == '.' || $element == '..') {
+                continue; // Skip the current and parent directories
+            }
+            if (is_file($element)) {
+                $sumSize += filesize($element);
+            }
+            if (is_dir($element)) {
+                $dirList[] = $dir_path.'/'.$element;
+            }
+        }
+
+        closedir($handle);
+
+        if (sizeof($dirList) > 0) {
+            foreach ($dirList as $j) {
+                $sizeDir = self::dir_total_space($j); // Recursivity
+                $sumSize += $sizeDir;
+            }
+        }
+        chdir($save_dir); // Return to initial position
+        return $sumSize;
+    }
+
+
+    /**
+     * Tries to add an extension to files without extension
+     * Some applications on Macintosh computers don't add an extension to the files.
+     * This subroutine try to fix this on the basis of the MIME type sent
+     * by the browser.
+     *
+     * Note : some browsers don't send the MIME Type (e.g. Netscape 4).
+     *        We don't have solution for this kind of situation
+     *
+     * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
+     * @author - Bert Vanderkimpen
+     * @param  - file_name (string) - Name of the file
+     * @param  - file_type (string) - Type of the file
+     * @return - file_name (string)
+     */
+    static function add_ext_on_mime($file_name, $file_type)
+    {
+
+        // Check whether the file has an extension AND whether the browser has sent a MIME Type
+
+        if (!preg_match('/^.*\.[a-zA-Z_0-9]+$/', $file_name) && $file_type) {
+
+            // Build a "MIME-types / extensions" connection table
+
+            static $mime_type = array();
+
+            $mime_type[] = 'application/msword';
+            $extension[] = '.doc';
+            $mime_type[] = 'application/rtf';
+            $extension[] = '.rtf';
+            $mime_type[] = 'application/vnd.ms-powerpoint';
+            $extension[] = '.ppt';
+            $mime_type[] = 'application/vnd.ms-excel';
+            $extension[] = '.xls';
+            $mime_type[] = 'application/pdf';
+            $extension[] = '.pdf';
+            $mime_type[] = 'application/postscript';
+            $extension[] = '.ps';
+            $mime_type[] = 'application/mac-binhex40';
+            $extension[] = '.hqx';
+            $mime_type[] = 'application/x-gzip';
+            $extension[] = 'tar.gz';
+            $mime_type[] = 'application/x-shockwave-flash';
+            $extension[] = '.swf';
+            $mime_type[] = 'application/x-stuffit';
+            $extension[] = '.sit';
+            $mime_type[] = 'application/x-tar';
+            $extension[] = '.tar';
+            $mime_type[] = 'application/zip';
+            $extension[] = '.zip';
+            $mime_type[] = 'application/x-tar';
+            $extension[] = '.tar';
+            $mime_type[] = 'text/html';
+            $extension[] = '.html';
+            $mime_type[] = 'text/plain';
+            $extension[] = '.txt';
+            $mime_type[] = 'text/rtf';
+            $extension[] = '.rtf';
+            $mime_type[] = 'img/gif';
+            $extension[] = '.gif';
+            $mime_type[] = 'img/jpeg';
+            $extension[] = '.jpg';
+            $mime_type[] = 'img/png';
+            $extension[] = '.png';
+            $mime_type[] = 'audio/midi';
+            $extension[] = '.mid';
+            $mime_type[] = 'audio/mpeg';
+            $extension[] = '.mp3';
+            $mime_type[] = 'audio/x-aiff';
+            $extension[] = '.aif';
+            $mime_type[] = 'audio/x-pn-realaudio';
+            $extension[] = '.rm';
+            $mime_type[] = 'audio/x-pn-realaudio-plugin';
+            $extension[] = '.rpm';
+            $mime_type[] = 'audio/x-wav';
+            $extension[] = '.wav';
+            $mime_type[] = 'video/mpeg';
+            $extension[] = '.mpg';
+            $mime_type[] = 'video/mpeg4-generic';
+            $extension[] = '.mp4';
+            $mime_type[] = 'video/quicktime';
+            $extension[] = '.mov';
+            $mime_type[] = 'video/x-msvideo';
+            $extension[] = '.avi';
+            $mime_type[] = 'video/x-ms-wmv';
+            $extension[] = '.wmv';
+            $mime_type[] = 'video/x-flv';
+            $extension[] = '.flv';
+            $mime_type[] = 'image/svg+xml';
+            $extension[] = '.svg';
+            $mime_type[] = 'image/svg+xml';
+            $extension[] = '.svgz';
+            $mime_type[] = 'video/ogg';
+            $extension[] = '.ogv';
+            $mime_type[] = 'audio/ogg';
+            $extension[] = '.oga';
+            $mime_type[] = 'application/ogg';
+            $extension[] = '.ogg';
+            $mime_type[] = 'application/ogg';
+            $extension[] = '.ogx';
+            $mime_type[] = 'application/x-freemind';
+            $extension[] = '.mm';
+            $mime_type[] = 'application/vnd.ms-word.document.macroEnabled.12';
+            $extension[] = '.docm';
+            $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
+            $extension[] = '.docx';
+            $mime_type[] = 'application/vnd.ms-word.template.macroEnabled.12';
+            $extension[] = '.dotm';
+            $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
+            $extension[] = '.dotx';
+            $mime_type[] = 'application/vnd.ms-powerpoint.template.macroEnabled.12';
+            $extension[] = '.potm';
+            $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.template';
+            $extension[] = '.potx';
+            $mime_type[] = 'application/vnd.ms-powerpoint.addin.macroEnabled.12';
+            $extension[] = '.ppam';
+            $mime_type[] = 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12';
+            $extension[] = '.ppsm';
+            $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
+            $extension[] = '.ppsx';
+            $mime_type[] = 'application/vnd.ms-powerpoint.presentation.macroEnabled.12';
+            $extension[] = '.pptm';
+            $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
+            $extension[] = '.pptx';
+            $mime_type[] = 'application/vnd.ms-excel.addin.macroEnabled.12';
+            $extension[] = '.xlam';
+            $mime_type[] = 'application/vnd.ms-excel.sheet.binary.macroEnabled.12';
+            $extension[] = '.xlsb';
+            $mime_type[] = 'application/vnd.ms-excel.sheet.macroEnabled.12';
+            $extension[] = '.xlsm';
+            $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
+            $extension[] = '.xlsx';
+            $mime_type[] = 'application/vnd.ms-excel.template.macroEnabled.12';
+            $extension[] = '.xltm';
+            $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.template';
+            $extension[] = '.xltx';
+
+            // Test on PC (files with no extension get application/octet-stream)
+            //$mime_type[] = 'application/octet-stream';      $extension[] = '.ext';
+
+            // Check whether the MIME type sent by the browser is within the table
+
+            foreach ($mime_type as $key => & $type) {
+                if ($type == $file_type) {
+                    $file_name .= $extension[$key];
+                    break;
+                }
+            }
+
+            unset($mime_type, $extension, $type, $key); // Delete to eschew possible collisions
+        }
+
+        return $file_name;
+    }
+
+
+    /**
+     * Manages all the unzipping process of an uploaded document
+     * This uses the item_property table for properties of documents
+     *
+     * @author Hugues Peeters <hugues.peeters@claroline.net>
+     * @author Bert Vanderkimpen
+     *
+     * @param  array  $uploaded_file - follows the $_FILES Structure
+     * @param  string $upload_path   - destination of the upload.
+     *                                This path is to append to $base_work_dir
+     * @param  string $base_work_dir  - base working directory of the module
+     * @param  int $max_filled_space  - amount of bytes to not exceed in the base
+     *                                working directory
+     * @param        boolean    Output switch. Optional. If no output not wanted on success, set to false.
+     *
+     * @return boolean true if it succeeds false otherwise
+     */
+    static function unzip_uploaded_document(
+        $uploaded_file,
+        $upload_path,
+        $base_work_dir,
+        $max_filled_space,
+        $output = true,
+        $to_group_id = 0
+    ) {
+        global $_course;
+        global $_user;
+        global $to_user_id;
+        global $to_group_id;
+
+        $zip_file = new PclZip($uploaded_file['tmp_name']);
+
+        // Check the zip content (real size and file extension)
+
+        $zip_content_array = (array)$zip_file->listContent();
+        $real_filesize = 0;
+        foreach ($zip_content_array as & $this_content) {
+            $real_filesize += $this_content['size'];
+        }
+
+        if (!DocumentManager::enough_space($real_filesize, $max_filled_space)) {
+            Display::display_error_message(get_lang('UplNotEnoughSpace'));
+
+            return false;
+        }
+
+        // It happens on Linux that $upload_path sometimes doesn't start with '/'
+        if ($upload_path[0] != '/') {
+            $upload_path = '/'.$upload_path;
+        }
+
+        /*	Uncompressing phase */
+
+        // Get into the right directory
+        $save_dir = getcwd();
+        chdir($base_work_dir.$upload_path);
+        // We extract using a callback function that "cleans" the path
+        //@todo check if this works
+        $unzipping_state = $zip_file->extract(
+            PCLZIP_CB_PRE_EXTRACT,
+            'FileManager::clean_up_files_in_zip',
+            PCLZIP_OPT_REPLACE_NEWER
+        );
+        // Add all documents in the unzipped folder to the database
+        self::add_all_documents_in_folder_to_database(
+            $_course,
+            $_user['user_id'],
+            $base_work_dir,
+            $upload_path == '/' ? '' : $upload_path,
+            $to_group_id
+        );
+
+        //Display::display_normal_message(get_lang('UplZipExtractSuccess'));
+        return true;
+    }
+
+    /**
+     * This function is a callback function that is used while extracting a zipfile
+     * http://www.phpconcept.net/pclzip/man/en/index.php?options-pclzip_cb_pre_extract
+     *
+     * @param $p_event
+     * @param $p_header
+     * @return 1 (If the function returns 1, then the extraction is resumed)
+     */
+    function clean_up_files_in_zip($p_event, &$p_header)
+    {
+        $res = self::clean_up_path($p_header['filename']);
+
+        return $res;
+    }
+
+    /**
+     * This function cleans up a given path
+     * by eliminating dangerous file names and cleaning them
+     *
+     * @param string $path
+     * @return $path
+     * @see FileManager::disable_dangerous_file()
+     * @see replace_dangerous_char()
+     */
+    static function clean_up_path(&$path)
+    {
+        // Split the path in folders and files
+        $path_array = explode('/', $path);
+        // Clean up every foler and filename in the path
+        foreach ($path_array as $key => & $val) {
+            // We don't want to lose the dots in ././folder/file (cfr. zipfile)
+            if ($val != '.') {
+                $val = self::disable_dangerous_file(replace_dangerous_char($val));
+            }
+        }
+        // Join the "cleaned" path (modified in-place as passed by reference)
+        $path = implode('/', $path_array);
+        $res = self::filter_extension($path);
+
+        return $res;
+    }
+
+    /**
+     * Checks if the file is dangerous, based on extension and/or mimetype.
+     * The list of extensions accepted/rejected can be found from
+     * api_get_setting('upload_extensions_exclude') and api_get_setting('upload_extensions_include')
+     * @param    string     filename passed by reference. The filename will be modified if filter rules say so! (you can include path but the filename should look like 'abc.html')
+     * @return    int        0 to skip file, 1 to keep file
+     */
+    static function filter_extension(&$filename)
+    {
+
+        if (substr($filename, -1) == '/') {
+            return 1; // Authorize directories
+        }
+        $blacklist = api_get_setting('upload_extensions_list_type');
+        if ($blacklist != 'whitelist') { // if = blacklist
+            $extensions = explode(';', strtolower(api_get_setting('upload_extensions_blacklist')));
+
+            $skip = api_get_setting('upload_extensions_skip');
+            $ext = strrchr($filename, '.');
+            $ext = substr($ext, 1);
+            if (empty($ext)) {
+                return 1; // We're in blacklist mode, so accept empty extensions
+            }
+            if (in_array(strtolower($ext), $extensions)) {
+                if ($skip == 'true') {
+                    return 0;
+                } else {
+                    $new_ext = api_get_setting('upload_extensions_replace_by');
+                    $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
+
+                    return 1;
+                }
+            } else {
+                return 1;
+            }
+        } else {
+            $extensions = split(';', strtolower(api_get_setting('upload_extensions_whitelist')));
+            $skip = api_get_setting('upload_extensions_skip');
+            $ext = strrchr($filename, '.');
+            $ext = substr($ext, 1);
+            if (empty($ext)) {
+                return 1; // Accept empty extensions
+            }
+            if (!in_array(strtolower($ext), $extensions)) {
+                if ($skip == 'true') {
+                    return 0;
+                } else {
+                    $new_ext = api_get_setting('upload_extensions_replace_by');
+                    $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
+
+                    return 1;
+                }
+            } else {
+                return 1;
+            }
+        }
+    }
+
+    /**
+     * Adds a new document to the database
+     *
+     * @param array $_course
+     * @param string $path
+     * @param string $filetype
+     * @param int $filesize
+     * @param string $title
+     *
+     * @return id if inserted document
+     */
+    static function add_document(
+        $_course,
+        $path,
+        $filetype,
+        $filesize,
+        $title,
+        $comment = null,
+        $readonly = 0,
+        $save_visibility = true,
+        $group_id = null
+    ) {
+        $session_id = api_get_session_id();
+        $readonly = intval($readonly);
+        $comment = Database::escape_string($comment);
+        $path = Database::escape_string($path);
+        $filetype = Database::escape_string($filetype);
+        $filesize = intval($filesize);
+        $title = Database::escape_string(htmlspecialchars($title));
+        $c_id = $_course['real_id'];
+
+        $table_document = Database::get_course_table(TABLE_DOCUMENT);
+        $sql = "INSERT INTO $table_document (c_id, path, filetype, size, title, comment, readonly, session_id)
+	        VALUES ($c_id, '$path','$filetype','$filesize','$title', '$comment', $readonly, $session_id)";
+
+        if (Database::query($sql)) {
+            $document_id = Database::insert_id();
+            if ($document_id) {
+                if ($save_visibility) {
+                    api_set_default_visibility($document_id, TOOL_DOCUMENT, $group_id);
+                }
+            }
+
+            return $document_id;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Updates an existing document in the database
+     * as the file exists, we only need to change the size
+     *
+     * @param array $_course
+     * @param int $document_id
+     * @param int $filesize
+     * @param int $readonly
+     *
+     * @return boolean true /false
+     */
+    static function update_existing_document($_course, $document_id, $filesize, $readonly = 0)
+    {
+        $document_table = Database::get_course_table(TABLE_DOCUMENT);
+        $document_id = intval($document_id);
+
+        $filesize = intval($filesize);
+        $readonly = intval($readonly);
+        $course_id = $_course['real_id'];
+
+        $sql = "UPDATE $document_table SET size = '$filesize' , readonly = '$readonly'
+			WHERE c_id = $course_id AND id = $document_id";
+        if (Database::query($sql)) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * This function updates the last_edit_date, last edit user id on all folders in a given path
+     *
+     * @param array $_course
+     * @param string $path
+     * @param int $user_id
+     */
+    static function item_property_update_on_folder($_course, $path, $user_id)
+    {
+        //display_message("Start update_lastedit_on_folder");
+        // If we are in the root, just return... no need to update anything
+        if ($path == '/') {
+            return;
+        }
+
+        $user_id = intval($user_id);
+
+        // If the given path ends with a / we remove it
+        $endchar = substr($path, strlen($path) - 1, 1);
+        if ($endchar == '/') {
+            $path = substr($path, 0, strlen($path) - 1);
+        }
+
+        $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+        // Get the time
+        $time = date('Y-m-d H:i:s', time());
+
+        // Det all paths in the given path
+        // /folder/subfolder/subsubfolder/file
+        // if file is updated, subsubfolder, subfolder and folder are updated
+
+        $exploded_path = explode('/', $path);
+        $course_id = api_get_course_int_id();
+        foreach ($exploded_path as $key => & $value) {
+            // We don't want a slash before our first slash
+            if ($key != 0) {
+                $newpath .= '/'.$value;
+
+                //echo 'path= '.$newpath.'<br />';
+                // Select ID of given folder
+                $folder_id = DocumentManager::get_document_id($_course, $newpath);
+
+                if ($folder_id) {
+                    $sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time',lastedit_type='DocumentInFolderUpdated', lastedit_user_id='$user_id'
+						WHERE c_id = $course_id AND tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
+                    Database::query($sql);
+                }
+            }
+        }
+    }
+
+    /**
+     * Returns the directory depth of the file.
+     *
+     * @author    Olivier Cauberghe <olivier.cauberghe@ugent.be>
+     * @param    path+filename eg: /main/document/document.php
+     * @return    The directory depth
+     */
+    static function get_levels($filename)
+    {
+        $levels = explode('/', $filename);
+        if (empty($levels[count($levels) - 1])) {
+            unset($levels[count($levels) - 1]);
+        }
+
+        return count($levels);
+    }
+
+    /**
+     * Retrieves the image path list in a html file
+     *
+     * @author Hugues Peeters <hugues.peeters@claroline.net>
+     * @param  string $html_file
+     * @return array -  images path list
+     */
+    static function search_img_from_html($html_file)
+    {
+
+        $img_path_list = array();
+
+        if (!$fp = fopen($html_file, 'r')) {
+            return;
+        }
+
+        // Aearch and store occurences of the <img> tag in an array
+        $size_file = (filesize($html_file) === 0) ? 1 : filesize($html_file);
+        if (isset($fp) && $fp !== false) {
+            $buffer = fread($fp, $size_file);
+            if (strlen($buffer) >= 0 && $buffer !== false) {
+                //
+            } else {
+                die('<center>Can not read file.</center>');
+            }
+        } else {
+            die('<center>Can not read file.</center>');
+        }
+        $matches = array();
+        if (preg_match_all('~<[[:space:]]*img[^>]*>~i', $buffer, $matches)) {
+            $img_tag_list = $matches[0];
+        }
+
+        fclose($fp);
+        unset($buffer);
+
+        // Search the image file path from all the <IMG> tag detected
+
+        if (sizeof($img_tag_list) > 0) {
+            foreach ($img_tag_list as & $this_img_tag) {
+                if (preg_match('~src[[:space:]]*=[[:space:]]*[\"]{1}([^\"]+)[\"]{1}~i', $this_img_tag, $matches)) {
+                    $img_path_list[] = $matches[1];
+                }
+            }
+            $img_path_list = array_unique($img_path_list); // Remove duplicate entries
+        }
+
+        return $img_path_list;
+    }
+
+    /**
+     * Creates a new directory trying to find a directory name
+     * that doesn't already exist
+     * (we could use unique_name() here...)
+     *
+     * @author  Hugues Peeters <hugues.peeters@claroline.net>
+     * @author  Bert Vanderkimpen
+     * @param   array   $_course current course information
+     * @param   int     $user_id current user id
+     * @param   string  $desiredDirName complete path of the desired name
+     * @param   string  The visible name of the directory
+     * @param   int     Visibility (0 for invisible, 1 for visible, 2 for deleted)
+     * @return  string  actual directory name if it succeeds,
+     *          boolean false otherwise
+     */
+    static function create_unexisting_directory(
+        $_course,
+        $user_id,
+        $session_id,
+        $to_group_id,
+        $to_user_id,
+        $base_work_dir,
+        $desired_dir_name,
+        $title = null,
+        $visibility = ''
+    ) {
+        $nb = '';
+        // add numerical suffix to directory if another one of the same number already exists
+        while (file_exists($base_work_dir.$desired_dir_name.$nb)) {
+            $nb += 1;
+        }
+
+        if ($title == null) {
+            $title = basename($desired_dir_name);
+        }
+        $course_id = $_course['real_id'];
+
+        if (mkdir($base_work_dir.$desired_dir_name.$nb, api_get_permissions_for_new_directories(), true)) {
+            // Check if pathname already exists inside document table
+            $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
+            $sql = "SELECT path FROM $tbl_document WHERE c_id = $course_id AND path='".$desired_dir_name.$nb."'";
+
+            $rs = Database::query($sql);
+            if (Database::num_rows($rs) == 0) {
+                $document_id = self::add_document(
+                    $_course,
+                    $desired_dir_name.$nb,
+                    'folder',
+                    0,
+                    $title,
+                    null,
+                    0,
+                    true,
+                    $to_group_id
+                );
+                if ($document_id) {
+                    // Update document item_property
+                    if ($visibility !== '') {
+                        $visibilities = array(0 => 'invisible', 1 => 'visible', 2 => 'delete');
+                        api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $document_id,
+                            $visibilities[$visibility],
+                            $user_id,
+                            $to_group_id,
+                            $to_user_id,
+                            null,
+                            null,
+                            $session_id
+                        );
+                    } else {
+                        api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $document_id,
+                            'FolderCreated',
+                            $user_id,
+                            $to_group_id,
+                            $to_user_id,
+                            null,
+                            null,
+                            $session_id
+                        );
+                    }
+
+                    return $desired_dir_name.$nb;
+                }
+            } else {
+                //This means the folder NOT exist in the filesystem (now this was created) but there is a record in the Database
+                return $desired_dir_name.$nb;
+            }
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Handles uploaded missing images
+     *
+     * @author Hugues Peeters <hugues.peeters@claroline.net>
+     * @author Bert Vanderkimpen
+     * @param array $_course
+     * @param array $uploaded_file_collection - follows the $_FILES Structure
+     * @param string $base_work_dir
+     * @param string $missing_files_dir
+     * @param int $user_id
+     * @param int $max_filled_space
+     */
+    static function move_uploaded_file_collection_into_directory(
+        $_course,
+        $uploaded_file_collection,
+        $base_work_dir,
+        $missing_files_dir,
+        $user_id,
+        $to_group_id,
+        $to_user_id,
+        $max_filled_space
+    ) {
+        $number_of_uploaded_images = count($uploaded_file_collection['name']);
+        for ($i = 0; $i < $number_of_uploaded_images; $i++) {
+            $missing_file['name'] = $uploaded_file_collection['name'][$i];
+            $missing_file['type'] = $uploaded_file_collection['type'][$i];
+            $missing_file['tmp_name'] = $uploaded_file_collection['tmp_name'][$i];
+            $missing_file['error'] = $uploaded_file_collection['error'][$i];
+            $missing_file['size'] = $uploaded_file_collection['size'][$i];
+
+            $upload_ok = self::process_uploaded_file($missing_file);
+            if ($upload_ok) {
+                $new_file_list[] = self::handle_uploaded_document(
+                    $_course,
+                    $missing_file,
+                    $base_work_dir,
+                    $missing_files_dir,
+                    $user_id,
+                    $to_group_id,
+                    $to_user_id,
+                    $max_filled_space,
+                    0,
+                    'overwrite'
+                );
+            }
+            unset($missing_file);
+        }
+
+        return $new_file_list;
+    }
+
+    /**
+     * Opens the old html file and replace the src path into the img tag
+     * This also works for files in subdirectories.
+     * @param $original_img_path is an array
+     * @param $new_img_path is an array
+     */
+    static function replace_img_path_in_html_file($original_img_path, $new_img_path, $html_file)
+    {
+        global $_course;
+
+        // Open the file
+
+        $fp = fopen($html_file, 'r');
+        $buffer = fread($fp, filesize($html_file));
+
+
+        // Fix the image tags
+
+        for ($i = 0, $fileNb = count($original_img_path); $i < $fileNb; $i++) {
+            $replace_what = $original_img_path[$i];
+            // We only need the directory and the filename /path/to/file_html_files/missing_file.gif -> file_html_files/missing_file.gif
+            $exploded_file_path = explode('/', $new_img_path[$i]);
+            $replace_by = $exploded_file_path[count($exploded_file_path) - 2].'/'.$exploded_file_path[count(
+                $exploded_file_path
+            ) - 1];
+            $buffer = str_replace($replace_what, $replace_by, $buffer);
+        }
+
+        $new_html_content .= $buffer;
+
+        @fclose($fp);
+
+        // Write the resulted new file
+
+        if (!$fp = fopen($html_file, 'w')) {
+            return;
+        }
+
+        if (!fwrite($fp, $new_html_content)) {
+            return;
+        }
+    }
+
+    /**
+     * Checks the extension of a file, if it's .htm or .html
+     * we use search_img_from_html to get all image paths in the file
+     *
+     * @param string $file
+     * @return array paths
+     * @see check_for_missing_files() uses search_img_from_html()
+     */
+    static function check_for_missing_files($file)
+    {
+        if (strrchr($file, '.') == '.htm' || strrchr($file, '.') == '.html') {
+            $img_file_path = self::search_img_from_html($file);
+
+            return $img_file_path;
+        }
+
+        return false;
+    }
+
+    /**
+     * This function builds a form that asks for the missing images in a html file
+     * maybe we should do this another way?
+     *
+     * @param array $missing_files
+     * @param string $upload_path
+     * @param string $file_name
+     * @return string the form
+     */
+    static function build_missing_files_form($missing_files, $upload_path, $file_name)
+    {
+        // Do we need a / or not?
+        $added_slash = ($upload_path == '/') ? '' : '/';
+        $folder_id = DocumentManager::get_document_id(api_get_course_info(), $upload_path);
+        // Build the form
+        $form = "<p><strong>".get_lang('MissingImagesDetected')."</strong></p>"
+            ."<form method=\"post\" action=\"".api_get_self()."\" enctype=\"multipart/form-data\">"
+            // Related_file is the path to the file that has missing images
+            ."<input type=\"hidden\" name=\"related_file\" value=\"".$upload_path.$added_slash.$file_name."\" />"
+            ."<input type=\"hidden\" name=\"upload_path\" value=\"".$upload_path."\" />"
+            ."<input type=\"hidden\" name=\"id\" value=\"".$folder_id."\" />"
+            ."<table border=\"0\">";
+        foreach ($missing_files as & $this_img_file_path) {
+            $form .= "<tr>"
+                ."<td>".basename($this_img_file_path)." : </td>"
+                ."<td>"
+                ."<input type=\"file\" name=\"img_file[]\"/>"
+                ."<input type=\"hidden\" name=\"img_file_path[]\" value=\"".$this_img_file_path."\" />"
+                ."</td>"
+                ."</tr>";
+        }
+        $form .= "</table>"
+            ."<button type='submit' name=\"cancel_submit_image\" value=\"".get_lang(
+            'Cancel'
+        )."\" class=\"cancel\">".get_lang('Cancel')."</button>"
+            ."<button type='submit' name=\"submit_image\" value=\"".get_lang('Ok')."\" class=\"save\">".get_lang(
+            'Ok'
+        )."</button>"
+            ."</form>";
+
+        return $form;
+    }
+
+    /**
+     * This recursive function can be used during the upgrade process form older versions of Chamilo
+     * It crawls the given directory, checks if the file is in the DB and adds it if it's not
+     *
+     * @param string $base_work_dir
+     * @param string $current_path, needed for recursivity
+     */
+    static function add_all_documents_in_folder_to_database(
+        $_course,
+        $user_id,
+        $base_work_dir,
+        $current_path = '',
+        $to_group_id = 0
+    ) {
+        $current_session_id = api_get_session_id();
+        $path = $base_work_dir.$current_path;
+        // Open dir
+        $handle = opendir($path);
+        if (is_dir($path)) {
+            // Run trough
+            while ($file = readdir($handle)) {
+                if ($file == '.' || $file == '..') {
+                    continue;
+                }
+
+                $completepath = "$path/$file";
+                // Directory?
+                if (is_dir($completepath)) {
+                    $title = self::get_document_title($file);
+                    $safe_file = replace_dangerous_char($file);
+                    @rename($path.'/'.$file, $path.'/'.$safe_file);
+                    // If we can't find the file, add it
+                    if (!DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file)) {
+                        $document_id = self::add_document($_course, $current_path.'/'.$safe_file, 'folder', 0, $title);
+                        api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $document_id,
+                            'DocumentAdded',
+                            $user_id,
+                            $to_group_id,
+                            null,
+                            null,
+                            null,
+                            $current_session_id
+                        );
+                        //echo $current_path.'/'.$safe_file.' added!<br />';
+                    }
+                    // Recursive
+                    self::add_all_documents_in_folder_to_database(
+                        $_course,
+                        $user_id,
+                        $base_work_dir,
+                        $current_path.'/'.$safe_file,
+                        $to_group_id
+                    );
+                } else {
+                    //Rename
+                    $safe_file = self::disable_dangerous_file(replace_dangerous_char($file, 'strict'));
+                    @rename($base_work_dir.$current_path.'/'.$file, $base_work_dir.$current_path.'/'.$safe_file);
+                    $document_id = DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file);
+                    if (!$document_id) {
+                        $title = self::get_document_title($file);
+                        $size = filesize($base_work_dir.$current_path.'/'.$safe_file);
+                        $document_id = self::add_document(
+                            $_course,
+                            $current_path.'/'.$safe_file,
+                            'file',
+                            $size,
+                            $title
+                        );
+                        api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $document_id,
+                            'DocumentAdded',
+                            $user_id,
+                            $to_group_id,
+                            null,
+                            null,
+                            null,
+                            $current_session_id
+                        );
+                        //echo $current_path.'/'.$safe_file.' added!<br />';
+                    } else {
+                        api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $document_id,
+                            'DocumentUpdated',
+                            $user_id,
+                            $to_group_id,
+                            null,
+                            null,
+                            null,
+                            $current_session_id
+                        );
+                    }
+                }
+            }
+        }
+    }
+}

+ 5 - 1498
main/inc/lib/fileUpload.lib.php

@@ -1,1509 +1,16 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- *	FILE UPLOAD LIBRARY
+ *    FILE UPLOAD LIBRARY
  *
- *	This is the file upload library for Chamilo.
- *	Include/require it in your code to use its functionality.
+ *    This is the file upload library for Chamilo.
+ *    Include/require it in your code to use its functionality.
  *
- *	@package chamilo.library
- *	@todo test and reorganise
+ * @package chamilo.library
+ * @todo test and reorganise
  */
 /**
  * Code
  */
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 
-/**
- * Changes the file name extension from .php to .phps
- * Useful for securing a site.
- *
- * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
- * @param  - file_name (string) name of a file
- * @return - the filenam phps'ized
- */
-function php2phps($file_name) {
-	return preg_replace('/\.(php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $file_name);
-}
-
-/**
- * Renames .htaccess & .HTACCESS to htaccess.txt
- *
- * @param string $filename
- * @return string
- */
-function htaccess2txt($filename) {
-	return str_replace(array('.htaccess', '.HTACCESS'), array('htaccess.txt', 'htaccess.txt'), $filename);
-}
-
-/**
- * This function executes our safety precautions
- * more functions can be added
- *
- * @param string $filename
- * @return string
- * @see php2phps()
- * @see htaccess2txt()
- */
-function disable_dangerous_file($filename) {
-	return htaccess2txt(php2phps($filename));
-}
-
-/**
- * This function generates a unique name for a file on a given location
- * filenames are changed to name_#.ext
- *
- * @param string $path
- * @param string $name
- * @return new unique name
- */
-function unique_name($path, $name) {
-	$ext = substr(strrchr($name, '.'), 0);
-	$name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name, $ext)));
-	$n = 0;
-	$unique = '';
-	while (file_exists($path . $name_no_ext . $unique . $ext)) {
-		$unique = '_' . ++$n;
-	}
-	return $name_no_ext . $unique . $ext;
-}
-
-/**
- * Returns the name without extension, used for the title
- *
- * @param string $name
- * @return name without the extension
- */
-function get_document_title($name) {
-	// If they upload .htaccess...
-	$name = disable_dangerous_file($name);
-	$ext = substr(strrchr($name, '.'), 0);
-	return addslashes(substr($name, 0, strlen($name) - strlen(strstr($name, $ext))));
-}
-
-/**
- * This function checks if the upload succeeded
- *
- * @param array $uploaded_file ($_FILES)
- * @return true if upload succeeded
- */
-function process_uploaded_file($uploaded_file, $show_output = true) {
-	// Checking the error code sent with the file upload.
-
-	switch ($uploaded_file['error']) {
-		case 1:
-			// The uploaded file exceeds the upload_max_filesize directive in php.ini.
-			if ($show_output)
-                Display::display_error_message(get_lang('UplExceedMaxServerUpload').ini_get('upload_max_filesize'));
-			return false;
-		case 2:
-			// The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
-			// Not used at the moment, but could be handy if we want to limit the size of an upload (e.g. image upload in html editor).
-			$max_file_size = intval($_POST['MAX_FILE_SIZE']);
-			if ($show_output) {
-                Display::display_error_message(get_lang('UplExceedMaxPostSize'). format_file_size($max_file_size));
-			}
-			return false;
-		case 3:
-			// The uploaded file was only partially uploaded.
-		    if ($show_output) {
-			     Display::display_error_message(get_lang('UplPartialUpload').' '.get_lang('PleaseTryAgain'));
-		    }
-			return false;
-		case 4:
-			// No file was uploaded.
-		    if ($show_output) {
-			     Display::display_error_message(get_lang('UplNoFileUploaded').' '. get_lang('UplSelectFileFirst'));
-		    }
-			return false;
-	}
-
-	if (!file_exists($uploaded_file['tmp_name'])) {
-	    // No file was uploaded.
-	    if ($show_output) {
-            Display::display_error_message(get_lang('UplUploadFailed'));
-	    }
-        return false;
-    }
-
-    if (file_exists($uploaded_file['tmp_name'])) {
-        $filesize = filesize($uploaded_file['tmp_name']);
-        if (empty($filesize)) {
-            // No file was uploaded.
-            if ($show_output) {
-                Display::display_error_message(get_lang('UplUploadFailedSizeIsZero'));
-            }
-            return false;
-        }
-    }
-
-    $course_id = api_get_course_id();
-    //Checking course quota if we are in a course
-
-    if (!empty($course_id)) {
-        $max_filled_space = DocumentManager::get_course_quota();
-        // Check if there is enough space to save the file
-        if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
-            if ($show_output) {
-                Display::display_error_message(get_lang('UplNotEnoughSpace'));
-            }
-            return false;
-        }
-    }
-
-	// case 0: default: We assume there is no error, the file uploaded with success.
-	return true;
-}
-
-/**
- * This function does the save-work for the documents.
- * It handles the uploaded file and adds the properties to the database
- * If unzip=1 and the file is a zipfile, it is extracted
- * If we decide to save ALL kinds of documents in one database,
- * we could extend this with a $type='document', 'scormdocument',...
- *
- * @param array $_course
- * @param array $uploaded_file ($_FILES)
- * @param string $base_work_dir
- * @param string $upload_path
- * @param int $user_id
- * @param int $to_group_id, 0 for everybody
- * @param int $to_user_id, NULL for everybody
- * @param int $unzip 1/0
- * @param string $what_if_file_exists overwrite, rename or warn if exists (default)
- * @param boolean Optional output parameter. So far only use for unzip_uploaded_document function. If no output wanted on success, set to false.
- * @return path of the saved file
- */
-function handle_uploaded_document($_course, $uploaded_file, $base_work_dir, $upload_path, $user_id, $to_group_id = 0, $to_user_id = null, $unzip = 0, $what_if_file_exists = '', $output = true) {
-	if (!$user_id) die('Not a valid user.');
-	// Strip slashes
-	$uploaded_file['name'] = stripslashes($uploaded_file['name']);
-	// Add extension to files without one (if possible)
-	$uploaded_file['name'] = add_ext_on_mime($uploaded_file['name'], $uploaded_file['type']);
-	$current_session_id    = api_get_session_id();
-
-    //Just in case process_uploaded_file is not called
-    $max_filled_space = DocumentManager::get_course_quota();
-
-	// Check if there is enough space to save the file
-	if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
-	    if ($output) {
-            Display::display_error_message(get_lang('UplNotEnoughSpace'));
-		}
-		return false;
-	}
-
-	// If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
-	if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
-		return unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $max_filled_space, $output, $to_group_id);
-		//display_message('Unzipping file');
-	} elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploaded_file['name']))) { // We can only unzip ZIP files (no gz, tar,...)
-	    if ($output) {
-            Display::display_error_message(get_lang('UplNotAZip')." ".get_lang('PleaseTryAgain'));
-	    }
-		return false;
-	} else {
-		// Clean up the name, only ASCII characters should stay. (and strict)
-		$clean_name = replace_dangerous_char($uploaded_file['name'], 'strict');
-
-		// No "dangerous" files
-		$clean_name = disable_dangerous_file($clean_name);
-
-		if (!filter_extension($clean_name)) {
-		    if ($output) {
-                Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
-		    }
-			return false;
-		} else {
-			// Extension is good
-			//echo '<br />clean name = '.$clean_name;
-			//echo '<br />upload_path = '.$upload_path;
-			// If the upload path differs from / (= root) it will need a slash at the end
-			if ($upload_path != '/') {
-				$upload_path = $upload_path.'/';
-			}
-			//echo '<br />upload_path = '.$upload_path;
-			$file_path = $upload_path.$clean_name;
-			//echo '<br />file path = '.$file_path;
-			// Full path to where we want to store the file with trailing slash
-			$where_to_save = $base_work_dir.$upload_path;
-			// At least if the directory doesn't exist, tell so
-			if (!is_dir($where_to_save)) {
-			    if ($output){
-				    Display::display_error_message(get_lang('DestDirectoryDoesntExist').' ('.$upload_path.')');
-				}
-				return false;
-			}
-			//echo '<br />where to save = '.$where_to_save;
-			// Full path of the destination
-			$store_path = $where_to_save.$clean_name;
-			//echo '<br />store path = '.$store_path;
-			// Name of the document without the extension (for the title)
-			$document_name = get_document_title($uploaded_file['name']);
-			// Size of the uploaded file (in bytes)
-			$file_size = $uploaded_file['size'];
-
-			$files_perm = api_get_permissions_for_new_files();
-
-			// What to do if the target file exists
-			switch ($what_if_file_exists) {
-				// Overwrite the file if it exists
-				case 'overwrite':
-					// Check if the target file exists, so we can give another message
-					$file_exists = file_exists($store_path);
-					if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
-						chmod($store_path, $files_perm);
-						if ($file_exists) {
-							// UPDATE DATABASE
-							$document_id = DocumentManager::get_document_id($_course, $file_path);
-
-							if (is_numeric($document_id)) {
-								// Update filesize
-								update_existing_document($_course, $document_id, $uploaded_file['size']);
-
-								// Update document item_property
-								api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
-
-                                //Redo visibility
-                                api_set_default_visibility(TOOL_DOCUMENT, $document_id);
-							}
-							// If the file is in a folder, we need to update all parent folders
-							item_property_update_on_folder($_course, $upload_path, $user_id);
-							// Display success message with extra info to user
-							if ($output) {
-								Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.$file_path .' '. get_lang('UplFileOverwritten'), false);
-							}
-							return $file_path;
-						} else {
-							// Put the document data in the database
-							$document_id = add_document($_course, $file_path, 'file', $file_size, $document_name, null, 0, true);
-							if ($document_id) {
-								// Put the document in item_property update
-								api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
-							}
-							// If the file is in a folder, we need to update all parent folders
-							item_property_update_on_folder($_course, $upload_path, $user_id);
-							// Display success message to user
-							if ($output){
-                                Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.$file_path, false);
-							}
-							return $file_path;
-						}
-					} else {
-					    if ($output) {
-						  Display::display_error_message(get_lang('UplUnableToSaveFile'));
-					    }
-						return false;
-					}
-					break;
-
-				// Rename the file if it exists
-				case 'rename':
-					$new_name = unique_name($where_to_save, $clean_name);
-					$store_path = $where_to_save.$new_name;
-					$new_file_path = $upload_path.$new_name;
-
-					if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
-
-						chmod($store_path, $files_perm);
-
-						// Put the document data in the database
-						$document_id = add_document($_course, $new_file_path, 'file', $file_size, $document_name, null, 0, true);
-						if ($document_id) {
-							// Update document item_property
-							api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
-						}
-						// If the file is in a folder, we need to update all parent folders
-						item_property_update_on_folder($_course, $upload_path, $user_id);
-
-						// Display success message to user
-						if ($output){
-							Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.get_lang('UplFileSavedAs').$new_file_path, false);
-						}
-						return $new_file_path;
-					} else {
-                        if ($output) {
-                            Display::display_error_message(get_lang('UplUnableToSaveFile'));
-                        }
-						return false;
-					}
-					break;
-
-				// Only save the file if it doesn't exist or warn user if it does exist
-				default:
-					if (file_exists($store_path)) {
-					    if ($output) {
-						  Display::display_error_message($clean_name.' '.get_lang('UplAlreadyExists'));
-						}
-					} else {
-						if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
-							chmod($store_path, $files_perm);
-
-							// Put the document data in the database
-							$document_id = add_document($_course, $file_path, 'file', $file_size, $document_name, null, 0, true);
-
-							if ($document_id) {
-								// Update document item_property
-								api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
-							}
-							// If the file is in a folder, we need to update all parent folders
-							item_property_update_on_folder($_course,$upload_path,$user_id);
-
-							// Display success message to user
-							if ($output){
-								Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.$file_path, false);
-							}
-							return $file_path;
-						} else {
-						    if ($output){
-                                Display::display_error_message(get_lang('UplUnableToSaveFile'));
-							}
-							return false;
-						}
-					}
-					break;
-				}
-		}
-	}
-}
-
-/**
- * Checks if there is enough place to add a file on a directory
- * on the base of a maximum directory size allowed
- * deprecated: use enough_space instead!
- * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
- * @param  - file_size (int) - size of the file in byte
- * @param  - dir (string) - Path of the directory
- *           whe the file should be added
- * @param  - max_dir_space (int) - maximum size of the diretory in byte
- * @return - boolean true if there is enough space,
- *				boolean false otherwise
- *
- * @see    - enough_size() uses  dir_total_space() function
- */
-function enough_size($file_size, $dir, $max_dir_space) {
-	if ($max_dir_space) {
-		$already_filled_space = dir_total_space($dir);
-		if (($file_size + $already_filled_space) > $max_dir_space) {
-			return false;
-		}
-	}
-	return true;
-}
-
-
-/**
- * Computes the size already occupied by a directory and is subdirectories
- *
- * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
- * @param  - dir_path (string) - size of the file in byte
- * @return - int - return the directory size in bytes
- */
-function dir_total_space($dir_path) {
-
-	$save_dir = getcwd();
-	chdir($dir_path) ;
-	$handle = opendir($dir_path);
-
-	while ($element = readdir($handle)) {
-		if ( $element == '.' || $element == '..') {
-			continue; // Skip the current and parent directories
-		}
-		if (is_file($element)) {
-			$sumSize += filesize($element);
-		}
-		if (is_dir($element)) {
-			$dirList[] = $dir_path.'/'.$element;
-		}
-	}
-
-	closedir($handle) ;
-
-	if (sizeof($dirList) > 0) {
-		foreach ($dirList as $j) {
-			$sizeDir = dir_total_space($j);	// Recursivity
-			$sumSize += $sizeDir;
-		}
-	}
-	chdir($save_dir); // Return to initial position
-	return $sumSize;
-}
-
-
-/**
- * Tries to add an extension to files without extension
- * Some applications on Macintosh computers don't add an extension to the files.
- * This subroutine try to fix this on the basis of the MIME type sent
- * by the browser.
- *
- * Note : some browsers don't send the MIME Type (e.g. Netscape 4).
- *        We don't have solution for this kind of situation
- *
- * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
- * @author - Bert Vanderkimpen
- * @param  - file_name (string) - Name of the file
- * @param  - file_type (string) - Type of the file
- * @return - file_name (string)
- */
-function add_ext_on_mime($file_name, $file_type) {
-
-	// Check whether the file has an extension AND whether the browser has sent a MIME Type
-
-	if (!preg_match('/^.*\.[a-zA-Z_0-9]+$/', $file_name) && $file_type) {
-
-		// Build a "MIME-types / extensions" connection table
-
-		static $mime_type = array();
-
-		$mime_type[] = 'application/msword';             $extension[] = '.doc';
-		$mime_type[] = 'application/rtf';                $extension[] = '.rtf';
-		$mime_type[] = 'application/vnd.ms-powerpoint';  $extension[] = '.ppt';
-		$mime_type[] = 'application/vnd.ms-excel';       $extension[] = '.xls';
-		$mime_type[] = 'application/pdf';                $extension[] = '.pdf';
-		$mime_type[] = 'application/postscript';         $extension[] = '.ps';
-		$mime_type[] = 'application/mac-binhex40';       $extension[] = '.hqx';
-		$mime_type[] = 'application/x-gzip';             $extension[] = 'tar.gz';
-		$mime_type[] = 'application/x-shockwave-flash';  $extension[] = '.swf';
-		$mime_type[] = 'application/x-stuffit';          $extension[] = '.sit';
-		$mime_type[] = 'application/x-tar';              $extension[] = '.tar';
-		$mime_type[] = 'application/zip';                $extension[] = '.zip';
-		$mime_type[] = 'application/x-tar';              $extension[] = '.tar';
-		$mime_type[] = 'text/html';                      $extension[] = '.html';
-		$mime_type[] = 'text/plain';                     $extension[] = '.txt';
-		$mime_type[] = 'text/rtf';                       $extension[] = '.rtf';
-		$mime_type[] = 'img/gif';                        $extension[] = '.gif';
-		$mime_type[] = 'img/jpeg';                       $extension[] = '.jpg';
-		$mime_type[] = 'img/png';                        $extension[] = '.png';
-		$mime_type[] = 'audio/midi';                     $extension[] = '.mid';
-		$mime_type[] = 'audio/mpeg';                     $extension[] = '.mp3';
-		$mime_type[] = 'audio/x-aiff';                   $extension[] = '.aif';
-		$mime_type[] = 'audio/x-pn-realaudio';           $extension[] = '.rm';
-		$mime_type[] = 'audio/x-pn-realaudio-plugin';    $extension[] = '.rpm';
-		$mime_type[] = 'audio/x-wav';                    $extension[] = '.wav';
-		$mime_type[] = 'video/mpeg';                     $extension[] = '.mpg';
-		$mime_type[] = 'video/mpeg4-generic';            $extension[] = '.mp4';
-		$mime_type[] = 'video/quicktime';                $extension[] = '.mov';
-		$mime_type[] = 'video/x-msvideo';                $extension[] = '.avi';
-
-		$mime_type[] = 'video/x-ms-wmv';                 $extension[] = '.wmv';
-		$mime_type[] = 'video/x-flv';                    $extension[] = '.flv';
-		$mime_type[] = 'image/svg+xml';                  $extension[] = '.svg';
-		$mime_type[] = 'image/svg+xml';                  $extension[] = '.svgz';
-		$mime_type[] = 'video/ogg';                  	 $extension[] = '.ogv';
-		$mime_type[] = 'audio/ogg';                  	 $extension[] = '.oga';
-		$mime_type[] = 'application/ogg';                $extension[] = '.ogg';
-		$mime_type[] = 'application/ogg';                $extension[] = '.ogx';
-		$mime_type[] = 'application/x-freemind';         $extension[] = '.mm';
-
-		$mime_type[] = 'application/vnd.ms-word.document.macroEnabled.12';							$extension[] = '.docm';
-		$mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';	$extension[] = '.docx';
-		$mime_type[] = 'application/vnd.ms-word.template.macroEnabled.12';							$extension[] = '.dotm';
-		$mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';	$extension[] = '.dotx';
-		$mime_type[] = 'application/vnd.ms-powerpoint.template.macroEnabled.12';					$extension[] = '.potm';
-		$mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.template';		$extension[] = '.potx';
-		$mime_type[] = 'application/vnd.ms-powerpoint.addin.macroEnabled.12';						$extension[] = '.ppam';
-		$mime_type[] = 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12';					$extension[] = '.ppsm';
-		$mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';	$extension[] = '.ppsx';
-		$mime_type[] = 'application/vnd.ms-powerpoint.presentation.macroEnabled.12';				$extension[] = '.pptm';
-		$mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';	$extension[] = '.pptx';
-		$mime_type[] = 'application/vnd.ms-excel.addin.macroEnabled.12';							$extension[] = '.xlam';
-		$mime_type[] = 'application/vnd.ms-excel.sheet.binary.macroEnabled.12';						$extension[] = '.xlsb';
-		$mime_type[] = 'application/vnd.ms-excel.sheet.macroEnabled.12';							$extension[] = '.xlsm';
-		$mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';			$extension[] = '.xlsx';
-		$mime_type[] = 'application/vnd.ms-excel.template.macroEnabled.12';							$extension[] = '.xltm';
-		$mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.template';		$extension[] = '.xltx';
-
-		// Test on PC (files with no extension get application/octet-stream)
-		//$mime_type[] = 'application/octet-stream';      $extension[] = '.ext';
-
-		// Check whether the MIME type sent by the browser is within the table
-
-		foreach ($mime_type as $key => & $type) {
-			if ($type == $file_type) {
-				$file_name .=  $extension[$key];
-				break;
-			}
-		}
-
-		unset($mime_type, $extension, $type, $key); // Delete to eschew possible collisions
-	}
-
-	return $file_name;
-}
-
-/**
- *
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- *
- * @param  array $uploaded_file - follows the $_FILES Structure
- * @param  string $base_work_dir - base working directory of the module
- * @param  string $upload_path  - destination of the upload.
- *                               This path is to append to $base_work_dir
- * @param  int $max_filled_space - amount of bytes to not exceed in the base
- *                               working directory
- *
- * @return boolean true if it succeds, false otherwise
- */
-function treat_uploaded_file($uploaded_file, $base_work_dir, $upload_path, $max_filled_space, $uncompress = '') {
-
-	$uploaded_file['name'] = stripslashes($uploaded_file['name']);
-
-	if (!enough_size($uploaded_file['size'], $base_work_dir, $max_filled_space)) {
-		return api_failure::set_failure('not_enough_space');
-	}
-
-	if ($uncompress == 'unzip' && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
-		return unzip_uploaded_file($uploaded_file, $upload_path, $base_work_dir, $max_filled_space);
-	} else {
-		$file_name = trim($uploaded_file['name']);
-
-		// CHECK FOR NO DESIRED CHARACTERS
-		$file_name = replace_dangerous_char($file_name, 'strict');
-
-		// TRY TO ADD AN EXTENSION TO FILES WITOUT EXTENSION
-		$file_name = add_ext_on_mime($file_name, $uploaded_file['type']);
-
-		// HANDLE PHP FILES
-		$file_name = ($file_name);
-
-		// COPY THE FILE TO THE DESIRED DESTINATION
-		if (move_uploaded_file($uploaded_file['tmp_name'], $base_work_dir.$upload_path.'/'.$file_name)) {
-			set_default_settings($upload_path, $file_name);
-		}
-
-		return true;
-	}
-}
-
-/**
- * Manages all the unzipping process of an uploaded file
- *
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- *
- * @param  array  $uploaded_file - follows the $_FILES Structure
- * @param  string $upload_path   - destination of the upload.
- *                                This path is to append to $base_work_dir
- * @param  string $base_work_dir  - base working directory of the module
- * @param  int $max_filled_space  - amount of bytes to not exceed in the base
- *                                working directory
- *
- * @return boolean true if it succeeds false otherwise
- */
-function unzip_uploaded_file($uploaded_file, $upload_path, $base_work_dir, $max_filled_space) {
-	$zip_file = new PclZip($uploaded_file['tmp_name']);
-
-	// Check the zip content (real size and file extension)
-	if (file_exists($uploaded_file)) {
-
-		$zip_content_array = $zip_file->listContent();
-		$ok_scorm = false;
-		foreach ($zip_content_array as & $this_content) {
-			if (preg_match('~.(php.*|phtml)$~i', $this_content['filename'])) {
-				return api_failure::set_failure('php_file_in_zip_file');
-			} elseif (stristr($this_content['filename'], 'imsmanifest.xml')) {
-				$ok_scorm = true;
-			} elseif (stristr($this_content['filename'], 'LMS')) {
-				$ok_plantyn_scorm1 = true;
-			} elseif (stristr($this_content['filename'], 'REF')) {
-				$ok_plantyn_scorm2 = true;
-			} elseif (stristr($this_content['filename'], 'SCO')) {
-				$ok_plantyn_scorm3 = true;
-			} elseif (stristr($this_content['filename'], 'AICC')) {
-				$ok_aicc_scorm = true;
-			}
-			$realFileSize += $this_content['size'];
-		}
-
-		if (($ok_plantyn_scorm1 && $ok_plantyn_scorm2 && $ok_plantyn_scorm3) || $ok_aicc_scorm) {
-			$ok_scorm = true;
-		}
-
-		if (!$ok_scorm && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM) {
-			return api_failure::set_failure('not_scorm_content');
-		}
-
-		if (!enough_size($realFileSize, $base_work_dir, $max_filled_space)) {
-			return api_failure::set_failure('not_enough_space');
-		}
-
-		// It happens on Linux that $upload_path sometimes doesn't start with '/'
-		if ($upload_path[0] != '/') {
-			$upload_path = '/'.$upload_path;
-		}
-
-		if ($upload_path[strlen($upload_path) - 1] == '/') {
-			$upload_path=substr($upload_path, 0, -1);
-		}
-
-		/*	Uncompressing phase */
-
-		/*
-			The first version, using OS unzip, is not used anymore
-			because it does not return enough information.
-			We need to process each individual file in the zip archive to
-			- add it to the database
-			- parse & change relative html links
-		*/
-		if (PHP_OS == 'Linux' && ! get_cfg_var('safe_mode') && false) { // *** UGent, changed by OC ***
-			// Shell Method - if this is possible, it gains some speed
-			exec("unzip -d \"".$base_work_dir.$upload_path."/\"".$uploaded_file['name']." " .$uploaded_file['tmp_name']);
-		} else {
-			// PHP method - slower...
-			$save_dir = getcwd();
-			chdir($base_work_dir.$upload_path);
-			$unzippingState = $zip_file->extract();
-			for ($j=0; $j < count($unzippingState); $j++) {
-				$state = $unzippingState[$j];
-
-				// Fix relative links in html files
-				$extension = strrchr($state['stored_filename'], '.');
-			}
-
-			if ($dir = @opendir($base_work_dir.$upload_path)) {
-				while ($file = readdir($dir)) {
-					if ($file != '.' && $file != '..') {
-
-						$filetype = 'file';
-						if (is_dir($base_work_dir.$upload_path.'/'.$file)) $filetype = 'folder';
-
-						$safe_file = replace_dangerous_char($file, 'strict');
-						@rename($base_work_dir.$upload_path.'/'.$file,$base_work_dir.$upload_path.'/'.$safe_file);
-						set_default_settings($upload_path, $safe_file,$filetype);
-					}
-				}
-
-				closedir($dir);
-			}
-			chdir($save_dir); // Back to previous dir position
-		}
-	}
-
-	return true;
-}
-
-/**
- * Manages all the unzipping process of an uploaded document
- * This uses the item_property table for properties of documents
- *
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- * @author Bert Vanderkimpen
- *
- * @param  array  $uploaded_file - follows the $_FILES Structure
- * @param  string $upload_path   - destination of the upload.
- *                                This path is to append to $base_work_dir
- * @param  string $base_work_dir  - base working directory of the module
- * @param  int $max_filled_space  - amount of bytes to not exceed in the base
- *                                working directory
- * @param		boolean	Output switch. Optional. If no output not wanted on success, set to false.
- *
- * @return boolean true if it succeeds false otherwise
- */
-function unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $max_filled_space, $output = true, $to_group_id = 0) {
-	global $_course;
-	global $_user;
-	global $to_user_id;
-	global $to_group_id;
-
-	$zip_file = new PclZip($uploaded_file['tmp_name']);
-
-	// Check the zip content (real size and file extension)
-
-	$zip_content_array = (array)$zip_file->listContent();
-
-	foreach($zip_content_array as & $this_content) {
-		$real_filesize += $this_content['size'];
-	}
-
-	if (!DocumentManager::enough_space($real_filesize, $max_filled_space)) {
-		Display::display_error_message(get_lang('UplNotEnoughSpace'));
-		return false;
-	}
-
-	// It happens on Linux that $upload_path sometimes doesn't start with '/'
-	if ($upload_path[0] != '/') {
-		$upload_path='/'.$upload_path;
-	}
-
-	/*	Uncompressing phase */
-
-	// Get into the right directory
-	$save_dir = getcwd();
-	chdir($base_work_dir.$upload_path);
-	// We extract using a callback function that "cleans" the path
-	$unzipping_state = $zip_file->extract(PCLZIP_CB_PRE_EXTRACT, 'clean_up_files_in_zip', PCLZIP_OPT_REPLACE_NEWER);
-	// Add all documents in the unzipped folder to the database
-	add_all_documents_in_folder_to_database($_course, $_user['user_id'], $base_work_dir ,$upload_path == '/' ? '' : $upload_path, $to_group_id);
-	//Display::display_normal_message(get_lang('UplZipExtractSuccess'));
-	return true;
-}
-
-/**
- * This function is a callback function that is used while extracting a zipfile
- * http://www.phpconcept.net/pclzip/man/en/index.php?options-pclzip_cb_pre_extract
- *
- * @param $p_event
- * @param $p_header
- * @return 1 (If the function returns 1, then the extraction is resumed)
- */
-function clean_up_files_in_zip($p_event, &$p_header) {
-	$res = clean_up_path($p_header['filename']);
-	return $res;
-}
-
-/**
- * This function cleans up a given path
- * by eliminating dangerous file names and cleaning them
- *
- * @param string $path
- * @return $path
- * @see disable_dangerous_file()
- * @see replace_dangerous_char()
- */
-function clean_up_path(&$path) {
-	// Split the path in folders and files
-    $path_array = explode('/', $path);
-    // Clean up every foler and filename in the path
-    foreach ($path_array as $key => & $val) {
-		// We don't want to lose the dots in ././folder/file (cfr. zipfile)
-		if ($val != '.') {
-			$val = disable_dangerous_file(replace_dangerous_char($val));
-		}
-	}
-	// Join the "cleaned" path (modified in-place as passed by reference)
-	$path = implode('/', $path_array);
-	$res = filter_extension($path);
-	return $res;
-}
-
-/**
- * Checks if the file is dangerous, based on extension and/or mimetype.
- * The list of extensions accepted/rejected can be found from
- * api_get_setting('upload_extensions_exclude') and api_get_setting('upload_extensions_include')
- * @param	string 	filename passed by reference. The filename will be modified if filter rules say so! (you can include path but the filename should look like 'abc.html')
- * @return	int		0 to skip file, 1 to keep file
- */
-function filter_extension(&$filename) {
-
-	if (substr($filename, -1) == '/') {
-		return 1;  // Authorize directories
-	}
-	$blacklist = api_get_setting('upload_extensions_list_type');
-	if ($blacklist != 'whitelist') { // if = blacklist
-		$extensions = explode(';', strtolower(api_get_setting('upload_extensions_blacklist')));
-
-		$skip = api_get_setting('upload_extensions_skip');
-		$ext = strrchr($filename, '.');
-		$ext = substr($ext, 1);
-		if (empty($ext)) {
-			return 1; // We're in blacklist mode, so accept empty extensions
-		}
-		if (in_array(strtolower($ext), $extensions)) {
-			if ($skip == 'true') {
-				return 0;
-			} else {
-				$new_ext = api_get_setting('upload_extensions_replace_by');
-				$filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
-				return 1;
-			}
-		} else {
-			return 1;
-		}
-	} else {
-		$extensions = split(';', strtolower(api_get_setting('upload_extensions_whitelist')));
-		$skip = api_get_setting('upload_extensions_skip');
-		$ext = strrchr($filename, '.');
-		$ext = substr($ext, 1);
-		if (empty($ext)) {
-			return 1; // Accept empty extensions
-		}
-		if (!in_array(strtolower($ext), $extensions)) {
-			if ($skip == 'true') {
-				return 0;
-			} else {
-				$new_ext = api_get_setting('upload_extensions_replace_by');
-				$filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
-				return 1;
-			}
-		} else {
-			return 1;
-		}
-	}
-}
-
-/**
- * Adds a new document to the database
- *
- * @param array $_course
- * @param string $path
- * @param string $filetype
- * @param int $filesize
- * @param string $title
- * @return id if inserted document
- */
-function add_document($_course, $path, $filetype, $filesize, $title, $comment = null, $readonly = 0, $save_visibility = true, $group_id = null) {
-	$session_id    = api_get_session_id();
-	$readonly      = intval($readonly);
-	$comment       = Database::escape_string($comment);
-	$path          = Database::escape_string($path);
-	$filetype      = Database::escape_string($filetype);
-	$filesize      = intval($filesize);
-    $title         = Database::escape_string(htmlspecialchars($title));
-    $c_id          = $_course['real_id'];
-
-	$table_document = Database::get_course_table(TABLE_DOCUMENT);
-	$sql = "INSERT INTO $table_document (c_id, path, filetype, size, title, comment, readonly, session_id)
-	        VALUES ($c_id, '$path','$filetype','$filesize','$title', '$comment', $readonly, $session_id)";
-
-	if (Database::query($sql)) {
-		$document_id = Database::insert_id();
-        if ($document_id) {
-            if ($save_visibility) {
-                api_set_default_visibility($document_id, TOOL_DOCUMENT, $group_id);
-            }
-        }
-		return $document_id;
-	} else {
-		return false;
-	}
-}
-
-/**
- * Updates an existing document in the database
- * as the file exists, we only need to change the size
- *
- * @param array $_course
- * @param int $document_id
- * @param int $filesize
- * @param int $readonly
- * @return boolean true /false
- */
-function update_existing_document($_course, $document_id, $filesize, $readonly = 0) {
-	$document_table = Database::get_course_table(TABLE_DOCUMENT);
-	$document_id 	= intval($document_id);
-	$filesize 		= intval($filesize);
-	$readonly 		= intval($readonly);
-	$course_id 		= $_course['real_id'];
-
-	$sql = "UPDATE $document_table SET size = '$filesize' , readonly = '$readonly'
-			WHERE c_id = $course_id AND id = $document_id";
-	if (Database::query($sql)) {
-		return true;
-	} else {
-		return false;
-	}
-}
-
-/**
- * This function updates the last_edit_date, last edit user id on all folders in a given path
- *
- * @param array $_course
- * @param string $path
- * @param int $user_id
- */
-function item_property_update_on_folder($_course, $path, $user_id) {
-	//display_message("Start update_lastedit_on_folder");
-	// If we are in the root, just return... no need to update anything
-	if ($path == '/') {
-		return;
-	}
-
-	$user_id = intval($user_id);
-
-	// If the given path ends with a / we remove it
-	$endchar = substr($path, strlen($path) - 1, 1);
-	if ($endchar == '/') {
-		$path = substr($path, 0, strlen($path) - 1);
-	}
-
-	$TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-	// Get the time
-	$time = date('Y-m-d H:i:s', time());
-
-	// Det all paths in the given path
-	// /folder/subfolder/subsubfolder/file
-	// if file is updated, subsubfolder, subfolder and folder are updated
-
-	$exploded_path = explode('/', $path);
-	$course_id = api_get_course_int_id();
-	foreach ($exploded_path as $key => & $value) {
-		// We don't want a slash before our first slash
-		if ($key != 0) {
-			$newpath .= '/'.$value;
-
-			//echo 'path= '.$newpath.'<br />';
-			// Select ID of given folder
-			$folder_id = DocumentManager::get_document_id($_course, $newpath);
-
-			if ($folder_id) {
-				$sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time',lastedit_type='DocumentInFolderUpdated', lastedit_user_id='$user_id'
-						WHERE c_id = $course_id AND tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
-				Database::query($sql);
-			}
-		}
-	}
-}
-
-/**
- * Returns the directory depth of the file.
- *
- * @author	Olivier Cauberghe <olivier.cauberghe@ugent.be>
- * @param	path+filename eg: /main/document/document.php
- * @return	The directory depth
- */
-function get_levels($filename) {
-	$levels=explode('/', $filename);
-	if (empty($levels[count($levels) - 1])) {
-		unset($levels[count($levels) - 1]);
-	}
-	return count($levels);
-}
-
-/**
- * Adds file to document table in database
- * deprecated: use file_set_default_settings instead
- *
- * @author	Olivier Cauberghe <olivier.cauberghe@ugent.be>
- * @param	path,filename
- * action:	Adds an entry to the document table with the default settings.
- */
-function set_default_settings($upload_path, $filename, $filetype = 'file') {
-	global $dbTable,$_configuration;
-	global $default_visibility;
-
-	if (!$default_visibility) {
-		$default_visibility = 'v';
-	}
-	$filetype = Database::escape_string($filetype);
-
-	$upload_path = str_replace('\\', '/', $upload_path);
-	$upload_path = str_replace('//', '/', $upload_path);
-
-	if ($upload_path == '/') {
-		$upload_path='';
-	} elseif (!empty($upload_path) && $upload_path[0] != '/') {
-		$upload_path="/$upload_path";
-	}
-
-	$endchar = substr($filename, strlen($filename) - 1, 1);
-
-	if ($endchar == '/') {
-		$filename = substr($filename, 0, -1);
-	}
-
-	// $dbTable already has backticks!
-	//$query = "select count(*) as bestaat from $dbTable where path='$upload_path/$filename'";
-	$query = "select count(*) as bestaat from $dbTable where path='$upload_path/$filename'";
-	$result = Database::query($query);
-	$row = Database::fetch_array($result);
-	if ($row['bestaat'] > 0) {
-		//$query = "update $dbTable set path='$upload_path/$filename',visibility='$default_visibility', filetype='$filetype' where path='$upload_path/$filename'";
-		$query = "UPDATE $dbTable SET path='$upload_path/$filename',visibility='$default_visibility', filetype='$filetype' where path='$upload_path/$filename'";
-	} else {
-		//$query = "INSERT INTO $dbTable (path,visibility,filetype) VALUES('$upload_path/$filename','$default_visibility','$filetype')";
-		$query = "INSERT INTO $dbTable (path,visibility,filetype) VALUES('$upload_path/$filename','$default_visibility','$filetype')";
-	}
-	Database::query($query);
-}
-
-/**
- * Retrieves the image path list in a html file
- *
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- * @param  string $html_file
- * @return array -  images path list
- */
-function search_img_from_html($html_file) {
-
-	$img_path_list = array();
-
-	if (!$fp = fopen($html_file, 'r')) {
-		return ;
-	}
-
-	// Aearch and store occurences of the <img> tag in an array
-	$size_file = (filesize($html_file) === 0) ? 1 : filesize($html_file);
-	if (isset($fp) && $fp !== false) {
-		$buffer = fread($fp, $size_file);
-		if (strlen($buffer) >= 0 && $buffer !== false) {
-			//
-		} else {
-			die('<center>Can not read file.</center>');
-		}
-	} else {
-		die('<center>Can not read file.</center>');
-	}
-	$matches = array();
-	if (preg_match_all('~<[[:space:]]*img[^>]*>~i', $buffer, $matches)) {
-		$img_tag_list = $matches[0];
-	}
-
-	fclose ($fp);
-	unset($buffer);
-
-	// Search the image file path from all the <IMG> tag detected
-
-	if (sizeof($img_tag_list) > 0) {
-		foreach ($img_tag_list as & $this_img_tag) {
-			if (preg_match('~src[[:space:]]*=[[:space:]]*[\"]{1}([^\"]+)[\"]{1}~i', $this_img_tag, $matches)) {
-				$img_path_list[] = $matches[1];
-			}
-		}
-		$img_path_list = array_unique($img_path_list); // Remove duplicate entries
-	}
-
-	return $img_path_list;
-}
-
-/**
- * Creates a new directory trying to find a directory name
- * that doesn't already exist
- * (we could use unique_name() here...)
- *
- * @author  Hugues Peeters <hugues.peeters@claroline.net>
- * @author  Bert Vanderkimpen
- * @param   array   $_course current course information
- * @param   int     $user_id current user id
- * @param   string  $desiredDirName complete path of the desired name
- * @param   string  The visible name of the directory
- * @param   int     Visibility (0 for invisible, 1 for visible, 2 for deleted)
- * @return  string  actual directory name if it succeeds,
- *          boolean false otherwise
- */
-function create_unexisting_directory($_course, $user_id, $session_id, $to_group_id, $to_user_id, $base_work_dir, $desired_dir_name, $title = null, $visibility = '') {
-	$nb = '';
-    // add numerical suffix to directory if another one of the same number already exists
-	while (file_exists($base_work_dir.$desired_dir_name.$nb)) {
-		$nb += 1;
-	}
-
-	if ($title == null) {
-		$title = basename($desired_dir_name);
-	}
-	$course_id = $_course['real_id'];
-
-	if (mkdir($base_work_dir.$desired_dir_name.$nb, api_get_permissions_for_new_directories(), true)) {
-		// Check if pathname already exists inside document table
-		$tbl_document = Database::get_course_table(TABLE_DOCUMENT);
-		$sql = "SELECT path FROM $tbl_document WHERE c_id = $course_id AND path='".$desired_dir_name.$nb."'";
-
-		$rs = Database::query($sql);
-		if (Database::num_rows($rs) == 0) {
-			$document_id = add_document($_course, $desired_dir_name.$nb, 'folder', 0, $title, null, 0, true, $to_group_id);
-			if ($document_id) {
-				// Update document item_property
-				if ($visibility !== '') {
-					$visibilities = array(0 => 'invisible', 1 => 'visible', 2 => 'delete');
-					api_item_property_update($_course, TOOL_DOCUMENT, $document_id, $visibilities[$visibility], $user_id, $to_group_id, $to_user_id, null, null, $session_id);
-				} else {
-					api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'FolderCreated', $user_id, $to_group_id, $to_user_id, null, null, $session_id);
-				}
-				return $desired_dir_name.$nb;
-			}
-		} else {
-			//This means the folder NOT exist in the filesystem (now this was created) but there is a record in the Database
-			return $desired_dir_name.$nb;
-		}
-	} else {
-		return false;
-	}
-}
-
-/**
- * Handles uploaded missing images
- *
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- * @author Bert Vanderkimpen
- * @param array $_course
- * @param array $uploaded_file_collection - follows the $_FILES Structure
- * @param string $base_work_dir
- * @param string $missing_files_dir
- * @param int $user_id
- * @param int $max_filled_space
- */
-function move_uploaded_file_collection_into_directory($_course, $uploaded_file_collection, $base_work_dir, $missing_files_dir, $user_id, $to_group_id, $to_user_id, $max_filled_space) {
-	$number_of_uploaded_images = count($uploaded_file_collection['name']);
-	for ($i = 0; $i < $number_of_uploaded_images; $i++) {
-		$missing_file['name'] = $uploaded_file_collection['name'][$i];
-		$missing_file['type'] = $uploaded_file_collection['type'][$i];
-		$missing_file['tmp_name'] = $uploaded_file_collection['tmp_name'][$i];
-		$missing_file['error'] = $uploaded_file_collection['error'][$i];
-		$missing_file['size'] = $uploaded_file_collection['size'][$i];
-
-		$upload_ok = process_uploaded_file($missing_file);
-		if ($upload_ok) {
-			$new_file_list[] = handle_uploaded_document($_course, $missing_file, $base_work_dir, $missing_files_dir, $user_id, $to_group_id, $to_user_id, $max_filled_space, 0, 'overwrite');
-		}
-		unset($missing_file);
-	}
-	return $new_file_list;
-}
-
-/**
- * Opens the old html file and replace the src path into the img tag
- * This also works for files in subdirectories.
- * @param $original_img_path is an array
- * @param $new_img_path is an array
- */
-function replace_img_path_in_html_file($original_img_path, $new_img_path, $html_file) {
-	global $_course;
-
-	// Open the file
-
-	$fp = fopen($html_file, 'r');
-	$buffer = fread($fp, filesize($html_file));
-
-
-	// Fix the image tags
-
-	for ($i = 0, $fileNb = count($original_img_path); $i < $fileNb ; $i++) {
-		$replace_what = $original_img_path[$i];
-		// We only need the directory and the filename /path/to/file_html_files/missing_file.gif -> file_html_files/missing_file.gif
-		$exploded_file_path = explode('/', $new_img_path[$i]);
-		$replace_by = $exploded_file_path[count($exploded_file_path) - 2].'/'.$exploded_file_path[count($exploded_file_path) - 1];
-		//$message .= "Element [$i] <b>" . $replace_what . "</b> replaced by <b>" . $replace_by . "</b><br />"; //debug
-		//api_display_debug_info($message);
-
-		$buffer = str_replace($replace_what, $replace_by, $buffer);
-	}
-
-	$new_html_content .= $buffer;
-
-	@fclose($fp);
-
-	// Write the resulted new file
-
-	if (!$fp = fopen($html_file, 'w')) {
-		return;
-	}
-
-	if (!fwrite($fp, $new_html_content)) {
-		return;
-	}
-}
-
-/**
- * Creates a file containing an html redirection to a given url
- *
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- * @param string $file_path
- * @param string $url
- * @return void
- */
-function create_link_file($file_path, $url) {
-	$file_content = '<html>'
-				  .'<head>'
-				  .'<meta http-equiv="refresh" content="1;url='.$url.'">'
-				  .'</head>'
-				  .'<body>'
-				  .'</body>'
-				  .'</html>';
-	if (file_exists($file_path)) {
-		if (!($fp = fopen ($file_path, 'w'))) {
-			return false;
-		}
-		return fwrite($fp, $file_content);
-	}
-}
-
-/**
- * Opens html file $full_file_name;
- * Parses the hyperlinks; and
- * Writes the result back in the html file.
- *
- * @author Roan Embrechts
- * @version 0.1
- */
-function api_replace_links_in_html($upload_path, $full_file_name) {
-	// Open the file
-	if (file_exists($full_file_name)) {
-		$fp = fopen($full_file_name, 'r');
-		$buffer = fread ($fp, filesize ($full_file_name));
-
-		// Parse the contents
-		$new_html_content = api_replace_links_in_string($upload_path, $buffer);
-
-		// Write the result
-		$fp = fopen($full_file_name, 'w');
-		fwrite($fp, $new_html_content);
-	}
-}
-
-/**
-	deprecated: use api_replace_parameter instead
-
-	Parse the buffer string provided as parameter
-	Replace the a href tags so they are displayed correctly.
-	- works for files in root and subdirectories
-	- replace relative hyperlinks to use showinframes.php?file= ...
-	- add target="_self" to all absolute hyperlinks
-	- leave local anchors untouched (e.g. #CHAPTER1)
-	- leave links with download.php and showinframes.php untouched
-
-	@author Roan Embrechts
-	@version 0.6
-*/
-function api_replace_links_in_string($upload_path, $buffer) {
-	// Search for hyperlinks
-	$matches = array();
-	if (preg_match_all('/<a[\s]*href[^<]*>/i', $buffer, $matches)) {
-		$tag_list = $matches[0];
-	}
-
-	// Search the filepath of all detected <a href> tags
-	if (sizeof($tag_list) > 0) {
-		$file_path_list = array();
-		$href_list = array();
-
-		foreach ($tag_list as & $this_tag) {
-			/* Match case insensitive, the stuff between the two ~ :
-				a href = <exactly one quote><one or more non-quotes><exactly one ">
-				e.g. a href="www.google.be", A HREF =   "info.html"
-				to match ["] escape the " or else PHP interprets it
-				[\"]{1} --> matches exactly one "
-				+	1 or more (like * is 0 or more)
-				[\s]* matches whitespace
-				$matches contains captured subpatterns
-				the only one here is ([^\"]+) --> matches[1]
-			*/
-			if (preg_match("~a href[\s]*=[\s]*[\"]{1}([^\"]+)[\"]{1}~i", $this_tag, $matches)) {
-				$file_path_list[] = $matches[1]; // older
-				$href_list[] = $matches[0]; // to also add target="_self"
-			}
-		}
-	}
-
-	// Replace the original hyperlinks by the correct ones
-	for ($count = 0; $count < sizeof($href_list); $count++) {
-
-		$replace_what[$count] = $href_list[$count];
-
-		$is_absolute_hyperlink = strpos($replace_what[$count], 'http');
-		$is_local_anchor = strpos($replace_what[$count], "#");
-		if (!$is_absolute_hyperlink && !$is_local_anchor) {
-			// This is a relative hyperlink
-			if ((strpos($replace_what[$count], 'showinframes.php') === false) && (strpos($replace_what[$count], 'download.php') === false)) {
-				// Fix the link to use showinframes.php
-				$replace_by[$count] = 'a href = "showinframes.php?file='.$upload_path.'/'.$file_path_list[$count].'" target="_self"';
-			} else {
-				// URL has been already fixed, leave it as is
-				$replace_by[$count] = $replace_what[$count];
-			}
-		} elseif ($is_absolute_hyperlink) {
-			$replace_by[$count] = 'a href="'.$file_path_list[$count].'" target ="_self"';
-		} else {
-			// Don't change anything
-			$replace_by[$count] = $replace_what[$count];
-		}
-		//Display::display_normal_message('Link replaced by ' . $replace_by[$count]); // debug
-	}
-
-	$buffer = str_replace($replace_what, $replace_by, $buffer);
-	return $buffer;
-}
-
-/**
-	EXPERIMENTAL - function seems to work, needs more testing
-
-	@param $upload_path is the path where the document is stored, like "/archive/"
-	if it is the root level, the function expects "/"
-	otherwise "/path/"
-
-	This function parses all tags with $param_name parameters.
-	so the tags are displayed correctly.
-
-	--------------
-	Algorithm v1.0
-	--------------
-		given a string and a parameter,
-		* OK find all tags in that string with the specified parameter (like href or src)
-		* OK for every one of these tags, find the src|href|... part to edit it
-		* OK change the src|href|... part to use download.php (or showinframes.php)
-		* OK do some special stuff for hyperlinks
-
-		Exceptions
-		* OK if download.php or showinframes.php is already in the tag, leave it alone
-		* OK if mailto is in the tag, leave it alone
-		* OK if the src|href param contains http://, it's absolute --> leave it alone
-
-		Special for hyperlinks (a href...)
-		* OK add target="_self"
-		* OK use showinframes.php instead of download.php
-
-	@author Roan Embrechts
-	@version 1.1
-*/
-function api_replace_parameter($upload_path, $buffer, $param_name = 'src') {
-
-	// Search for tags with $param_name as a parameter
-
-	/*
-	// [\s]*	matches whitespace
-	// [\"=a-z] matches ", = and a-z
-	// ([\s]*[a-z]*)*	matches all whitespace and normal alphabet
-	//					characters a-z combinations but seems too slow
-	//	perhaps ([\s]*[a-z]*) a maximum number of times ?
-	// [\s]*[a-z]*[\s]*	matches many tags
-	// the ending "i" means to match case insensitive (a matches a and A)
-	*/
-	$matches = array();
-	if (preg_match_all('/<[a-z]+[^<]*'.$param_name.'[^<]*>/i', $buffer, $matches)) {
-		$tag_list = $matches[0];
-	}
-
-	// Search the filepath of parameter $param_name in all detected tags
-
-	if (sizeof($tag_list) > 0) {
-		$file_path_list = array();
-		$href_list = array();
-
-		foreach ($tag_list as & $this_tag) {
-			//Display::display_normal_message(htmlentities($this_tag)); //debug
-			if ( preg_match("~".$param_name."[\s]*=[\s]*[\"]{1}([^\"]+)[\"]{1}~i", $this_tag, $matches)) {
-				$file_path_list[] = $matches[1]; // older
-				$href_list[] = $matches[0]; // to also add target="_self"
-			}
-		}
-	}
-
-	// Replace the original tags by the correct ones
-
-	for ($count = 0; $count < sizeof($href_list); $count++) {
-		$replace_what[$count] = $href_list[$count];
-
-		$is_absolute_hyperlink = strpos($replace_what[$count], 'http');
-		$is_local_anchor = strpos($replace_what[$count], '#');
-		if (!$is_absolute_hyperlink && !$is_local_anchor) {
-			if ((strpos($replace_what[$count], 'showinframes.php') === false)
-				&& (strpos($replace_what[$count], 'download.php') === false)
-				&& (strpos($replace_what[$count], 'mailto') === false)) {
-
-				// Fix the link to use download.php or showinframes.php
-				if (preg_match("/<a([\s]*[\"\/:'=a-z0-9]*){5}href[^<]*>/i", $tag_list[$count])) {
-					$replace_by[$count] = " $param_name =\"showinframes.php?file=" . $upload_path.$file_path_list[$count]."\" target=\"_self\" ";
-				} else {
-					$replace_by[$count] = " $param_name =\"download.php?doc_url=" . $upload_path.$file_path_list[$count]."\" ";
-				}
-			} else {
-				// "mailto" or url already fixed, leave as is
-				//$message .= "Already fixed or contains mailto: ";
-				$replace_by[$count] = $replace_what[$count];
-			}
-		} elseif ($is_absolute_hyperlink) {
-			//$message .= "Absolute hyperlink, don't change, add target=_self: ";
-			$replace_by[$count] = " $param_name=\"" . $file_path_list[$count] . "\" target =\"_self\"";
-		} else {
-			// Don't change anything
-			//$message .= "Local anchor, don't change: ";
-			$replace_by[$count] = $replace_what[$count];
-		}
-		//$message .= "In tag $count, <b>" . htmlentities($tag_list[$count])
-		//	. "</b>, parameter <b>" . $replace_what[$count] . "</b> replaced by <b>" . $replace_by[$count] . "</b><br>"; //debug
-	}
-	//if ($message) api_display_debug_info($message); //debug
-	$buffer = str_replace($replace_what, $replace_by, $buffer);
-	return $buffer;
-}
-
-/**
- * Checks the extension of a file, if it's .htm or .html
- * we use search_img_from_html to get all image paths in the file
- *
- * @param string $file
- * @return array paths
- * @see check_for_missing_files() uses search_img_from_html()
- */
-function check_for_missing_files($file) {
-	if (strrchr($file, '.') == '.htm' || strrchr($file, '.') == '.html') {
-		$img_file_path = search_img_from_html($file);
-		return $img_file_path;
-	}
-	return false;
-}
-
-/**
- * This function builds a form that asks for the missing images in a html file
- * maybe we should do this another way?
- *
- * @param array $missing_files
- * @param string $upload_path
- * @param string $file_name
- * @return string the form
- */
-function build_missing_files_form($missing_files, $upload_path, $file_name) {
-	// Do we need a / or not?
-	$added_slash = ($upload_path == '/') ? '' : '/';
-	$folder_id      = DocumentManager::get_document_id(api_get_course_info(), $upload_path);
-	// Build the form
-	$form .= "<p><strong>".get_lang('MissingImagesDetected')."</strong></p>"
-		."<form method=\"post\" action=\"".api_get_self()."\" enctype=\"multipart/form-data\">"
-		// Related_file is the path to the file that has missing images
-		."<input type=\"hidden\" name=\"related_file\" value=\"".$upload_path.$added_slash.$file_name."\" />"
-		."<input type=\"hidden\" name=\"upload_path\" value=\"".$upload_path."\" />"
-		."<input type=\"hidden\" name=\"id\" value=\"".$folder_id."\" />"
-		."<table border=\"0\">";
-	foreach ($missing_files as & $this_img_file_path) {
-		$form .= "<tr>"
-			."<td>".basename($this_img_file_path)." : </td>"
-			."<td>"
-			."<input type=\"file\" name=\"img_file[]\"/>"
-			."<input type=\"hidden\" name=\"img_file_path[]\" value=\"".$this_img_file_path."\" />"
-			."</td>"
-			."</tr>";
-	}
-	$form .= "</table>"
-		."<button type='submit' name=\"cancel_submit_image\" value=\"".get_lang('Cancel')."\" class=\"cancel\">".get_lang('Cancel')."</button>"
-		."<button type='submit' name=\"submit_image\" value=\"".get_lang('Ok')."\" class=\"save\">".get_lang('Ok')."</button>"
-		."</form>";
-	return $form;
-}
-
-/**
- * This recursive function can be used during the upgrade process form older versions of Chamilo
- * It crawls the given directory, checks if the file is in the DB and adds it if it's not
- *
- * @param string $base_work_dir
- * @param string $current_path, needed for recursivity
- */
-function add_all_documents_in_folder_to_database($_course, $user_id, $base_work_dir, $current_path = '', $to_group_id = 0) {
-	$current_session_id = api_get_session_id();
-	$path = $base_work_dir.$current_path;
-	// Open dir
-	$handle = opendir($path);
-	if (is_dir($path)) {
-		// Run trough
-		while ($file = readdir($handle)) {
-		   if ($file == '.' || $file == '..') continue;
-
-		   $completepath = "$path/$file";
-		   // Directory?
-		   if (is_dir($completepath)) {
-		   		$title = get_document_title($file);
-		   		$safe_file = replace_dangerous_char($file);
-		   		@rename($path.'/'.$file, $path.'/'.$safe_file);
-		   		// If we can't find the file, add it
-		   		if (!DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file)) {
-		   			$document_id = add_document($_course, $current_path.'/'.$safe_file, 'folder', 0, $title);
-		   			api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, null, null, null, $current_session_id);
-		   			//echo $current_path.'/'.$safe_file.' added!<br />';
-		   		}
-		   		// Recursive
-		   		add_all_documents_in_folder_to_database($_course,$user_id,$base_work_dir,$current_path.'/'.$safe_file, $to_group_id);
-		   } else {
-		   		//Rename
-		   		$safe_file = disable_dangerous_file(replace_dangerous_char($file, 'strict'));
-				@rename($base_work_dir.$current_path.'/'.$file, $base_work_dir.$current_path.'/'.$safe_file);
-				$document_id = DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file);
-				if (!$document_id) {
-					$title = get_document_title($file);
-					$size = filesize($base_work_dir.$current_path.'/'.$safe_file);
-					$document_id = add_document($_course, $current_path.'/'.$safe_file, 'file', $size, $title);
-					api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, null, null, null, $current_session_id);
-					//echo $current_path.'/'.$safe_file.' added!<br />';
-				} else {
-					api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $user_id, $to_group_id, null, null, null, $current_session_id);
-				}
-		   }
-		}
-	}
-}

+ 19 - 13
main/inc/lib/file_store.class.php

@@ -12,17 +12,16 @@ class FileStore
     /**
      *
      * @param int $c_id
-     * @param string $sub_path 
-
-     * @return FileStore 
+     * @param string $sub_path
+     * @return FileStore
      */
-    static function course($c_id, $sub_path = '') 
-    { 
-        
+    static function course($c_id, $sub_path = '')
+    {
+
         $sys_path = api_get_path(SYS_COURSE_PATH);
         $course = api_get_course_info_by_id($c_id);
         $course_path = $course['path'];
-        $path = $sys_path . $course_path . $sub_path;
+        $path = $sys_path.$course_path.$sub_path;
         if (!is_dir($path)) {
             $mode = api_get_permissions_for_new_directories();
             $success = mkdir($path, $mode, true);
@@ -30,6 +29,7 @@ class FileStore
                 return false;
             }
         }
+
         return new self($path);
     }
 
@@ -49,7 +49,7 @@ class FileStore
 
     function accept($filename)
     {
-        return (bool) filter_extension($filename);
+        return (bool)FileManager::filter_extension($filename);
     }
 
     function add($path)
@@ -59,24 +59,29 @@ class FileStore
 
         $new_path = "$root/$id";
         $success = @move_uploaded_file($path, $new_path);
+
         return $success ? $id : false;
     }
-    
-    function remove($path){
-        
+
+    function remove($path)
+    {
+
         $root = $this->root();
         $full_path = "$root/$path";
-        if(is_file($full_path)){
+        if (is_file($full_path)) {
             $result = unlink($full_path);
+
             return $result;
         }
-        return  false;
+
+        return false;
     }
 
     function get($id)
     {
         $root = $this->root();
         $result = "$root/$id";
+
         return $result;
     }
 
@@ -89,6 +94,7 @@ class FileStore
             $id = uniqid('');
             $path = "$root/$id";
         }
+
         return $id;
     }
 

Fișier diff suprimat deoarece este prea mare
+ 488 - 411
main/inc/lib/groupmanager.lib.php


+ 62 - 45
main/inc/lib/jpegcam/webcam_receiver.php

@@ -4,7 +4,6 @@
 /* Receives JPEG webcam submission and saves to local file. */
 /* Make sure your directory has permission to write files as your web server user! */
 require_once '../../../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 ////Add security from Chamilo
 api_protect_course_script();
@@ -13,55 +12,56 @@ api_block_anonymous_users();
 # Save the audio to a URL-accessible directory for playback.
 parse_str($_SERVER['QUERY_STRING'], $params);
 
-if(isset($params['webcamname']) && isset($params['webcamdir']) && isset($params['webcamuserid'])) {
-	$webcamname = $params['webcamname'];
-	$webcamdir = $params['webcamdir'];
-	$webcamuserid = $params['webcamuserid'];
-}
-else {
-	api_not_allowed();
-	die();
+if (isset($params['webcamname']) && isset($params['webcamdir']) && isset($params['webcamuserid'])) {
+    $webcamname = $params['webcamname'];
+    $webcamdir = $params['webcamdir'];
+    $webcamuserid = $params['webcamuserid'];
+} else {
+    api_not_allowed();
+    die();
 }
 
-if ($webcamuserid!= api_get_user_id() || api_get_user_id()==0 || $webcamuserid==0) {
-	api_not_allowed();
-	die();
+if ($webcamuserid != api_get_user_id() || api_get_user_id() == 0 || $webcamuserid == 0) {
+    api_not_allowed();
+    die();
 }
-	
+
 
 //clean
 $webcamname = Security::remove_XSS($webcamname);
 $webcamname = Database::escape_string($webcamname);
 $webcamname = addslashes(trim($webcamname));
 $webcamname = replace_dangerous_char($webcamname, 'strict');
-$webcamname = disable_dangerous_file($webcamname);
+$webcamname = FileManager::disable_dangerous_file($webcamname);
 $webcamdir = Security::remove_XSS($webcamdir);
 
 //security extension
 $ext = explode('.', $webcamname);
 $ext = strtolower($ext[sizeof($ext) - 1]);
 
-if($ext!= 'jpg'){
-	die();
+if ($ext != 'jpg') {
+    die();
 }
 
 //Do not use here check Fileinfo method because return: text/plain                //CHECK THIS BEFORE COMMIT
 
 $dirBaseDocuments = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-$saveDir=$dirBaseDocuments.$webcamdir;
+$saveDir = $dirBaseDocuments.$webcamdir;
 $current_session_id = api_get_session_id();
-$groupId=$_SESSION['_gid'];
+$groupId = $_SESSION['_gid'];
 
 //avoid duplicates
-$webcamname_to_save=$webcamname;
-$title_to_save=str_replace('_',' ',$webcamname);
-$webcamname_noex=basename($webcamname, ".jpg");
-if (file_exists($saveDir.'/'.$webcamname_noex.'.'.$ext)){ 
-		$i = 1;		
-		while (file_exists($saveDir.'/'.$webcamname_noex.'_'.$i.'.'.$ext)) $i++;
-		$webcamname_to_save = $webcamname_noex . '_' . $i . '.'.$ext;
-		$title_to_save = $webcamname_noex . '_' . $i . '.'.$ext;
-		$title_to_save = str_replace('_',' ',$title_to_save);
+$webcamname_to_save = $webcamname;
+$title_to_save = str_replace('_', ' ', $webcamname);
+$webcamname_noex = basename($webcamname, ".jpg");
+if (file_exists($saveDir.'/'.$webcamname_noex.'.'.$ext)) {
+    $i = 1;
+    while (file_exists($saveDir.'/'.$webcamname_noex.'_'.$i.'.'.$ext)) {
+        $i++;
+    }
+    $webcamname_to_save = $webcamname_noex.'_'.$i.'.'.$ext;
+    $title_to_save = $webcamname_noex.'_'.$i.'.'.$ext;
+    $title_to_save = str_replace('_', ' ', $title_to_save);
 }
 
 
@@ -71,25 +71,25 @@ $documentPath = $saveDir.'/'.$webcamname_to_save;
 //read content
 $content = file_get_contents('php://input');
 if (!$content) {
-	print "ERROR: Failed to read data\n";
-	exit();
+    print "ERROR: Failed to read data\n";
+    exit();
 }
 
 
 //make a temporal file for get the file size
-	$tmpfname = tempnam("/tmp", "CTF");
-	$handle = fopen($tmpfname, "w");
-	fwrite($handle, $content);
-	fclose($handle);
-	
-	// Check if there is enough space in the course to save the file
-	if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
-		unlink($tmpfname);
-		die(get_lang('UplNotEnoughSpace'));
-	}
-	
-	//erase temporal file
-	unlink($tmpfname);
+$tmpfname = tempnam("/tmp", "CTF");
+$handle = fopen($tmpfname, "w");
+fwrite($handle, $content);
+fclose($handle);
+
+// Check if there is enough space in the course to save the file
+if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
+    unlink($tmpfname);
+    die(get_lang('UplNotEnoughSpace'));
+}
+
+//erase temporal file
+unlink($tmpfname);
 
 //add to disk
 $fh = fopen($documentPath, 'w') or die("can't open file");
@@ -97,10 +97,27 @@ fwrite($fh, $content);
 fclose($fh);
 
 //add document to database
-	$doc_id = add_document($_course, $webcamdir.'/'.$webcamname_to_save, 'file', filesize($documentPath), $title_to_save);
-	api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
+$doc_id = FileManager::add_document(
+    $_course,
+    $webcamdir.'/'.$webcamname_to_save,
+    'file',
+    filesize($documentPath),
+    $title_to_save
+);
+api_item_property_update(
+    $_course,
+    TOOL_DOCUMENT,
+    $doc_id,
+    'DocumentAdded',
+    $_user['user_id'],
+    $groupId,
+    null,
+    null,
+    null,
+    $current_session_id
+);
 ///
-$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $documentPath;
+$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI']).'/'.$documentPath;
 print "$url\n";
 
 ?>

Fișier diff suprimat deoarece este prea mare
+ 560 - 442
main/inc/lib/message.lib.php


+ 482 - 412
main/inc/lib/nanogong.lib.php

@@ -13,305 +13,346 @@
  *
  *
  */
-class Nanogong {
+class Nanogong
+{
 
-	var $filename;
-	var $store_filename;
-	var $store_path;
-	var $params;
-	var $can_edit = false;
+    var $filename;
+    var $store_filename;
+    var $store_path;
+    var $params;
+    var $can_edit = false;
 
-	/* Files allowed to upload */
-	var $available_extensions = array('mp3', 'wav', 'ogg');
+    /* Files allowed to upload */
+    var $available_extensions = array('mp3', 'wav', 'ogg');
 
-	public function __construct($params = array()) {
-		$this->set_parameters($params);
-	}
+    public function __construct($params = array())
+    {
+        $this->set_parameters($params);
+    }
 
-	function create_user_folder() {
+    function create_user_folder()
+    {
 
-		//COURSE123/exercises/session_id/exercise_id/question_id/user_id
-		if (empty($this->store_path)) {
-			return false;
-		}
+        //COURSE123/exercises/session_id/exercise_id/question_id/user_id
+        if (empty($this->store_path)) {
+            return false;
+        }
 
         //@todo use an array to create folders
-		$folders_to_create = array();
+        $folders_to_create = array();
 
         //Trying to create the courses/COURSE123/exercises/ dir just in case
         if (!is_dir($this->store_path)) {
-			mkdir($this->store_path);
-		}
-
-		if (!is_dir($this->store_path.$this->session_id)) {
-			mkdir($this->store_path.$this->session_id);
-		}
-
-		if (!empty($this->exercise_id) && !is_dir($this->store_path.$this->session_id.'/'.$this->exercise_id)) {
-			mkdir($this->store_path.$this->session_id.'/'.$this->exercise_id);
-		}
-
-		if (!empty($this->question_id) && !is_dir($this->store_path.$this->session_id.'/'.$this->exercise_id.'/'.$this->question_id)) {
-			mkdir($this->store_path.$this->session_id.'/'.$this->exercise_id.'/'.$this->question_id);
-		}
-
-		if (!empty($this->user_id) && !is_dir($this->store_path.$this->session_id.'/'.$this->exercise_id.'/'.$this->question_id.'/'.$this->user_id)) {
-			mkdir($this->store_path.$this->session_id.'/'.$this->exercise_id.'/'.$this->question_id.'/'.$this->user_id);
-		}
-	}
-
-	/**
-	 * Setting parameters: course id, session id, etc
-	 * @param	array
-	 */
-	function set_parameters($params = array()) {
-
-		//Setting course id
-		if (isset($params['course_id'])) {
-			$this->course_id = intval($params['course_id']);
-		} else {
-			$this->course_id = $params['course_id'] = api_get_course_int_id();
-		}
-
-		//Setting course info
-		if (isset($this->course_id)) {
-			$this->course_info = api_get_course_info_by_id($this->course_id);
-		}
-
-		//Setting session id
-		if (isset($params['session_id'])) {
-			$this->session_id = intval($params['session_id']);
-		} else {
-			$this->session_id = $params['session_id'] = api_get_session_id();
-		}
-
-		//Setting user ids
-		if (isset($params['user_id'])) {
-			$this->user_id = intval($params['user_id']);
-		} else {
-			$this->user_id = $params['user_id'] = api_get_user_id();
-		}
-
-		//Setting user ids
-		if (isset($params['exercise_id'])) {
-			$this->exercise_id = intval($params['exercise_id']);
-		} else {
-			$this->exercise_id = 0;
-		}
-
-		//Setting user ids
-		if (isset($params['question_id'])) {
-			$this->question_id = intval($params['question_id']);
-		} else {
-			$this->question_id = 0;
-		}
-
-		$this->can_edit  = false;
-
-		if (api_is_allowed_to_edit()) {
-			$this->can_edit = true;
-		} else {
-			if ($this->user_id ==  api_get_user_id()) {
-				$this->can_edit = true;
-			}
-		}
-
-		//Settings the params array
-		$this->params 			= $params;
-
-		$this->store_path 		= api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/exercises/';
-
-		$this->create_user_folder();
-
-		$this->store_path 		= $this->store_path.implode('/', array($this->session_id, $this->exercise_id, $this->question_id, $this->user_id)).'/';
-		$this->filename 		= $this->generate_filename();
-		$this->store_filename 	= $this->store_path.$this->filename;
-	}
-
-	/**
-	 * Generates the filename with the next format:
-	 * (course_id)/(session_id)/(user_id)/(exercise_id)/(question_id)/(exe_id)
-	 *
-	 * @return string
-	 */
-	function generate_filename() {
-		if (!empty($this->params)) {
-			//filename
-			//course_id/session_id/user_id/exercise_id/question_id/exe_id
-			$filename_array = array($this->params['course_id'], $this->params['session_id'], $this->params['user_id'], $this->params['exercise_id'], $this->params['question_id'], $this->params['exe_id']);
-			return implode('-', $filename_array);
-		} else {
-			return api_get_unique_id();
-		}
-	}
-
-	/**
-	 * Delete audio file
-	 * @return number
-	 */
-	function delete_files() {
-		$delete_found = 0;
-		if ($this->can_edit) {
-			$file = $this->load_filename_if_exists();
-
-			$path_info = pathinfo($file);
-			foreach($this->available_extensions as $extension) {
-				$file_to_delete = $path_info['dirname'].'/'.$path_info['filename'].'.'.$extension;
-				if (is_file($file_to_delete)) {
-					unlink($file_to_delete);
-					$delete_found = 1;
-				}
-			}
-		}
-		return $delete_found;
-	}
-
-	/**
-	 *
-	 * Tricky stuff to deal with the feedback = 0 in exercises (all question per page)
-	 * @param unknown_type $exe_id
-	 */
-	function replace_with_real_exe($exe_id) {
-		$filename = null;
-		//@ugly fix
-		foreach($this->available_extensions as $extension) {
-			$items = explode('-', $this->filename);
-			$items[5] = 'temp_exe';
-			$filename = implode('-', $items);
-			if (is_file($this->store_path.$filename.'.'.$extension)) {
-				$old_name = $this->store_path.$filename.'.'.$extension;
-				$items = explode('-', $this->filename);
-				$items[5] = $exe_id;
-				$filename = $filename = implode('-', $items);
-				$new_name = $this->store_path.$filename.'.'.$extension;
-				//var_dump($old_name, $new_name);
-				rename($old_name, $new_name);
-				break;
-			}
-		}
-	}
-
-	function load_filename_if_exists($load_from_database = false) {
-		$filename = null;
-		//@ugly fix
-		foreach($this->available_extensions as $extension) {
-			if (is_file($this->store_path.$this->filename.'.'.$extension)) {
-				$filename = $this->filename.'.'.$extension;
-				break;
-			}
-		}
+            mkdir($this->store_path);
+        }
+
+        if (!is_dir($this->store_path.$this->session_id)) {
+            mkdir($this->store_path.$this->session_id);
+        }
+
+        if (!empty($this->exercise_id) && !is_dir($this->store_path.$this->session_id.'/'.$this->exercise_id)) {
+            mkdir($this->store_path.$this->session_id.'/'.$this->exercise_id);
+        }
+
+        if (!empty($this->question_id) && !is_dir(
+            $this->store_path.$this->session_id.'/'.$this->exercise_id.'/'.$this->question_id
+        )
+        ) {
+            mkdir($this->store_path.$this->session_id.'/'.$this->exercise_id.'/'.$this->question_id);
+        }
+
+        if (!empty($this->user_id) && !is_dir(
+            $this->store_path.$this->session_id.'/'.$this->exercise_id.'/'.$this->question_id.'/'.$this->user_id
+        )
+        ) {
+            mkdir($this->store_path.$this->session_id.'/'.$this->exercise_id.'/'.$this->question_id.'/'.$this->user_id);
+        }
+    }
+
+    /**
+     * Setting parameters: course id, session id, etc
+     * @param    array
+     */
+    function set_parameters($params = array())
+    {
+
+        //Setting course id
+        if (isset($params['course_id'])) {
+            $this->course_id = intval($params['course_id']);
+        } else {
+            $this->course_id = $params['course_id'] = api_get_course_int_id();
+        }
+
+        //Setting course info
+        if (isset($this->course_id)) {
+            $this->course_info = api_get_course_info_by_id($this->course_id);
+        }
+
+        //Setting session id
+        if (isset($params['session_id'])) {
+            $this->session_id = intval($params['session_id']);
+        } else {
+            $this->session_id = $params['session_id'] = api_get_session_id();
+        }
+
+        //Setting user ids
+        if (isset($params['user_id'])) {
+            $this->user_id = intval($params['user_id']);
+        } else {
+            $this->user_id = $params['user_id'] = api_get_user_id();
+        }
+
+        //Setting user ids
+        if (isset($params['exercise_id'])) {
+            $this->exercise_id = intval($params['exercise_id']);
+        } else {
+            $this->exercise_id = 0;
+        }
+
+        //Setting user ids
+        if (isset($params['question_id'])) {
+            $this->question_id = intval($params['question_id']);
+        } else {
+            $this->question_id = 0;
+        }
+
+        $this->can_edit = false;
+
+        if (api_is_allowed_to_edit()) {
+            $this->can_edit = true;
+        } else {
+            if ($this->user_id == api_get_user_id()) {
+                $this->can_edit = true;
+            }
+        }
+
+        //Settings the params array
+        $this->params = $params;
+
+        $this->store_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/exercises/';
+
+        $this->create_user_folder();
+
+        $this->store_path = $this->store_path.implode(
+            '/',
+            array($this->session_id, $this->exercise_id, $this->question_id, $this->user_id)
+        ).'/';
+        $this->filename = $this->generate_filename();
+        $this->store_filename = $this->store_path.$this->filename;
+    }
+
+    /**
+     * Generates the filename with the next format:
+     * (course_id)/(session_id)/(user_id)/(exercise_id)/(question_id)/(exe_id)
+     *
+     * @return string
+     */
+    function generate_filename()
+    {
+        if (!empty($this->params)) {
+            //filename
+            //course_id/session_id/user_id/exercise_id/question_id/exe_id
+            $filename_array = array(
+                $this->params['course_id'],
+                $this->params['session_id'],
+                $this->params['user_id'],
+                $this->params['exercise_id'],
+                $this->params['question_id'],
+                $this->params['exe_id']
+            );
+
+            return implode('-', $filename_array);
+        } else {
+            return api_get_unique_id();
+        }
+    }
+
+    /**
+     * Delete audio file
+     * @return number
+     */
+    function delete_files()
+    {
+        $delete_found = 0;
+        if ($this->can_edit) {
+            $file = $this->load_filename_if_exists();
+
+            $path_info = pathinfo($file);
+            foreach ($this->available_extensions as $extension) {
+                $file_to_delete = $path_info['dirname'].'/'.$path_info['filename'].'.'.$extension;
+                if (is_file($file_to_delete)) {
+                    unlink($file_to_delete);
+                    $delete_found = 1;
+                }
+            }
+        }
+
+        return $delete_found;
+    }
+
+    /**
+     *
+     * Tricky stuff to deal with the feedback = 0 in exercises (all question per page)
+     * @param unknown_type $exe_id
+     */
+    function replace_with_real_exe($exe_id)
+    {
+        $filename = null;
+        //@ugly fix
+        foreach ($this->available_extensions as $extension) {
+            $items = explode('-', $this->filename);
+            $items[5] = 'temp_exe';
+            $filename = implode('-', $items);
+            if (is_file($this->store_path.$filename.'.'.$extension)) {
+                $old_name = $this->store_path.$filename.'.'.$extension;
+                $items = explode('-', $this->filename);
+                $items[5] = $exe_id;
+                $filename = $filename = implode('-', $items);
+                $new_name = $this->store_path.$filename.'.'.$extension;
+                //var_dump($old_name, $new_name);
+                rename($old_name, $new_name);
+                break;
+            }
+        }
+    }
+
+    function load_filename_if_exists($load_from_database = false)
+    {
+        $filename = null;
+        //@ugly fix
+        foreach ($this->available_extensions as $extension) {
+            if (is_file($this->store_path.$this->filename.'.'.$extension)) {
+                $filename = $this->filename.'.'.$extension;
+                break;
+            }
+        }
 
-		//temp_exe
-		if ($load_from_database) {
+        //temp_exe
+        if ($load_from_database) {
 
-			//Load the real filename just if exists
-			if (isset($this->params['exe_id']) && isset($this->params['user_id']) && isset($this->params['question_id']) && isset($this->params['session_id']) && isset($this->params['course_id'])) {
-				$attempt_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-				$sql = "SELECT filename FROM $attempt_table
+            //Load the real filename just if exists
+            if (isset($this->params['exe_id']) && isset($this->params['user_id']) && isset($this->params['question_id']) && isset($this->params['session_id']) && isset($this->params['course_id'])) {
+                $attempt_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+                $sql = "SELECT filename FROM $attempt_table
 								WHERE 	exe_id 		= ".$this->params['exe_id']." AND
 										user_id 	= ".$this->params['user_id']." AND
 										question_id = ".$this->params['question_id']." AND
 										session_id 	= ".$this->params['session_id']." AND
 										course_code = '".$this->course_info['code']."' LIMIT 1";
-				$result = Database::query($sql);
-				$result = Database::fetch_row($result,'ASSOC');
+                $result = Database::query($sql);
+                $result = Database::fetch_row($result, 'ASSOC');
 
-				if (isset($result) && isset($result[0]) && !empty($result[0])) {
-					$filename = $result[0];
-				}
-			}
-		}
-
-		if (is_file($this->store_path.$filename)) {
-			return $this->store_path.$filename;
-		}
-		return null;
-	}
-
-	/**
-	 *
-	 * Get the URL of the file
-	 * path courses/XXX/exercises/(session_id)/(exercise_id)/(question_id)/(user_id)/
-	 *
-	 * @return string
-	 */
-	function get_public_url($force_download = 0) {
-		$params = $this->get_params(true);
-		$url = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=get_file&download='.$force_download.'&'.$params;
-		$params = $this->get_params();
-		$filename = basename($this->load_filename_if_exists());
-		$url = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/exercises/'.
-		$params['session_id'].'/'.$params['exercise_id'].'/'.$params['question_id'].'/'.$params['user_id'].'/'.$filename;
-		return $url;
-	}
-
-	/**
-	 * Uploads the nanogong wav file
-	 */
-	public function upload_file($is_nano = false) {
-		require_once api_get_path(LIBRARY_PATH).'document.lib.php';
-		if (!empty($_FILES)) {
-			$upload_ok = process_uploaded_file($_FILES['file'], false);
-
-			if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
-				return 0;
-			}
+                if (isset($result) && isset($result[0]) && !empty($result[0])) {
+                    $filename = $result[0];
+                }
+            }
+        }
+
+        if (is_file($this->store_path.$filename)) {
+            return $this->store_path.$filename;
+        }
+
+        return null;
+    }
+
+    /**
+     *
+     * Get the URL of the file
+     * path courses/XXX/exercises/(session_id)/(exercise_id)/(question_id)/(user_id)/
+     *
+     * @return string
+     */
+    function get_public_url($force_download = 0)
+    {
+        $params = $this->get_params(true);
+        $url = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=get_file&download='.$force_download.'&'.$params;
+        $params = $this->get_params();
+        $filename = basename($this->load_filename_if_exists());
+        $url = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/exercises/'.
+            $params['session_id'].'/'.$params['exercise_id'].'/'.$params['question_id'].'/'.$params['user_id'].'/'.$filename;
+
+        return $url;
+    }
+
+    /**
+     * Uploads the nanogong wav file
+     */
+    public function upload_file($is_nano = false)
+    {
+        require_once api_get_path(LIBRARY_PATH).'document.lib.php';
+        if (!empty($_FILES)) {
+            $upload_ok = FileManager::process_uploaded_file($_FILES['file'], false);
+
+            if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
+                return 0;
+            }
 
-			if ($upload_ok) {
-				// Check if there is enough space to save the file
-				if (!DocumentManager::enough_space($_FILES['file']['size'], DocumentManager::get_course_quota())) {
-					return 0;
-				}
+            if ($upload_ok) {
+                // Check if there is enough space to save the file
+                if (!DocumentManager::enough_space($_FILES['file']['size'], DocumentManager::get_course_quota())) {
+                    return 0;
+                }
 
-				//first we delete everything before uploading the file
-				$this->delete_files();
+                //first we delete everything before uploading the file
+                $this->delete_files();
 
-				//Reload the filename variable
-				$file_name = add_ext_on_mime($_FILES['file']['name'], $_FILES['file']['type']);
-				$file_name = strtolower($file_name);
-				$file_info = pathinfo($file_name);
+                //Reload the filename variable
+                $file_name = FileManager::add_ext_on_mime($_FILES['file']['name'], $_FILES['file']['type']);
+                $file_name = strtolower($file_name);
+                $file_info = pathinfo($file_name);
 
-				if ($is_nano == true) {
-					$file_info['extension'] = 'wav';
-				}
+                if ($is_nano == true) {
+                    $file_info['extension'] = 'wav';
+                }
 
-				$file_name = $this->filename.'.'.$file_info['extension'];
+                $file_name = $this->filename.'.'.$file_info['extension'];
 
-				if (in_array($file_info['extension'], $this->available_extensions)) {
-					if (move_uploaded_file($_FILES['file']['tmp_name'], $this->store_path.$file_name)) {
-						$this->store_filename = $this->store_path.$file_name;
-						//error_log('saved');
-						return 1;
-					}
-				}
-			}
-		}
-		return 0;
-	}
-
-	/**
-	 * Show the audio file + a button to download
-	 *
-	 */
-	public function show_audio_file($show_delete_button = false) {
-		$html = '';
-		$file_path = $this->load_filename_if_exists();
-
-		if (!empty($file_path)) {
-			$url = $this->get_public_url(true);
-			$actions = Display::url(Display::return_icon('save.png', get_lang('Download'), array(), ICON_SIZE_SMALL), $url, array('target'=>'_blank'));
-			$download_button = Display::url(get_lang('Download'), $url, array('class' =>'btn'));
-
-			if ($show_delete_button) {
-				$actions .= ' '.Display::url(Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL), "#", array('onclick'=>'delete_file();'));
-			}
+                if (in_array($file_info['extension'], $this->available_extensions)) {
+                    if (move_uploaded_file($_FILES['file']['tmp_name'], $this->store_path.$file_name)) {
+                        $this->store_filename = $this->store_path.$file_name;
 
-			$basename = basename($file_path);
-			$path_info = pathinfo($basename);
+                        //error_log('saved');
+                        return 1;
+                    }
+                }
+            }
+        }
+
+        return 0;
+    }
+
+    /**
+     * Show the audio file + a button to download
+     *
+     */
+    public function show_audio_file($show_delete_button = false)
+    {
+        $html = '';
+        $file_path = $this->load_filename_if_exists();
+
+        if (!empty($file_path)) {
+            $url = $this->get_public_url(true);
+            $actions = Display::url(
+                Display::return_icon('save.png', get_lang('Download'), array(), ICON_SIZE_SMALL),
+                $url,
+                array('target' => '_blank')
+            );
+            $download_button = Display::url(get_lang('Download'), $url, array('class' => 'btn'));
+
+            if ($show_delete_button) {
+                $actions .= ' '.Display::url(
+                    Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL),
+                    "#",
+                    array('onclick' => 'delete_file();')
+                );
+            }
 
-			if ($path_info['extension'] == 'wav') {
+            $basename = basename($file_path);
+            $path_info = pathinfo($basename);
 
-				$html .= '<script>
+            if ($path_info['extension'] == 'wav') {
+
+                $html .= '<script>
 				$(document).ready( function() {
 					var java_enabled = navigator.javaEnabled();
 
@@ -325,84 +366,92 @@ class Nanogong {
 				});
 				</script>';
 
-				$html .= '<div id="nanogong_player_id" class="nanogong_player_container">';
-					$html .= '<div class="action_player">'.$actions.'</div>';
-					$html .= '<div class="nanogong_player">';
-						$html .= '<applet id="nanogong_player" archive="'.api_get_path(WEB_LIBRARY_PATH).'nanogong/nanogong.jar" code="gong.NanoGong" width="250" height="40" ALIGN="middle">';
-
-						$html .= '<param name="ShowRecordButton" value="false" />'; // default true
-						$html .= '<param name="ShowSaveButton" value="false" />'; //you can save in local computer | (default true)
-						//echo '<param name="ShowSpeedButton" value="false" />'; // default true
-						//echo '<param name="ShowAudioLevel" value="false" />'; //  it displays the audiometer | (default true)
-						$html .= '<param name="ShowTime" value="true" />'; // default false
-						$html .= '<param name="Color" value="#FFFFFF" />';
-						//echo '<param name="StartTime" value="10.5" />';
-						//echo '<param name="EndTime" value="65" />';
-						$html .= '<param name="AudioFormat" value="ImaADPCM" />';// ImaADPCM (more speed), Speex (more compression)|(default Speex)
-						//$html .= '<param name="AudioFormat" value="Speex" />';// ImaADPCM (more speed), Speex (more compression)|(default Speex)
-
-						//Quality for ImaADPCM (low 8000, medium 11025, normal 22050, hight 44100) OR Quality for Speex (low 8000, medium 16000, normal 32000, hight 44100) | (default 44100)
-						//echo '<param name="SamplingRate" value="32000" />';
-						//echo '<param name="MaxDuration" value="60" />';
-						$html .=  '<param name="SoundFileURL" value="'.$url.'" />';//load a file |(default "")
-						$html .= '</applet>';
-					$html .= '</div>';
-				$html .= '</div>';
-
-				$html .= '<div id="nanogong_warning">'.Display::return_message(get_lang('BrowserDoesNotSupportNanogongPlayer'),'warning').$download_button.'</div>';
-
-			} elseif(in_array($path_info['extension'],array('mp3', 'ogg','wav'))) {
-				$js_path 		= api_get_path(WEB_LIBRARY_PATH).'javascript/';
-
-				$html .= '<link rel="stylesheet" href="'.$js_path.'jquery-jplayer/skins/blue/jplayer.blue.monday.css" type="text/css">';
+                $html .= '<div id="nanogong_player_id" class="nanogong_player_container">';
+                $html .= '<div class="action_player">'.$actions.'</div>';
+                $html .= '<div class="nanogong_player">';
+                $html .= '<applet id="nanogong_player" archive="'.api_get_path(
+                    WEB_LIBRARY_PATH
+                ).'nanogong/nanogong.jar" code="gong.NanoGong" width="250" height="40" ALIGN="middle">';
+
+                $html .= '<param name="ShowRecordButton" value="false" />'; // default true
+                $html .= '<param name="ShowSaveButton" value="false" />'; //you can save in local computer | (default true)
+                //echo '<param name="ShowSpeedButton" value="false" />'; // default true
+                //echo '<param name="ShowAudioLevel" value="false" />'; //  it displays the audiometer | (default true)
+                $html .= '<param name="ShowTime" value="true" />'; // default false
+                $html .= '<param name="Color" value="#FFFFFF" />';
+                //echo '<param name="StartTime" value="10.5" />';
+                //echo '<param name="EndTime" value="65" />';
+                $html .= '<param name="AudioFormat" value="ImaADPCM" />'; // ImaADPCM (more speed), Speex (more compression)|(default Speex)
+                //$html .= '<param name="AudioFormat" value="Speex" />';// ImaADPCM (more speed), Speex (more compression)|(default Speex)
+
+                //Quality for ImaADPCM (low 8000, medium 11025, normal 22050, hight 44100) OR Quality for Speex (low 8000, medium 16000, normal 32000, hight 44100) | (default 44100)
+                //echo '<param name="SamplingRate" value="32000" />';
+                //echo '<param name="MaxDuration" value="60" />';
+                $html .= '<param name="SoundFileURL" value="'.$url.'" />'; //load a file |(default "")
+                $html .= '</applet>';
+                $html .= '</div>';
+                $html .= '</div>';
+
+                $html .= '<div id="nanogong_warning">'.Display::return_message(
+                    get_lang('BrowserDoesNotSupportNanogongPlayer'),
+                    'warning'
+                ).$download_button.'</div>';
+
+            } elseif (in_array($path_info['extension'], array('mp3', 'ogg', 'wav'))) {
+                $js_path = api_get_path(WEB_LIBRARY_PATH).'javascript/';
+
+                $html .= '<link rel="stylesheet" href="'.$js_path.'jquery-jplayer/skins/blue/jplayer.blue.monday.css" type="text/css">';
                 //$html .= '<link rel="stylesheet" href="' . $js_path . 'jquery-jplayer/skins/chamilo/jplayer.blue.monday.css" type="text/css">';
-				$html .= '<script type="text/javascript" src="'.$js_path.'jquery-jplayer/jquery.jplayer.min.js"></script>';
+                $html .= '<script type="text/javascript" src="'.$js_path.'jquery-jplayer/jquery.jplayer.min.js"></script>';
 
-				$html .= '<div class="nanogong_player"></div>';
-				$html .= '<br /><div class="action_player">'.$actions.'</div><br /><br /><br />';
+                $html .= '<div class="nanogong_player"></div>';
+                $html .= '<br /><div class="action_player">'.$actions.'</div><br /><br /><br />';
 
-                $params = array('url' => $url,
-                                'extension' =>$path_info['extension'],
-                                'count'=> 1
-                 );
+                $params = array(
+                    'url' => $url,
+                    'extension' => $path_info['extension'],
+                    'count' => 1
+                );
                 $jquery = DocumentManager::generate_jplayer_jquery($params);
 
 
-				$html .= '<script>
+                $html .= '<script>
 				$(document).ready( function() {
 				    //Experimental changes to preview mp3, ogg files
 				     '.$jquery.'
 				});
 				</script>';
-				$html .= DocumentManager::generate_media_preview(1, 'advanced');
-			}
-		}
+                $html .= DocumentManager::generate_media_preview(1, 'advanced');
+            }
+        }
+
         return $html;
-	}
+    }
 
 
-	/*
-	var filename = document.getElementById("audio_title").value+".wav";
-	var filename = filename.replace(/\s/g, "_");//replace spaces by _
-	var filename = encodeURIComponent(filename);
-	var filepath="'.urlencode($filepath).'";
-	var dir="'.urlencode($dir).'";
-	var course_code="'.urlencode($course_code).'";
-	var urlnanogong="'.$url.'?filename="+filename+"&filepath="+filepath+"&dir="+dir+"&course_code="+course_code;
-	*/
+    /*
+    var filename = document.getElementById("audio_title").value+".wav";
+    var filename = filename.replace(/\s/g, "_");//replace spaces by _
+    var filename = encodeURIComponent(filename);
+    var filepath="'.urlencode($filepath).'";
+    var dir="'.urlencode($dir).'";
+    var course_code="'.urlencode($course_code).'";
+    var urlnanogong="'.$url.'?filename="+filename+"&filepath="+filepath+"&dir="+dir+"&course_code="+course_code;
+    */
 
-	/**
-	 * Returns the nanogong javascript code
-	 * @return string
-	 */
-	function return_js() {
-		$params = $this->get_params(true);
-		$url = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=save_file&'.$params.'&is_nano=1';
-		$url_load_file = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=show_audio&'.$params;
+    /**
+     * Returns the nanogong javascript code
+     * @return string
+     */
+    function return_js()
+    {
+        $params = $this->get_params(true);
+        $url = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=save_file&'.$params.'&is_nano=1';
+        $url_load_file = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=show_audio&'.$params;
 
-		$url_delete = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=delete&'.$params;
+        $url_delete = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=delete&'.$params;
 
-		$js =  '<script language="javascript">
+        $js = '<script language="javascript">
 
 			//lang vars
 
@@ -518,106 +567,127 @@ class Nanogong {
 				return false;
 			}
 			</script>';
-		return $js;
-	}
 
-	/**
-	 * Returns the HTML form to upload a nano file or upload a file
-	 */
-	function return_form($message = null) {
+        return $js;
+    }
 
-		$params = $this->get_params(true);
-		$url = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=save_file&'.$params;
+    /**
+     * Returns the HTML form to upload a nano file or upload a file
+     */
+    function return_form($message = null)
+    {
 
-		//check browser support and load form
-		$array_browser = api_browser_support('check_browser');
+        $params = $this->get_params(true);
+        $url = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=save_file&'.$params;
 
-		$preview_file = $this->show_audio_file(true, true);
+        //check browser support and load form
+        $array_browser = api_browser_support('check_browser');
 
-		$preview_file = Display::div($preview_file, array('id' => 'preview', 'style' => 'text-align:center; padding-left: 25px;'));
+        $preview_file = $this->show_audio_file(true, true);
 
-		$html .= '<center>';
+        $preview_file = Display::div(
+            $preview_file,
+            array('id' => 'preview', 'style' => 'text-align:center; padding-left: 25px;')
+        );
 
-		//Use normal upload file
-		$html .= Display::return_icon('microphone.png', get_lang('PressRecordButton'),'', ICON_SIZE_BIG);
-		$html .='<br />';
+        $html .= '<center>';
 
-		$html .= '<div id="nanogong_div">';
+        //Use normal upload file
+        $html .= Display::return_icon('microphone.png', get_lang('PressRecordButton'), '', ICON_SIZE_BIG);
+        $html .= '<br />';
 
-		$html .= '<applet id="nanogong" archive="'.api_get_path(WEB_LIBRARY_PATH).'nanogong/nanogong.jar" code="gong.NanoGong" width="250" height="40" align="middle">';
-		//echo '<param name="ShowRecordButton" value="false" />'; // default true
-		// echo '<param name="ShowSaveButton" value="false" />'; //you can save in local computer | (default true)
-		//echo '<param name="ShowSpeedButton" value="false" />'; // default true
-		//echo '<param name="ShowAudioLevel" value="false" />'; //  it displays the audiometer | (default true)
-		$html .= '<param name="ShowTime" value="true" />'; // default false
-		$html .= '<param name="Color" value="#FFFFFF" />'; // default #FFFFFF
-		//echo '<param name="StartTime" value="10.5" />';
-		//echo '<param name="EndTime" value="65" />';
-		$html .= '<param name="AudioFormat" value="ImaADPCM" />';// ImaADPCM (more speed), Speex (more compression)|(default Speex)
-		//$html .= '<param name="AudioFormat" value="Speex" />';// ImaADPCM (more speed), Speex (more compression)|(default Speex)
+        $html .= '<div id="nanogong_div">';
 
-		//echo '<param name="SamplingRate" value="32000" />';//Quality for ImaADPCM (low 8000, medium 11025, normal 22050, hight 44100) OR Quality for Speex (low 8000, medium 16000, normal 32000, hight 44100) | (default 44100)
-		//echo '<param name="MaxDuration" value="60" />';
-		//echo '<param name="SoundFileURL" value="http://somewhere.com/mysoundfile.wav" />';//load a file |(default "")
-		$html .= '</applet>';
+        $html .= '<applet id="nanogong" archive="'.api_get_path(
+            WEB_LIBRARY_PATH
+        ).'nanogong/nanogong.jar" code="gong.NanoGong" width="250" height="40" align="middle">';
+        //echo '<param name="ShowRecordButton" value="false" />'; // default true
+        // echo '<param name="ShowSaveButton" value="false" />'; //you can save in local computer | (default true)
+        //echo '<param name="ShowSpeedButton" value="false" />'; // default true
+        //echo '<param name="ShowAudioLevel" value="false" />'; //  it displays the audiometer | (default true)
+        $html .= '<param name="ShowTime" value="true" />'; // default false
+        $html .= '<param name="Color" value="#FFFFFF" />'; // default #FFFFFF
+        //echo '<param name="StartTime" value="10.5" />';
+        //echo '<param name="EndTime" value="65" />';
+        $html .= '<param name="AudioFormat" value="ImaADPCM" />'; // ImaADPCM (more speed), Speex (more compression)|(default Speex)
+        //$html .= '<param name="AudioFormat" value="Speex" />';// ImaADPCM (more speed), Speex (more compression)|(default Speex)
 
-		$html .= '<br /><br /><br />';
-
-        $html .= '<form name="form_nanogong_advanced">';
-		$html .= '<input type="hidden" name="is_nano" value="1">';
-		$html .= '<a href="#" class="btn"  onclick="send_voice()" />'.get_lang('SendRecord').'</a>';
-		$html .= '</form></div>';
+        //echo '<param name="SamplingRate" value="32000" />';//Quality for ImaADPCM (low 8000, medium 11025, normal 22050, hight 44100) OR Quality for Speex (low 8000, medium 16000, normal 32000, hight 44100) | (default 44100)
+        //echo '<param name="MaxDuration" value="60" />';
+        //echo '<param name="SoundFileURL" value="http://somewhere.com/mysoundfile.wav" />';//load a file |(default "")
+        $html .= '</applet>';
 
+        $html .= '<br /><br /><br />';
 
-        $html .= Display::url(get_lang('ProblemsRecordingUploadYourOwnAudioFile'), 'javascript:void(0)', array('onclick' => 'show_simple_upload_form();'));
-
-		$html .= '<br /><br /><div id="no_nanogong_div">';
-		//$html .= Display::return_message(get_lang('BrowserNotSupportNanogongSend'), 'warning');
-		$html .= '<form id="form_nanogong_simple" class="form-search" action="'.$url.'" name="form_nanogong" method="POST" enctype="multipart/form-data">';
-		$html .= '<input type="file" name="file">';
-		$html .= '<a href="#" class="btn"  onclick="upload_file()" />'.get_lang('UploadFile').'</a>';
-		$html .= '</form>';
+        $html .= '<form name="form_nanogong_advanced">';
+        $html .= '<input type="hidden" name="is_nano" value="1">';
+        $html .= '<a href="#" class="btn"  onclick="send_voice()" />'.get_lang('SendRecord').'</a>';
+        $html .= '</form></div>';
+
+
+        $html .= Display::url(
+            get_lang('ProblemsRecordingUploadYourOwnAudioFile'),
+            'javascript:void(0)',
+            array('onclick' => 'show_simple_upload_form();')
+        );
+
+        $html .= '<br /><br /><div id="no_nanogong_div">';
+        //$html .= Display::return_message(get_lang('BrowserNotSupportNanogongSend'), 'warning');
+        $html .= '<form id="form_nanogong_simple" class="form-search" action="'.$url.'" name="form_nanogong" method="POST" enctype="multipart/form-data">';
+        $html .= '<input type="file" name="file">';
+        $html .= '<a href="#" class="btn"  onclick="upload_file()" />'.get_lang('UploadFile').'</a>';
+        $html .= '</form>';
         $html .= '</div>';
 
 
-		$html .= '</center>';
+        $html .= '</center>';
 
 
-		$html .= '<div style="display:none" id="status_ok" class="confirmation-message"></div><div style="display:none" id="status_warning" class="warning-message"></div>';
+        $html .= '<div style="display:none" id="status_ok" class="confirmation-message"></div><div style="display:none" id="status_warning" class="warning-message"></div>';
 
-		$html .= '<div id="messages">'.$message.'</div>';
+        $html .= '<div id="messages">'.$message.'</div>';
 
-		$html .= $preview_file;
+        $html .= $preview_file;
 
 
-		return $html;
-	}
-
-	function get_params($return_as_query = false) {
-		if (empty($this->params)) {
-			return false;
-		}
-		if ($return_as_query) {
-			return http_build_query($this->params);
-		}
-		return $this->params;
-	}
-
-	function get_param_value($attribute) {
-		if (isset($this->params[$attribute])) {
-			return $this->params[$attribute];
-		}
-	}
+        return $html;
+    }
+
+    function get_params($return_as_query = false)
+    {
+        if (empty($this->params)) {
+            return false;
+        }
+        if ($return_as_query) {
+            return http_build_query($this->params);
+        }
+
+        return $this->params;
+    }
+
+    function get_param_value($attribute)
+    {
+        if (isset($this->params[$attribute])) {
+            return $this->params[$attribute];
+        }
+    }
+
+    /**
+     * Show a button to load the form
+     * @return string
+     */
+    function show_button()
+    {
+        $params_string = $this->get_params(true);
+        $html .= '<br />'.Display::url(
+            get_lang('RecordAnswer'),
+            api_get_path(
+                WEB_AJAX_PATH
+            ).'nanogong.ajax.php?a=show_form&'.$params_string.'&TB_iframe=true&height=400&width=500',
+            array('class' => 'btn thickbox')
+        );
+        $html .= '<br /><br />'.Display::return_message(get_lang('UseTheMessageBelowToAddSomeComments'));
 
-	/**
-	 * Show a button to load the form
-	 * @return string
-	 */
-	function show_button() {
-		$params_string = $this->get_params(true);
-		$html .= '<br />'.Display::url(get_lang('RecordAnswer'),api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=show_form&'.$params_string.'&TB_iframe=true&height=400&width=500',
-						array('class'=>'btn thickbox'));
-		$html .= '<br /><br />'.Display::return_message(get_lang('UseTheMessageBelowToAddSomeComments'));
-		return $html;
-	}
+        return $html;
+    }
 }

+ 50 - 38
main/inc/lib/nanogong/receiver.php

@@ -2,56 +2,57 @@
 /* For licensing terms, see /license.txt */
 
 /**
- *	This file allows creating new svg and png documents with an online editor.
+ *    This file allows creating new svg and png documents with an online editor.
  *
- *	@package chamilo.document
+ * @package chamilo.document
  *
  * @author Juan Carlos Raña Trabado
  * @since 5/mar/2011
-*/
+ */
 /**
  * Code
  */
 require_once '../../../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 
-	api_protect_course_script();
-	api_block_anonymous_users();
+api_protect_course_script();
+api_block_anonymous_users();
 
-if (!isset($_GET['filename']) || !isset($_GET['filepath']) || !isset($_GET['dir']) || !isset($_GET['course_code'])|| !isset($_GET['nano_group_id']) || !isset($_GET['nano_session_id']) || !isset($_GET['nano_user_id'])){
-	echo 'Error. Not allowed';
-	exit;
+if (!isset($_GET['filename']) || !isset($_GET['filepath']) || !isset($_GET['dir']) || !isset($_GET['course_code']) || !isset($_GET['nano_group_id']) || !isset($_GET['nano_session_id']) || !isset($_GET['nano_user_id'])) {
+    echo 'Error. Not allowed';
+    exit;
+}
+if (!is_uploaded_file($_FILES['voicefile']['tmp_name'])) {
+    exit;
 }
-if (!is_uploaded_file($_FILES['voicefile']['tmp_name'])) exit;
 
 //clean
-$nano_user_id=Security::remove_XSS($_GET['nano_user_id']);
-$nano_group_id=Security::remove_XSS($_GET['nano_group_id']);
-$nano_session_id=Security::remove_XSS($_GET['nano_session_id']);
+$nano_user_id = Security::remove_XSS($_GET['nano_user_id']);
+$nano_group_id = Security::remove_XSS($_GET['nano_group_id']);
+$nano_session_id = Security::remove_XSS($_GET['nano_session_id']);
 
-$filename=Security::remove_XSS($_GET['filename']);
-$filename=urldecode($filename);
-$filepath=Security::remove_XSS(urldecode($_GET['filepath']));
-$dir=Security::remove_XSS(urldecode($_GET['dir']));
+$filename = Security::remove_XSS($_GET['filename']);
+$filename = urldecode($filename);
+$filepath = Security::remove_XSS(urldecode($_GET['filepath']));
+$dir = Security::remove_XSS(urldecode($_GET['dir']));
 
 $course_code = Security::remove_XSS(urldecode($_GET['course_code']));
-$_course=api_get_course_info($course_code);
+$_course = api_get_course_info($course_code);
 
 $filename = trim($_GET['filename']);
 $filename = Security::remove_XSS($filename);
 $filename = Database::escape_string($filename);
-$filename = replace_dangerous_char($filename, $strict = 'loose');// or strict
-$filename = disable_dangerous_file($filename);
+$filename = replace_dangerous_char($filename, $strict = 'loose'); // or strict
+$filename = FileManager::disable_dangerous_file($filename);
 
-$title= trim(str_replace('_chnano_.','.',$filename));//hide nanogong wav tag at title
-$title= str_replace('_',' ',$title);
+$title = trim(str_replace('_chnano_.', '.', $filename)); //hide nanogong wav tag at title
+$title = str_replace('_', ' ', $title);
 
 //
 $documentPath = $filepath.$filename;
 
-if ($nano_user_id!= api_get_user_id() || api_get_user_id()==0 || $nano_user_id==0) {
-	echo 'Not allowed';
-	exit;
+if ($nano_user_id != api_get_user_id() || api_get_user_id() == 0 || $nano_user_id == 0) {
+    echo 'Not allowed';
+    exit;
 }
 
 
@@ -59,20 +60,31 @@ if ($nano_user_id!= api_get_user_id() || api_get_user_id()==0 || $nano_user_id==
 
 // Check if there is enough space in the course to save the file
 if (!DocumentManager::enough_space(filesize($_FILES['voicefile']['tmp_name']), DocumentManager::get_course_quota())) {
-	die(get_lang('UplNotEnoughSpace'));
+    die(get_lang('UplNotEnoughSpace'));
 }
 
-if (!file_exists($documentPath)){
-	//add document to disk
-	move_uploaded_file($_FILES['voicefile']['tmp_name'], $documentPath);
-	
-	//add document to database
-	$current_session_id = $nano_session_id;
-	$groupId=$nano_group_id;
-	$file_size = filesize($documentPath);
-	$relativeUrlPath=$dir;		
-	$doc_id = add_document($_course, $relativeUrlPath.$filename, 'file', filesize($documentPath), $title);
-	api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $nano_user_id, $groupId, null, null, null, $current_session_id);
+if (!file_exists($documentPath)) {
+    //add document to disk
+    move_uploaded_file($_FILES['voicefile']['tmp_name'], $documentPath);
+
+    //add document to database
+    $current_session_id = $nano_session_id;
+    $groupId = $nano_group_id;
+    $file_size = filesize($documentPath);
+    $relativeUrlPath = $dir;
+    $doc_id = FileManager::add_document($_course, $relativeUrlPath.$filename, 'file', filesize($documentPath), $title);
+    api_item_property_update(
+        $_course,
+        TOOL_DOCUMENT,
+        $doc_id,
+        'DocumentAdded',
+        $nano_user_id,
+        $groupId,
+        null,
+        null,
+        null,
+        $current_session_id
+    );
 } else {
-	return get_lang('FileExistRename');
+    return get_lang('FileExistRename');
 }

+ 60 - 35
main/inc/lib/search/xapian/XapianIndexer.class.php

@@ -9,13 +9,14 @@
  */
 
 require_once 'xapian.php';
-require_once dirname(__FILE__) . '/../IndexableChunk.class.php';
+require_once dirname(__FILE__).'/../IndexableChunk.class.php';
 
 /**
  * Abstract helper class
  * @package chamilo.include.search
  */
-abstract class XapianIndexer {
+abstract class XapianIndexer
+{
     /* XapianWritableDatabase */
 
     protected $db;
@@ -33,7 +34,8 @@ abstract class XapianIndexer {
      * Chamilo languages and Xapian languages (through hardcoding)
      * @return  array  Array of languages codes -> Xapian languages
      */
-    public final function xapian_languages() {
+    public final function xapian_languages()
+    {
         /* http://xapian.org/docs/apidoc/html/classXapian_1_1Stem.html */
         return array(
             'none' => 'none', //don't stem terms
@@ -60,14 +62,18 @@ abstract class XapianIndexer {
     /**
      * Connect to the database, and create it if it doesn't exist
      */
-    function connectDb($path = NULL, $dbMode = NULL, $lang = 'english') {
-        if ($this->db != NULL)
+    function connectDb($path = null, $dbMode = null, $lang = 'english')
+    {
+        if ($this->db != null) {
             return $this->db;
-        if ($dbMode == NULL)
+        }
+        if ($dbMode == null) {
             $dbMode = Xapian::DB_CREATE_OR_OPEN;
+        }
 
-        if ($path == NULL)
-            $path = api_get_path(SYS_PATH) . 'searchdb/';
+        if ($path == null) {
+            $path = api_get_path(SYS_PATH).'searchdb/';
+        }
 
         try {
             $this->db = new XapianWritableDatabase($path, $dbMode);
@@ -82,6 +88,7 @@ abstract class XapianIndexer {
             return $this->db;
         } catch (Exception $e) {
             Display::display_error_message($e->getMessage());
+
             return 1;
         }
     }
@@ -90,7 +97,8 @@ abstract class XapianIndexer {
      * Simple getter for the db attribute
      * @return  object  The db attribute
      */
-    function getDb() {
+    function getDb()
+    {
         return $this->db;
     }
 
@@ -99,7 +107,8 @@ abstract class XapianIndexer {
      * @param  string  Chunk of text
      * @return  void
      */
-    function addChunk($chunk) {
+    function addChunk($chunk)
+    {
         $this->chunks[] = $chunk;
     }
 
@@ -108,7 +117,8 @@ abstract class XapianIndexer {
      *
      * @return integer  New Xapian document ID or NULL upon failure
      */
-    function index() {
+    function index()
+    {
         try {
             if (!empty($this->chunks)) {
                 foreach ($this->chunks as $chunk) {
@@ -117,7 +127,7 @@ abstract class XapianIndexer {
                     if (!empty($chunk->terms)) {
                         foreach ($chunk->terms as $term) {
                             /* FIXME: think of getting weight */
-                            $doc->add_term($term['flag'] . $term['name'], 1);
+                            $doc->add_term($term['flag'].$term['name'], 1);
                         }
                     }
 
@@ -128,7 +138,7 @@ abstract class XapianIndexer {
                         }
                     }
                     $doc->set_data($chunk->xapian_data, 1);
-                    $did = $this->db->add_document($doc);
+                    $did = $this->db->FileManager::add_document($doc);
 
                     //write to disk
                     $this->db->flush();
@@ -148,8 +158,9 @@ abstract class XapianIndexer {
      * @param   int     did     Xapian::docid
      * @return  mixed   XapianDocument, or false on error
      */
-    function get_document($did) {
-        if ($this->db == NULL) {
+    function get_document($did)
+    {
+        if ($this->db == null) {
             $this->connectDb();
         }
         try {
@@ -158,6 +169,7 @@ abstract class XapianIndexer {
             //Display::display_error_message($e->getMessage());
             return false;
         }
+
         return $docid;
     }
 
@@ -167,15 +179,17 @@ abstract class XapianIndexer {
      * @param XapianDocument $doc xapian document to push into the db
      * @return mixed xapian document data or FALSE if error
      */
-    function get_document_data($doc) {
-        if ($this->db == NULL) {
+    function get_document_data($doc)
+    {
+        if ($this->db == null) {
             $this->connectDb();
         }
         try {
             if (!is_a($doc, 'XapianDocument')) {
-                return FALSE;
+                return false;
             }
             $doc_data = $doc->get_data();
+
             return $doc_data;
         } catch (Exception $e) {
             //Display::display_error_message($e->getMessage());
@@ -190,7 +204,8 @@ abstract class XapianIndexer {
      * @param   array   terms   New terms of the document
      * @return  boolean false on error
      */
-    function update_terms($did, $terms, $prefix) {
+    function update_terms($did, $terms, $prefix)
+    {
         $doc = $this->get_document($did);
         if ($doc === false) {
             return false;
@@ -198,10 +213,11 @@ abstract class XapianIndexer {
         $doc->clear_terms();
         foreach ($terms as $term) {
             //add directly
-            $doc->add_term($prefix . $term, 1);
+            $doc->add_term($prefix.$term, 1);
         }
         $this->db->replace_document($did, $doc);
         $this->db->flush();
+
         return true;
     }
 
@@ -210,13 +226,14 @@ abstract class XapianIndexer {
      *
      * @param int   did     Xapian::docid
      */
-    function remove_document($did) {
-        if ($this->db == NULL) {
+    function remove_document($did)
+    {
+        if ($this->db == null) {
             $this->connectDb();
         }
         if (is_numeric($did) && $did > 0) {
             $doc = $this->get_document($did);
-            if ($doc !== FALSE) {
+            if ($doc !== false) {
                 $this->db->delete_document($did);
                 $this->db->flush();
             }
@@ -230,14 +247,16 @@ abstract class XapianIndexer {
      * @param XapianDocument $doc The xapian document where to add the term
      * @return  mixed   XapianDocument, or false on error
      */
-    function add_term_to_doc($term, $doc) {
+    function add_term_to_doc($term, $doc)
+    {
         if (!is_a($doc, 'XapianDocument')) {
-            return FALSE;
+            return false;
         }
         try {
             $doc->add_term($term);
         } catch (Exception $e) {
             Display::display_error_message($e->getMessage());
+
             return 1;
         }
     }
@@ -249,14 +268,16 @@ abstract class XapianIndexer {
      * @param XapianDocument $doc The xapian document where to add the term
      * @return  mixed   XapianDocument, or false on error
      */
-    function remove_term_from_doc($term, $doc) {
+    function remove_term_from_doc($term, $doc)
+    {
         if (!is_a($doc, 'XapianDocument')) {
-            return FALSE;
+            return false;
         }
         try {
             $doc->remove_term($term);
         } catch (Exception $e) {
             Display::display_error_message($e->getMessage());
+
             return 1;
         }
     }
@@ -267,18 +288,20 @@ abstract class XapianIndexer {
      * @param XapianDocument $doc xapian document to push into the db
      * @param Xapian::docid $did xapian document id of the document to replace
      */
-    function replace_document($doc, $did) {
+    function replace_document($doc, $did)
+    {
         if (!is_a($doc, 'XapianDocument')) {
-            return FALSE;
+            return false;
         }
-        if ($this->db == NULL) {
+        if ($this->db == null) {
             $this->connectDb();
         }
         try {
-            $this->getDb()->replace_document((int) $did, $doc);
+            $this->getDb()->replace_document((int)$did, $doc);
             $this->getDb()->flush();
         } catch (Exception $e) {
             Display::display_error_message($e->getMessage());
+
             return 1;
         }
     }
@@ -286,15 +309,17 @@ abstract class XapianIndexer {
     /**
      * Class contructor
      */
-    function __construct() {
-        $this->db = NULL;
-        $this->stemmer = NULL;
+    function __construct()
+    {
+        $this->db = null;
+        $this->stemmer = null;
     }
 
     /**
      * Class destructor
      */
-    function __destruct() {
+    function __destruct()
+    {
         unset($this->db);
         unset($this->stemmer);
     }

+ 135 - 139
main/inc/lib/security.lib.php

@@ -34,19 +34,23 @@
  * and then using $secure->clean['var'] as a filtered equivalent, although
  * this is *not* mandatory at all.
  */
-class Security {
+class Security
+{
     public static $clean = array();
 
     /**
      * Checks if the absolute path (directory) given is really under the
      * checker path (directory)
-     * @param	string	Absolute path to be checked (with trailing slash)
-     * @param	string	Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
-     * @return	bool	True if the path is under the checker, false otherwise
+     * @param    string    Absolute path to be checked (with trailing slash)
+     * @param    string    Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
+     * @return    bool    True if the path is under the checker, false otherwise
      */
-    public static function check_abs_path($abs_path, $checker_path) {
+    public static function check_abs_path($abs_path, $checker_path)
+    {
         global $_configuration;
-        if (empty($checker_path)) { return false; } // The checker path must be set.
+        if (empty($checker_path)) {
+            return false;
+        } // The checker path must be set.
 
         $true_path = str_replace("\\", '/', realpath($abs_path));
         $found = strpos($true_path.'/', $checker_path);
@@ -62,34 +66,44 @@ class Security {
                 }
             }
             // Code specific to courses directory stored on other disk.
-            $checker_path = str_replace(api_get_path(SYS_COURSE_PATH), $_configuration['symbolic_course_folder_abs'], $checker_path);
+            $checker_path = str_replace(
+                api_get_path(SYS_COURSE_PATH),
+                $_configuration['symbolic_course_folder_abs'],
+                $checker_path
+            );
             $found = strpos($true_path.'/', $checker_path);
             if ($found === 0) {
                 return true;
             }
         }
+
         return false;
     }
 
     /**
      * Checks if the relative path (directory) given is really under the
      * checker path (directory)
-     * @param	string	Relative path to be checked (relative to the current directory) (with trailing slash)
-     * @param	string	Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
-     * @return	bool	True if the path is under the checker, false otherwise
+     * @param string $rel_path Relative path to be checked (relative to the current directory) (with trailing slash)
+     * @param string $checker_path Checker path under which the path should be (absolute path, with trailing slash, get it from api_get_path(SYS_COURSE_PATH))
+     *
+     * @return    bool    True if the path is under the checker, false otherwise
      */
-    public static function check_rel_path($rel_path, $checker_path) {
-        if (empty($checker_path)) { return false; } // The checker path must be set.
+    public static function check_rel_path($rel_path, $checker_path)
+    {
+        if (empty($checker_path)) {
+            return false;
+        } // The checker path must be set.
         $current_path = getcwd(); // No trailing slash.
         if (substr($rel_path, -1, 1) != '/') {
             $rel_path = '/'.$rel_path;
         }
         $abs_path = $current_path.$rel_path;
-        $true_path=str_replace("\\", '/', realpath($abs_path));
+        $true_path = str_replace("\\", '/', realpath($abs_path));
         $found = strpos($true_path.'/', $checker_path);
         if ($found === 0) {
             return true;
         }
+
         return false;
     }
 
@@ -97,41 +111,49 @@ class Security {
      * Filters dangerous filenames (*.php[.]?* and .htaccess) and returns it in
      * a non-executable form (for PHP and htaccess, this is still vulnerable to
      * other languages' files extensions)
-     * @param   string  Unfiltered filename
-     * @param   string  Filtered filename
+     * @param string $filename Unfiltered filename
+     *
+     * @return string
      */
-    public static function filter_filename($filename) {
-        require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-        return disable_dangerous_file($filename);
+    public static function filter_filename($filename)
+    {
+        return FileManager::disable_dangerous_file($filename);
     }
 
     /**
      * This function checks that the token generated in get_token() has been kept (prevents
      * Cross-Site Request Forgeries attacks)
-     * @param	string	The array in which to get the token ('get' or 'post')
-     * @return	bool	True if it's the right token, false otherwise
+     * @param string $request_type The array in which to get the token ('get' or 'post')
+     *
+     * @return bool True if it's the right token, false otherwise
+     *
      */
-    public static function check_token($request_type = 'post') {
+    public static function check_token($request_type = 'post')
+    {
         switch ($request_type) {
             case 'request':
                 if (isset($_SESSION['sec_token']) && isset($_REQUEST['sec_token']) && $_SESSION['sec_token'] === $_REQUEST['sec_token']) {
                     return true;
                 }
+
                 return false;
             case 'get':
                 if (isset($_SESSION['sec_token']) && isset($_GET['sec_token']) && $_SESSION['sec_token'] === $_GET['sec_token']) {
                     return true;
                 }
+
                 return false;
             case 'post':
                 if (isset($_SESSION['sec_token']) && isset($_POST['sec_token']) && $_SESSION['sec_token'] === $_POST['sec_token']) {
                     return true;
                 }
+
                 return false;
             default:
                 if (isset($_SESSION['sec_token']) && isset($request_type) && $_SESSION['sec_token'] === $request_type) {
                     return true;
                 }
+
                 return false;
         }
         return false; // Just in case, don't let anything slip.
@@ -140,12 +162,14 @@ class Security {
     /**
      * Checks the user agent of the client as recorder by get_ua() to prevent
      * most session hijacking attacks.
-     * @return	bool	True if the user agent is the same, false otherwise
+     * @return    bool    True if the user agent is the same, false otherwise
      */
-    public static function check_ua() {
+    public static function check_ua()
+    {
         if (isset($_SESSION['sec_ua']) and $_SESSION['sec_ua'] === $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed']) {
             return true;
         }
+
         return false;
     }
 
@@ -153,7 +177,8 @@ class Security {
      * Clear the security token from the session
      * @return void
      */
-    public static function clear_token() {
+    public static function clear_token()
+    {
         $_SESSION['sec_token'] = null;
         unset($_SESSION['sec_token']);
     }
@@ -165,12 +190,14 @@ class Security {
      * the one that sent this form in knowingly (this form hasn't been generated from
      * another website visited by the user at the same time).
      * Check the token with check_token()
-     * @return	string	Hidden-type input ready to insert into a form
+     * @return    string    Hidden-type input ready to insert into a form
      */
-    public static function get_HTML_token() {
-        $token = md5(uniqid(rand(), TRUE));
+    public static function get_HTML_token()
+    {
+        $token = md5(uniqid(rand(), true));
         $string = '<input type="hidden" name="sec_token" value="'.$token.'" />';
         $_SESSION['sec_token'] = $token;
+
         return $string;
     }
 
@@ -181,11 +208,13 @@ class Security {
      * the one that sent this form in knowingly (this form hasn't been generated from
      * another website visited by the user at the same time).
      * Check the token with check_token()
-     * @return	string	Token
+     * @return    string    Token
      */
-    public static function get_token() {
-        $token = md5(uniqid(rand(), TRUE));
+    public static function get_token()
+    {
+        $token = md5(uniqid(rand(), true));
         $_SESSION['sec_token'] = $token;
+
         return $token;
     }
 
@@ -194,82 +223,43 @@ class Security {
      * most cases of session hijacking.
      * @return void
      */
-    public static function get_ua() {
-        $_SESSION['sec_ua_seed'] = uniqid(rand(), TRUE);
+    public static function get_ua()
+    {
+        $_SESSION['sec_ua_seed'] = uniqid(rand(), true);
         $_SESSION['sec_ua'] = $_SERVER['HTTP_USER_AGENT'].$_SESSION['sec_ua_seed'];
     }
 
-    /**
-     * This function filters a variable to the type given, with the options given
-     * @param	mixed	The variable to be filtered
-     * @param	string	The type of variable we expect (bool,int,float,string)
-     * @param	array	Additional options
-     * @return	bool	True if variable was filtered and added to the current object, false otherwise
-     */
-    public static function filter($var, $type = 'string', $options = array()) {
-        // This function has not been finished! Do not use!
-        $result = false;
-        // Get variable name and value.
-        $args = func_get_args();
-        $names = array_keys($args);
-        $name = $names[0];
-        $value = $args[$name];
-        switch ($type) {
-            case 'bool':
-                $result = (bool) $var;
-                break;
-            case 'int':
-                $result = (int) $var;
-                break;
-            case 'float':
-                $result = (float) $var;
-                break;
-            case 'string/html':
-                $result = self::remove_XSS($var);
-                break;
-            case 'string/db':
-                $result = Database::escape_string($var);
-                break;
-            case 'array':
-                // An array variable shouldn't be given to the filter.
-                return false;
-            default:
-                return false;
-        }
-        if (!empty($option['save'])) {
-            $this->clean[$name] = $result;
-        }
-        return $result;
-    }
-
     /**
      * This function returns a variable from the clean array. If the variable doesn't exist,
      * it returns null
-     * @param	string	Variable name
-     * @return	mixed	Variable or NULL on error
+     * @param    string    Variable name
+     * @return    mixed    Variable or NULL on error
      */
-    public static function get($varname) {
+    public static function get($varname)
+    {
         if (isset(self::$clean[$varname])) {
             return self::$clean[$varname];
         }
-        return NULL;
+
+        return null;
     }
 
     /**
      * This function tackles the XSS injections.
      * Filtering for XSS is very easily done by using the htmlentities() function.
      * This kind of filtering prevents JavaScript snippets to be understood as such.
-     * @param	mixed	The variable to filter for XSS, this params can be a string or an array (example : array(x,y))
+     * @param    mixed    The variable to filter for XSS, this params can be a string or an array (example : array(x,y))
      * @param   integer The user status,constant allowed (STUDENT, COURSEMANAGER, ANONYMOUS, COURSEMANAGERLOWSECURITY)
-     * @return	mixed	Filtered string or array
+     * @return    mixed    Filtered string or array
      */
-    public static function remove_XSS($var, $user_status = ANONYMOUS, $filter_terms = false) {
-    	if ($filter_terms) {
-    		$var = self::filter_terms($var);
-    	}
+    public static function remove_XSS($var, $user_status = ANONYMOUS, $filter_terms = false)
+    {
+        if ($filter_terms) {
+            $var = self::filter_terms($var);
+        }
 
         if ($user_status == COURSEMANAGERLOWSECURITY) {
-            return $var;  // No filtering.
+            return $var; // No filtering.
         }
         static $purifier = array();
         if (!isset($purifier[$user_status])) {
@@ -285,8 +275,8 @@ class Security {
             //$config->set('Cache.DefinitionImpl', null); // Enable this line for testing purposes, for turning off caching. Don't forget to disable this line later!
             $config->set('Cache.SerializerPath', $cache_dir);
             $config->set('Core.Encoding', api_get_system_encoding());
-            $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');            
-            $config->set('HTML.MaxImgLength', '2560');                    
+            $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
+            $config->set('HTML.MaxImgLength', '2560');
             $config->set('HTML.TidyLevel', 'light');
             $config->set('Core.ConvertDocumentToFragment', false);
             $config->set('Core.RemoveProcessingInstructions', true);
@@ -296,7 +286,7 @@ class Security {
             }
 
             //Shows _target attribute in anchors
-            $config->set('Attr.AllowedFrameTargets', array('_blank','_top','_self', '_parent'));
+            $config->set('Attr.AllowedFrameTargets', array('_blank', '_top', '_self', '_parent'));
             if ($user_status == STUDENT) {
                 global $allowed_html_student;
                 $config->set('HTML.SafeEmbed', true);
@@ -315,7 +305,10 @@ class Security {
                 global $allowed_html_anonymous;
                 $config->set('HTML.Allowed', $allowed_html_anonymous);
             }
-            $config->set('Attr.EnableID', true); // We need it for example for the flv player (ids of surrounding div-tags have to be preserved).
+            $config->set(
+                'Attr.EnableID',
+                true
+            ); // We need it for example for the flv player (ids of surrounding div-tags have to be preserved).
             $config->set('CSS.AllowImportant', true);
             $config->set('CSS.AllowTricky', true); // We need for the flv player the css definition display: none;
             $config->set('CSS.Proprietary', true);
@@ -323,7 +316,6 @@ class Security {
         }
 
 
-
         if (is_array($var)) {
             return $purifier[$user_status]->purifyArray($var);
         } else {
@@ -335,54 +327,56 @@ class Security {
     /**
      *
      * Filter content
-     * @param	string content to be filter
-     * @return 	string
+     * @param    string content to be filter
+     * @return     string
      */
-    static function filter_terms($text) {
-    	static $bad_terms = array();
-
-    	if (empty($bad_terms)) {
-    		$list = api_get_setting('filter_terms');
-    		$list = explode("\n", $list);
-    		$list = array_filter($list);
-    		if (!empty($list)) {
-    			foreach($list as $term) {
-    				$term = str_replace(array("\r\n", "\r", "\n", "\t"), '', $term);
-    				$html_entities_value = api_htmlentities($term, ENT_QUOTES, api_get_system_encoding());
-    				$bad_terms[] = $term;
-    				if ($term != $html_entities_value) {
-    					$bad_terms[] = $html_entities_value;
-    				}
-    			}
-    			$bad_terms = array_filter($bad_terms);
-    		}
-    	}
-
-    	$replace = '***';
-    	if (!empty($bad_terms)) {
-    		//Fast way
-    		$new_text = str_ireplace($bad_terms, $replace, $text, $count);
-
-    		//We need statistics
-    		/*
-    		if (strlen($new_text) != strlen($text)) {
-    			$table = Database::get_main_table(TABLE_STATISTIC_TRACK_FILTERED_TERMS);
-    			$attributes = array();
-
-
-    			$attributes['user_id'] 		=
-    			$attributes['course_id'] 	=
-    			$attributes['session_id'] 	=
-    			$attributes['tool_id'] 		=
-    			$attributes['term'] 		=
-    			$attributes['created_at'] 	= api_get_utc_datetime();
-    			$sql = Database::insert($table, $attributes);
-    		}
-    		*/
-    		$text = $new_text;
-
-    	}
-		return $text;
+    static function filter_terms($text)
+    {
+        static $bad_terms = array();
+
+        if (empty($bad_terms)) {
+            $list = api_get_setting('filter_terms');
+            $list = explode("\n", $list);
+            $list = array_filter($list);
+            if (!empty($list)) {
+                foreach ($list as $term) {
+                    $term = str_replace(array("\r\n", "\r", "\n", "\t"), '', $term);
+                    $html_entities_value = api_htmlentities($term, ENT_QUOTES, api_get_system_encoding());
+                    $bad_terms[] = $term;
+                    if ($term != $html_entities_value) {
+                        $bad_terms[] = $html_entities_value;
+                    }
+                }
+                $bad_terms = array_filter($bad_terms);
+            }
+        }
+
+        $replace = '***';
+        if (!empty($bad_terms)) {
+            //Fast way
+            $new_text = str_ireplace($bad_terms, $replace, $text, $count);
+
+            //We need statistics
+            /*
+            if (strlen($new_text) != strlen($text)) {
+                $table = Database::get_main_table(TABLE_STATISTIC_TRACK_FILTERED_TERMS);
+                $attributes = array();
+
+
+                $attributes['user_id'] 		=
+                $attributes['course_id'] 	=
+                $attributes['session_id'] 	=
+                $attributes['tool_id'] 		=
+                $attributes['term'] 		=
+                $attributes['created_at'] 	= api_get_utc_datetime();
+                $sql = Database::insert($table, $attributes);
+            }
+            */
+            $text = $new_text;
+
+        }
+
+        return $text;
     }
 
 
@@ -394,7 +388,8 @@ class Security {
      * @return string                   Returns sanitized image path or an empty string when the image path is not secure.
      * @author Ivan Tcholakov, March 2011
      */
-    public static function filter_img_path($image_path) {
+    public static function filter_img_path($image_path)
+    {
         static $allowed_extensions = array('png', 'gif', 'jpg', 'jpeg');
         $image_path = htmlspecialchars(trim($image_path)); // No html code is allowed.
         // We allow static images only, query strings are forbidden.
@@ -426,6 +421,7 @@ class Security {
         } else {
             return '';
         }
+
         return $image_path;
     }
 }

+ 30 - 31
main/inc/lib/svg-edit/extensions/fileopen.php

@@ -12,59 +12,58 @@
  * @since 25/september/2010
 */
 
-require_once '../../../../inc/global.inc.php';//hack for chamilo
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+require_once '../../../../inc/global.inc.php'; //hack for chamilo
 
 api_protect_course_script();
 api_block_anonymous_users();
 
-if(!isset($_FILES['svg_file']['tmp_name'])) {
-	api_not_allowed(false);//from Chamilo
-	die();
+if (!isset($_FILES['svg_file']['tmp_name'])) {
+    api_not_allowed(false); //from Chamilo
+    die();
 }
 
 
 ?>
 <!doctype html>
 <?php
-	// Very minimal PHP file, all we do is Base64 encode the uploaded file and
-	// return it to the editor
-	
-	$file = $_FILES['svg_file']['tmp_name'];
-	
-	$output = file_get_contents($file);
-	
-	$type = $_REQUEST['type'];
-	
-	$prefix = '';
-	
-	// Make Data URL prefix for import image
-	if($type == 'import_img') {
-		$info = getimagesize($file);
-		$prefix = 'data:' . $info['mime'] . ';base64,';
-	}
-	
+// Very minimal PHP file, all we do is Base64 encode the uploaded file and
+// return it to the editor
+
+$file = $_FILES['svg_file']['tmp_name'];
+
+$output = file_get_contents($file);
+
+$type = $_REQUEST['type'];
+
+$prefix = '';
+
+// Make Data URL prefix for import image
+if ($type == 'import_img') {
+    $info = getimagesize($file);
+    $prefix = 'data:'.$info['mime'].';base64,';
+}
+
 //check the extension
 $extension = explode('.', $file);
-$extension = strtolower($extension[sizeof($extension) - 1]);	
+$extension = strtolower($extension[sizeof($extension) - 1]);
 
 //a bit title security
 $filename = addslashes(trim($file));
 $filename = Security::remove_XSS($filename);
 $filename = replace_dangerous_char($filename, 'strict');
-$filename = disable_dangerous_file($filename);	
-	
+$filename = FileManager::disable_dangerous_file($filename);
+
 //a bit mime security
 $current_mime = $_FILES['svg_file']['type'];
-$mime_svg='image/svg+xml';
-$mime_xml='application/xml';//hack for svg-edit because original code return application/xml; charset=us-ascii.
-		
-if(strpos($current_mime, $mime_svg)===false && strpos($current_mime, $mime_xml)===false && $extension=='svg'){
-	// die();//File extension does not match its content disabled to check into chamilo dev campus TODO:enabled
+$mime_svg = 'image/svg+xml';
+$mime_xml = 'application/xml';//hack for svg-edit because original code return application/xml; charset=us-ascii.
+
+if (strpos($current_mime, $mime_svg) === false && strpos($current_mime, $mime_xml) === false && $extension == 'svg') {
+    // die();//File extension does not match its content disabled to check into chamilo dev campus TODO:enabled
 }
 
 ?>
 
 <script>
-window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo $type ?>");
+    window.top.window.svgEditor.processFile("<?php echo $prefix.base64_encode($output); ?>", "<?php echo $type ?>");
 </script>

+ 129 - 80
main/inc/lib/svg-edit/extensions/filesave.php

@@ -12,72 +12,71 @@
  * @since 25/september/2010
 */
 
-$language_file = array('document');//Chamilo load lang var
+$language_file = array('document'); //Chamilo load lang var
 
 //Chamilo load libraries
 require_once '../../../../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 
 //Add security from Chamilo
 api_protect_course_script();
 api_block_anonymous_users();
 
-if(!isset($_POST['output_svg']) && !isset($_POST['output_png'])) {
-	api_not_allowed();//from Chamilo
-	die();
+if (!isset($_POST['output_svg']) && !isset($_POST['output_png'])) {
+    api_not_allowed(); //from Chamilo
+    die();
 }
 
 $file = '';
-$suffix = isset($_POST['output_svg'])?'svg':'png';
+$suffix = isset($_POST['output_svg']) ? 'svg' : 'png';
 
-if(isset($_POST['filename']) && strlen($_POST['filename']) > 0) {
-	$file = $_POST['filename'];	
+if (isset($_POST['filename']) && strlen($_POST['filename']) > 0) {
+    $file = $_POST['filename'];
 } else {
-	$file = 'image';
+    $file = 'image';
 }
 
-if($suffix == 'svg') {
-	$mime = 'image/svg+xml';
-	$contents = rawurldecode($_POST['output_svg']);
+if ($suffix == 'svg') {
+    $mime = 'image/svg+xml';
+    $contents = rawurldecode($_POST['output_svg']);
 } else {
-	$mime = 'image/png';
-	$contents = $_POST['output_png'];
-	$pos = (strpos($contents, 'base64,') + 7);
-	$contents = base64_decode(substr($contents, $pos));
+    $mime = 'image/png';
+    $contents = $_POST['output_png'];
+    $pos = (strpos($contents, 'base64,') + 7);
+    $contents = base64_decode(substr($contents, $pos));
 }
 
 //get SVG-Edit values
-$filename=$file;//from svg-edit
-$extension=$suffix;// from svg-edit
-$content=$contents;//from svg-edit
+$filename = $file; //from svg-edit
+$extension = $suffix; // from svg-edit
+$content = $contents; //from svg-edit
 
-$title = Database::escape_string(str_replace('_',' ',$filename));
+$title = Database::escape_string(str_replace('_', ' ', $filename));
 
-//get Chamilo variables 
+//get Chamilo variables
 
-if(!isset($_SESSION['draw_dir']) && !isset($_SESSION['whereami'])) {
-	api_not_allowed();//from Chamilo
-	die();	
+if (!isset($_SESSION['draw_dir']) && !isset($_SESSION['whereami'])) {
+    api_not_allowed(); //from Chamilo
+    die();
 }
 
 $current_session_id = api_get_session_id();
-$groupId    =  api_get_group_id();
-$relativeUrlPath=$_SESSION['draw_dir'];
-$currentTool=$_SESSION['whereami'];
+$groupId = api_get_group_id();
+$relativeUrlPath = $_SESSION['draw_dir'];
+$currentTool = $_SESSION['whereami'];
 $dirBaseDocuments = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-$saveDir=$dirBaseDocuments.$_SESSION['draw_dir'];
+$saveDir = $dirBaseDocuments.$_SESSION['draw_dir'];
 
 //a bit title security
 
 $filename = addslashes(trim($filename));
 $filename = Security::remove_XSS($filename);
 $filename = replace_dangerous_char($filename, 'strict');
-$filename = disable_dangerous_file($filename);
+$filename = FileManager::disable_dangerous_file($filename);
 
 // a bit extension
-if ($suffix!= 'svg' && $suffix!= 'png'){
-	die();
+if ($suffix != 'svg' && $suffix != 'png') {
+    die();
 }
 
 //a bit mime security
@@ -87,9 +86,9 @@ if (phpversion() >= '5.3' && extension_loaded('fileinfo')) {
 	$finfo = new finfo(FILEINFO_MIME);
 	$current_mime=$finfo->buffer($contents);
 	finfo_close($finfo);
-	$mime_png='image/png';//svg-edit return image/png; charset=binary 
+	$mime_png='image/png';//svg-edit return image/png; charset=binary
 	$mime_svg='image/svg+xml';
-	$mime_xml='application/xml';//hack for svg-edit because original code return application/xml; charset=us-ascii. See	  
+	$mime_xml='application/xml';//hack for svg-edit because original code return application/xml; charset=us-ascii. See
 	if(strpos($current_mime, $mime_png)===false && $extension=='png') {
 		die();//File extension does not match its content
 	} elseif(strpos($current_mime, $mime_svg)===false && strpos($current_mime, $mime_xml)===false && $extension=='svg') {
@@ -99,54 +98,99 @@ if (phpversion() >= '5.3' && extension_loaded('fileinfo')) {
 */
 
 //checks if the file exists, then rename the new
-if (file_exists($saveDir.'/'.$filename.$i.'.'.$extension) && $currentTool=='document/createdraw'){
-	echo '<script language="javascript" type="text/javascript">';
-	echo 'alert("'.get_lang('FileExistsChangeToSave').'");';
-	echo '</script>';
-	die();
+if (file_exists($saveDir.'/'.$filename.$i.'.'.$extension) && $currentTool == 'document/createdraw') {
+    echo '<script language="javascript" type="text/javascript">';
+    echo 'alert("'.get_lang('FileExistsChangeToSave').'");';
+    echo '</script>';
+    die();
 } else {
-	$drawFileName = $filename.'.'.$extension;
-	$title = $title.'.'.$extension;
+    $drawFileName = $filename.'.'.$extension;
+    $title = $title.'.'.$extension;
 }
 $documentPath = $saveDir.'/'.$drawFileName;
 
 //make a temporal file for get the file size
-	$tmpfname = tempnam("/tmp", "CTF");
-	$handle = fopen($tmpfname, "w");
-	fwrite($handle, $contents);
-	fclose($handle);
-	// Check if there is enough space in the course to save the file
-	if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
-		unlink($tmpfname);
-		die(get_lang('UplNotEnoughSpace'));
-	}
-	//erase temporal file
-	unlink($tmpfname);
+$tmpfname = tempnam("/tmp", "CTF");
+$handle = fopen($tmpfname, "w");
+fwrite($handle, $contents);
+fclose($handle);
+// Check if there is enough space in the course to save the file
+if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
+    unlink($tmpfname);
+    die(get_lang('UplNotEnoughSpace'));
+}
+//erase temporal file
+unlink($tmpfname);
 
 //add new document to disk
-file_put_contents( $documentPath, $contents );
-
-if ($currentTool=='document/createdraw') {
-	//add document to database
-	$doc_id = add_document($_course, $relativeUrlPath.'/'.$drawFileName, 'file', filesize($documentPath), $title);
-	api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
-
-} elseif($currentTool=='document/editdraw') {
-
-	//check path
-	if (!isset($_SESSION['draw_file'])){
-		api_not_allowed();//from Chamilo
-		die();
-	}
-	if ($_SESSION['draw_file'] == $drawFileName ){
-		$document_id = DocumentManager::get_document_id($_course, $relativeUrlPath.'/'.$drawFileName);
-		update_existing_document($_course, $document_id, filesize($documentPath), null);
-		api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $_user['user_id'], $groupId, null, null, null, $current_session_id);
-	} else {
-		//add a new document
-		$doc_id = add_document($_course, $relativeUrlPath.'/'.$drawFileName, 'file', filesize($documentPath), $title);
-		api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
-	}	
+file_put_contents($documentPath, $contents);
+
+if ($currentTool == 'document/createdraw') {
+    //add document to database
+    $doc_id = FileManager::add_document(
+        $_course,
+        $relativeUrlPath.'/'.$drawFileName,
+        'file',
+        filesize($documentPath),
+        $title
+    );
+    api_item_property_update(
+        $_course,
+        TOOL_DOCUMENT,
+        $doc_id,
+        'DocumentAdded',
+        $_user['user_id'],
+        $groupId,
+        null,
+        null,
+        null,
+        $current_session_id
+    );
+
+} elseif ($currentTool == 'document/editdraw') {
+
+    //check path
+    if (!isset($_SESSION['draw_file'])) {
+        api_not_allowed(); //from Chamilo
+        die();
+    }
+    if ($_SESSION['draw_file'] == $drawFileName) {
+        $document_id = DocumentManager::get_document_id($_course, $relativeUrlPath.'/'.$drawFileName);
+        FileManager::update_existing_document($_course, $document_id, filesize($documentPath), null);
+        api_item_property_update(
+            $_course,
+            TOOL_DOCUMENT,
+            $document_id,
+            'DocumentUpdated',
+            $_user['user_id'],
+            $groupId,
+            null,
+            null,
+            null,
+            $current_session_id
+        );
+    } else {
+        //add a new document
+        $doc_id = FileManager::add_document(
+            $_course,
+            $relativeUrlPath.'/'.$drawFileName,
+            'file',
+            filesize($documentPath),
+            $title
+        );
+        api_item_property_update(
+            $_course,
+            TOOL_DOCUMENT,
+            $doc_id,
+            'DocumentAdded',
+            $_user['user_id'],
+            $groupId,
+            null,
+            null,
+            null,
+            $current_session_id
+        );
+    }
 }
 
 //clean sessions and add messages and return to current document list
@@ -155,12 +199,17 @@ unset($_SESSION['draw_file']);
 unset($_SESSION['whereami']);
 
 echo '<script language="javascript" type="text/javascript">';
-if ($suffix!= 'png'){	
-	if ($relativeUrlPath==''){$relativeUrlPath='/';};    
-	$interbreadcrumb=api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq().'&curdirpath='.	urlencode($relativeUrlPath);
-	echo 'alert("'.get_lang('FileSavedAs').': '.$title.'");';	
-	echo 'window.top.location.href="'.$interbreadcrumb.'";';//return to current document list
+if ($suffix != 'png') {
+    if ($relativeUrlPath == '') {
+        $relativeUrlPath = '/';
+    }
+    ;
+    $interbreadcrumb = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq().'&curdirpath='.urlencode(
+        $relativeUrlPath
+    );
+    echo 'alert("'.get_lang('FileSavedAs').': '.$title.'");';
+    echo 'window.top.location.href="'.$interbreadcrumb.'";'; //return to current document list
 } else {
-	echo 'alert("'.get_lang('FileExportAs').': '.$title.'");';
+    echo 'alert("'.get_lang('FileExportAs').': '.$title.'");';
 }
 echo '</script>';

+ 57 - 40
main/inc/lib/wami-recorder/record_document.php

@@ -1,6 +1,5 @@
 <?php
 require_once '../../../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 ////Add security from Chamilo
 api_protect_course_script();
@@ -9,28 +8,27 @@ api_block_anonymous_users();
 # Save the audio to a URL-accessible directory for playback.
 parse_str($_SERVER['QUERY_STRING'], $params);
 
-if(isset($params['waminame']) && isset($params['wamidir']) && isset($params['wamiuserid'])) {
-	$waminame = $params['waminame'];
-	$wamidir = $params['wamidir'];
-	$wamiuserid = $params['wamiuserid'];
-}
-else {
-	api_not_allowed();
-	die();
+if (isset($params['waminame']) && isset($params['wamidir']) && isset($params['wamiuserid'])) {
+    $waminame = $params['waminame'];
+    $wamidir = $params['wamidir'];
+    $wamiuserid = $params['wamiuserid'];
+} else {
+    api_not_allowed();
+    die();
 }
 
-if ($wamiuserid!= api_get_user_id() || api_get_user_id()==0 || $wamiuserid==0) {
-	api_not_allowed();
-	die();
+if ($wamiuserid != api_get_user_id() || api_get_user_id() == 0 || $wamiuserid == 0) {
+    api_not_allowed();
+    die();
 }
-	
+
 
 //clean
 $waminame = Security::remove_XSS($waminame);
 $waminame = Database::escape_string($waminame);
 $waminame = addslashes(trim($waminame));
 $waminame = replace_dangerous_char($waminame, 'strict');
-$waminame = disable_dangerous_file($waminame);
+$waminame = FileManager::disable_dangerous_file($waminame);
 $wamidir = Security::remove_XSS($wamidir);
 
 $content = file_get_contents('php://input');
@@ -39,44 +37,46 @@ $content = file_get_contents('php://input');
 $ext = explode('.', $waminame);
 $ext = strtolower($ext[sizeof($ext) - 1]);
 
-if($ext!= 'wav'){
-	die();
+if ($ext != 'wav') {
+    die();
 }
 
 //Do not use here check Fileinfo method because return: text/plain
 
 $dirBaseDocuments = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-$saveDir=$dirBaseDocuments.$wamidir;
+$saveDir = $dirBaseDocuments.$wamidir;
 $current_session_id = api_get_session_id();
-$groupId=$_SESSION['_gid'];
+$groupId = $_SESSION['_gid'];
 
 //avoid duplicates
-$waminame_to_save=$waminame;
-$title_to_save=str_replace('_',' ',$waminame);
-$waminame_noex=basename($waminame, ".wav");
-if (file_exists($saveDir.'/'.$waminame_noex.'.'.$ext)){ 
-		$i = 1;		
-		while (file_exists($saveDir.'/'.$waminame_noex.'_'.$i.'.'.$ext)) $i++;
-		$waminame_to_save = $waminame_noex . '_' . $i . '.'.$ext;
-		$title_to_save = $waminame_noex . '_' . $i . '.'.$ext;
-		$title_to_save = str_replace('_',' ',$title_to_save);
+$waminame_to_save = $waminame;
+$title_to_save = str_replace('_', ' ', $waminame);
+$waminame_noex = basename($waminame, ".wav");
+if (file_exists($saveDir.'/'.$waminame_noex.'.'.$ext)) {
+    $i = 1;
+    while (file_exists($saveDir.'/'.$waminame_noex.'_'.$i.'.'.$ext)) {
+        $i++;
+    }
+    $waminame_to_save = $waminame_noex.'_'.$i.'.'.$ext;
+    $title_to_save = $waminame_noex.'_'.$i.'.'.$ext;
+    $title_to_save = str_replace('_', ' ', $title_to_save);
 }
 
 
 $documentPath = $saveDir.'/'.$waminame_to_save;
 
 //make a temporal file for get the file size
-	$tmpfname = tempnam("/tmp", "CTF");
-	$handle = fopen($tmpfname, "w");
-	fwrite($handle, $content);
-	fclose($handle);
-	// Check if there is enough space in the course to save the file
-	if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
-		unlink($tmpfname);
-		die(get_lang('UplNotEnoughSpace'));
-	}
-	//erase temporal file
-	unlink($tmpfname);
+$tmpfname = tempnam("/tmp", "CTF");
+$handle = fopen($tmpfname, "w");
+fwrite($handle, $content);
+fclose($handle);
+// Check if there is enough space in the course to save the file
+if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
+    unlink($tmpfname);
+    die(get_lang('UplNotEnoughSpace'));
+}
+//erase temporal file
+unlink($tmpfname);
 
 
 //add to disk
@@ -85,6 +85,23 @@ fwrite($fh, $content);
 fclose($fh);
 
 //add document to database
-	$doc_id = add_document($_course, $wamidir.'/'.$waminame_to_save, 'file', filesize($documentPath), $title_to_save);
-	api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
+$doc_id = FileManager::add_document(
+    $_course,
+    $wamidir.'/'.$waminame_to_save,
+    'file',
+    filesize($documentPath),
+    $title_to_save
+);
+api_item_property_update(
+    $_course,
+    TOOL_DOCUMENT,
+    $doc_id,
+    'DocumentAdded',
+    $_user['user_id'],
+    $groupId,
+    null,
+    null,
+    null,
+    $current_session_id
+);
 ?>

Fișier diff suprimat deoarece este prea mare
+ 648 - 525
main/install/index.php


Fișier diff suprimat deoarece este prea mare
+ 345 - 186
main/install/install.lib.php


+ 56 - 54
main/install/update-files-1.6.x-1.8.0.inc.php

@@ -24,125 +24,127 @@ function insert_db($db_name, $folder_name, $text)
     // TODO: The (global?) variable $_course has not been declared/initialized.
     $_course['dbName'] = $db_name;
 
-    $doc_id = add_document_180($_course, '/' . $folder_name, 'folder', 0, api_ucfirst($text));
+    $doc_id = FileManager::add_document_180($_course, '/'.$folder_name, 'folder', 0, api_ucfirst($text));
     api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', 1);
 }
 
 if (defined('SYSTEM_INSTALLATION')) {
 
-    $sys_course_path = $pathForm . 'courses/';
+    $sys_course_path = $pathForm.'courses/';
     //$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
     Database::select_db($dbNameForm);
     $db_name = $dbNameForm;
     $sql = "SELECT * FROM course";
-    $app['monolog']->addInfo('Getting courses for files updates: ' . $sql);
+    $app['monolog']->addInfo('Getting courses for files updates: '.$sql);
     $result = Database::query($sql);
 
     while ($courses_directories = Database::fetch_array($result)) {
 
-        $currentCourseRepositorySys = $sys_course_path . $courses_directories["directory"] . "/";
+        $currentCourseRepositorySys = $sys_course_path.$courses_directories["directory"]."/";
         $db_name = $courses_directories["db_name"];
-        $origCRS = $updatePath . 'courses/' . $courses_directories["directory"];
+        $origCRS = $updatePath.'courses/'.$courses_directories["directory"];
 
         if (!is_dir($origCRS)) {
-            $app['monolog']->addError('Directory ' . $origCRS . ' does not exist. Skipping.');
+            $app['monolog']->addError('Directory '.$origCRS.' does not exist. Skipping.');
             continue;
         }
         // Move everything to the new hierarchy (from old path to new path)
-        $app['monolog']->addInfo('Renaming ' . $origCRS . ' to ' . $sys_course_path . $courses_directories["directory"]);
-        rename($origCRS, $sys_course_path . $courses_directories["directory"]);
-        $app['monolog']->addInfo('Creating dirs in ' . $currentCourseRepositorySys);
+        $app['monolog']->addInfo('Renaming '.$origCRS.' to '.$sys_course_path.$courses_directories["directory"]);
+        rename($origCRS, $sys_course_path.$courses_directories["directory"]);
+        $app['monolog']->addInfo('Creating dirs in '.$currentCourseRepositorySys);
 
         // FOLDER DOCUMENT
         // document > audio
-        if (!is_dir($currentCourseRepositorySys . "document/audio")) {
-            mkdir($currentCourseRepositorySys . "document/audio", $perm);
+        if (!is_dir($currentCourseRepositorySys."document/audio")) {
+            mkdir($currentCourseRepositorySys."document/audio", $perm);
             insert_db($db_name, "audio", get_lang('Audio'));
         }
 
         // document > flash
-        if (!is_dir($currentCourseRepositorySys . "document/flash")) {
-            mkdir($currentCourseRepositorySys . "document/flash", $perm);
+        if (!is_dir($currentCourseRepositorySys."document/flash")) {
+            mkdir($currentCourseRepositorySys."document/flash", $perm);
             insert_db($db_name, "flash", get_lang('Flash'));
         }
 
         // document > images
-        if (!is_dir($currentCourseRepositorySys . "document/images")) {
-            mkdir($currentCourseRepositorySys . "document/images", $perm);
+        if (!is_dir($currentCourseRepositorySys."document/images")) {
+            mkdir($currentCourseRepositorySys."document/images", $perm);
             insert_db($db_name, "images", get_lang('Images'));
         }
 
         // document > video
-        if (!is_dir($currentCourseRepositorySys . "document/video")) {
-            mkdir($currentCourseRepositorySys . "document/video", $perm);
+        if (!is_dir($currentCourseRepositorySys."document/video")) {
+            mkdir($currentCourseRepositorySys."document/video", $perm);
             insert_db($db_name, "video", get_lang('Video'));
         }
 
         // document > video > flv
-        if (!is_dir($currentCourseRepositorySys . "document/video/flv")) {
-            mkdir($currentCourseRepositorySys . "document/video/flv", $perm);
-            insert_db($db_name, "video", get_lang('Video') . " (flv)");
+        if (!is_dir($currentCourseRepositorySys."document/video/flv")) {
+            mkdir($currentCourseRepositorySys."document/video/flv", $perm);
+            insert_db($db_name, "video", get_lang('Video')." (flv)");
         }
 
         // FOLDER UPLOAD
         // upload
-        if (!is_dir($currentCourseRepositorySys . "upload")) {
-            mkdir($currentCourseRepositorySys . "upload", $perm);
+        if (!is_dir($currentCourseRepositorySys."upload")) {
+            mkdir($currentCourseRepositorySys."upload", $perm);
         }
 
         // upload > blog
-        if (!is_dir($currentCourseRepositorySys . "upload/blog")) {
-            mkdir($currentCourseRepositorySys . "upload/blog", $perm);
+        if (!is_dir($currentCourseRepositorySys."upload/blog")) {
+            mkdir($currentCourseRepositorySys."upload/blog", $perm);
         }
 
         // upload > forum
-        if (!is_dir($currentCourseRepositorySys . "upload/forum")) {
-            mkdir($currentCourseRepositorySys . "upload/forum", $perm);
+        if (!is_dir($currentCourseRepositorySys."upload/forum")) {
+            mkdir($currentCourseRepositorySys."upload/forum", $perm);
         }
 
         // upload > test
-        if (!is_dir($currentCourseRepositorySys . "upload/test")) {
-            mkdir($currentCourseRepositorySys . "upload/test", $perm);
+        if (!is_dir($currentCourseRepositorySys."upload/test")) {
+            mkdir($currentCourseRepositorySys."upload/test", $perm);
         }
 
         // Updating index file in courses directories to change claroline/ into main/
-        $content = '<?php' . "\n" .
-            '$cidReq="' . $courses_directories['code'] . '";' . "\n" .
-            '$dbname="' . $courses_directories['db_name'] . '";' . "\n" .
-            'include("../../main/course_home/course_home.php");' . "\n" .
+        $content = '<?php'."\n".
+            '$cidReq="'.$courses_directories['code'].'";'."\n".
+            '$dbname="'.$courses_directories['db_name'].'";'."\n".
+            'include("../../main/course_home/course_home.php");'."\n".
             '?>';
-        unlink($currentCourseRepositorySys . 'index.php');
-        $fp = @ fopen($currentCourseRepositorySys . 'index.php', 'w');
+        unlink($currentCourseRepositorySys.'index.php');
+        $fp = @ fopen($currentCourseRepositorySys.'index.php', 'w');
         if ($fp) {
-            $app['monolog']->addError('Writing redirection file in ' . $currentCourseRepositorySys . 'index.php');
+            $app['monolog']->addError('Writing redirection file in '.$currentCourseRepositorySys.'index.php');
             fwrite($fp, $content);
             fclose($fp);
         } else {
-            $app['monolog']->addError('Could not open file ' . $currentCourseRepositorySys . 'index.php');
+            $app['monolog']->addError('Could not open file '.$currentCourseRepositorySys.'index.php');
         }
     }
 
     // Write the config file
-    write_system_config_file(api_get_path(CONFIGURATION_PATH) . 'configuration.php');
+    write_system_config_file(api_get_path(CONFIGURATION_PATH).'configuration.php');
     // Write a distribution file with the config as a backup for the admin
-    write_system_config_file(api_get_path(CONFIGURATION_PATH) . 'configuration.dist.php');
+    write_system_config_file(api_get_path(CONFIGURATION_PATH).'configuration.dist.php');
     // Write a .htaccess file in the course repository
     write_courses_htaccess_file($urlAppendPath);
-    copy($updatePath . 'claroline/inc/conf/add_course.conf.php', $pathForm . 'main/inc/conf/add_course.conf.php');
-    copy($updatePath . 'claroline/inc/conf/course_info.conf.php', $pathForm . 'main/inc/conf/course_info.conf.php');
-    copy($updatePath . 'claroline/inc/conf/mail.conf.php', $pathForm . 'main/inc/conf/mail.conf.php');
-    copy($updatePath . 'claroline/inc/conf/profile.conf.inc.php', $pathForm . 'main/inc/conf/profile.conf.php');
-
-    $app['monolog']->addInfo('Renaming ' . $updatePath . 'claroline/upload/users to ' . $pathForm . 'main/upload/users');
-    rename($updatePath . 'claroline/upload/users', $pathForm . 'main/upload/users');
-    $app['monolog']->addInfo('Renaming ' . $updatePath . 'claroline/upload/audio to ' . $pathForm . 'main/upload/audio');
-    rename($updatePath . 'claroline/upload/audio', $pathForm . 'main/upload/audio');
-    $app['monolog']->addInfo('Renaming ' . $updatePath . 'claroline/upload/images to ' . $pathForm . 'main/upload/images');
-    rename($updatePath . 'claroline/upload/images', $pathForm . 'main/upload/images');
-    $app['monolog']->addInfo('Renaming ' . $updatePath . 'claroline/upload/linked_files to ' . $pathForm . 'main/upload/linked_files');
-    rename($updatePath . 'claroline/upload/linked_files', $pathForm . 'main/upload/linked_files');
-    $app['monolog']->addInfo('Renaming ' . $updatePath . 'claroline/upload/video to ' . $pathForm . 'main/upload/video');
-    rename($updatePath . 'claroline/upload/video', $pathForm . 'main/upload/video');
+    copy($updatePath.'claroline/inc/conf/add_course.conf.php', $pathForm.'main/inc/conf/add_course.conf.php');
+    copy($updatePath.'claroline/inc/conf/course_info.conf.php', $pathForm.'main/inc/conf/course_info.conf.php');
+    copy($updatePath.'claroline/inc/conf/mail.conf.php', $pathForm.'main/inc/conf/mail.conf.php');
+    copy($updatePath.'claroline/inc/conf/profile.conf.inc.php', $pathForm.'main/inc/conf/profile.conf.php');
+
+    $app['monolog']->addInfo('Renaming '.$updatePath.'claroline/upload/users to '.$pathForm.'main/upload/users');
+    rename($updatePath.'claroline/upload/users', $pathForm.'main/upload/users');
+    $app['monolog']->addInfo('Renaming '.$updatePath.'claroline/upload/audio to '.$pathForm.'main/upload/audio');
+    rename($updatePath.'claroline/upload/audio', $pathForm.'main/upload/audio');
+    $app['monolog']->addInfo('Renaming '.$updatePath.'claroline/upload/images to '.$pathForm.'main/upload/images');
+    rename($updatePath.'claroline/upload/images', $pathForm.'main/upload/images');
+    $app['monolog']->addInfo(
+        'Renaming '.$updatePath.'claroline/upload/linked_files to '.$pathForm.'main/upload/linked_files'
+    );
+    rename($updatePath.'claroline/upload/linked_files', $pathForm.'main/upload/linked_files');
+    $app['monolog']->addInfo('Renaming '.$updatePath.'claroline/upload/video to '.$pathForm.'main/upload/video');
+    rename($updatePath.'claroline/upload/video', $pathForm.'main/upload/video');
 } else {
-    echo 'You are not allowed here !' . __FILE__;
+    echo 'You are not allowed here !'.__FILE__;
 }

Fișier diff suprimat deoarece este prea mare
+ 499 - 403
main/metadata/importmanifest.php


+ 92 - 69
main/mySpace/user_import.php

@@ -5,11 +5,11 @@
  * This code is inherited from admin/user_import.php
  * @package chamilo.reporting
  * Created on 26 julio 2008  by Julio Montoya gugli100@gmail.com
-*/
+ */
 /**
  * Main script
  */
-$language_file = array ('admin', 'registration', 'index', 'trad4all', 'tracking');
+$language_file = array('admin', 'registration', 'index', 'trad4all', 'tracking');
 
 $cidReset = true;
 require '../inc/global.inc.php';
@@ -17,19 +17,17 @@ require_once 'myspace.lib.php';
 
 $this_section = SECTION_PLATFORM_ADMIN; // TODO: Platform admin section?
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
 require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 
 $tool_name = get_lang('ImportUserListXMLCSV');
 api_block_anonymous_users();
 
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('MySpace'));
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('MySpace'));
 $id_session = '';
 if (isset($_GET['id_session']) && $_GET['id_session'] != '') {
- 	$id_session = intval($_GET['id_session']);
-	$interbreadcrumb[] = array ('url' => 'session.php', 'name' => get_lang('Sessions'));
-	$interbreadcrumb[] = array ('url' => 'course.php?id_session='.$id_session.'', 'name' => get_lang('Course'));
+    $id_session = intval($_GET['id_session']);
+    $interbreadcrumb[] = array('url' => 'session.php', 'name' => get_lang('Sessions'));
+    $interbreadcrumb[] = array('url' => 'course.php?id_session='.$id_session.'', 'name' => get_lang('Course'));
 }
 
 // Set this option to true to enforce strict purification for usenames.
@@ -44,87 +42,112 @@ if (!api_is_coach()) {
 
 // Checking whether the current coach is the admin coach.
 if (api_get_setting('add_users_by_coach') == 'true') {
-	if (!api_is_platform_admin()) {
-		if (isset($_REQUEST['id_session'])) {
-			$id_session = intval($_REQUEST['id_session']);
-			$sql = 'SELECT id_coach FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_session;
-			$rs = Database::query($sql);
-			if (Database::result($rs, 0, 0) != $_user['user_id']) {
-				api_not_allowed(true);
-			}
-		} else {
-			api_not_allowed(true);
-		}
-	}
+    if (!api_is_platform_admin()) {
+        if (isset($_REQUEST['id_session'])) {
+            $id_session = intval($_REQUEST['id_session']);
+            $sql = 'SELECT id_coach FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_session;
+            $rs = Database::query($sql);
+            if (Database::result($rs, 0, 0) != $_user['user_id']) {
+                api_not_allowed(true);
+            }
+        } else {
+            api_not_allowed(true);
+        }
+    }
 } else {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 set_time_limit(0);
 
 if ($_POST['formSent'] && $_FILES['import_file']['size'] !== 0) {
-	$file_type = $_POST['file_type'];
-	$id_session = intval($_POST['id_session']);
-	if ($file_type == 'csv') {
-		$users = MySpace::parse_csv_data($_FILES['import_file']['tmp_name']);
-	} else {
-		$users = MySpace::parse_xml_data($_FILES['import_file']['tmp_name']);
-	}
-	if (count($users) > 0) {
-		$results = MySpace::validate_data($users);
-		$errors = $results['errors'];
-		$users = $results['users'];
-
-		if (count($errors) == 0) {
-			if (!empty($id_session)) {
-				$tbl_session_rel_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-				// Selecting all the courses from the session id requested.
-				$sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'";
-				$result = Database::query($sql);
-				$course_list = array();
-				while ($row = Database::fetch_array($result)) {
-					$course_list[] = $row['course_code'];
-				}
-				$errors = MySpace::get_user_creator($users, $course_list, $id_session);
-				$users = MySpace::check_all_usernames($users, $course_list, $id_session);
-				if (count($errors) == 0) {
-					MySpace::save_data($users, $course_list, $id_session);
-				}
-			} else {
-				header('Location: course.php?id_session='.$id_session.'&action=error_message&message='.urlencode(get_lang('NoSessionId')));
-			}
-		}
-	} else {
-		header('Location: course.php?id_session='.$id_session.'&action=error_message&message='.urlencode(get_lang('NoUsersRead')));
-	}
+    $file_type = $_POST['file_type'];
+    $id_session = intval($_POST['id_session']);
+    if ($file_type == 'csv') {
+        $users = MySpace::parse_csv_data($_FILES['import_file']['tmp_name']);
+    } else {
+        $users = MySpace::parse_xml_data($_FILES['import_file']['tmp_name']);
+    }
+    if (count($users) > 0) {
+        $results = MySpace::validate_data($users);
+        $errors = $results['errors'];
+        $users = $results['users'];
+
+        if (count($errors) == 0) {
+            if (!empty($id_session)) {
+                $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+                // Selecting all the courses from the session id requested.
+                $sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'";
+                $result = Database::query($sql);
+                $course_list = array();
+                while ($row = Database::fetch_array($result)) {
+                    $course_list[] = $row['course_code'];
+                }
+                $errors = MySpace::get_user_creator($users, $course_list, $id_session);
+                $users = MySpace::check_all_usernames($users, $course_list, $id_session);
+                if (count($errors) == 0) {
+                    MySpace::save_data($users, $course_list, $id_session);
+                }
+            } else {
+                header(
+                    'Location: course.php?id_session='.$id_session.'&action=error_message&message='.urlencode(
+                        get_lang('NoSessionId')
+                    )
+                );
+            }
+        }
+    } else {
+        header(
+            'Location: course.php?id_session='.$id_session.'&action=error_message&message='.urlencode(
+                get_lang('NoUsersRead')
+            )
+        );
+    }
 }
 
 Display :: display_header($tool_name);
 
 if ($_FILES['import_file']['size'] == 0 && $_POST) {
-	Display::display_error_message(get_lang('ThisFieldIsRequired'));
+    Display::display_error_message(get_lang('ThisFieldIsRequired'));
 }
 
 if (count($errors) != 0) {
-	$error_message = '<ul>';
-	foreach ($errors as $index => $error_user) {
-		$error_message .= '<li><strong>'.$error_user['error'].'</strong>: ';
-		$error_message .= api_get_person_name($error_user['FirstName'], $error_user['LastName']);
-		$error_message .= '</li>';
-	}
-	$error_message .= '</ul>';
-	Display :: display_error_message($error_message, false);
+    $error_message = '<ul>';
+    foreach ($errors as $index => $error_user) {
+        $error_message .= '<li><strong>'.$error_user['error'].'</strong>: ';
+        $error_message .= api_get_person_name($error_user['FirstName'], $error_user['LastName']);
+        $error_message .= '</li>';
+    }
+    $error_message .= '</ul>';
+    Display :: display_error_message($error_message, false);
 }
 
 $form = new FormValidator('user_import');
 $form->addElement('hidden', 'formSent');
-$form->addElement('hidden', 'id_session',$id_session);
+$form->addElement('hidden', 'id_session', $id_session);
 $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
 $form->addRule('import_file', get_lang('ThisFieldIsRequired'), 'required');
-$allowed_file_types = array ('xml', 'csv');
-$form->addRule('import_file', get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')', 'filetype', $allowed_file_types);
-$form->addElement('radio', 'file_type', get_lang('FileType'), 'XML (<a href="../admin/example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)', 'xml');
-$form->addElement('radio', 'file_type', null, 'CSV (<a href="../admin/example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)', 'csv');
+$allowed_file_types = array('xml', 'csv');
+$form->addRule(
+    'import_file',
+    get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')',
+    'filetype',
+    $allowed_file_types
+);
+$form->addElement(
+    'radio',
+    'file_type',
+    get_lang('FileType'),
+    'XML (<a href="../admin/example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)',
+    'xml'
+);
+$form->addElement(
+    'radio',
+    'file_type',
+    null,
+    'CSV (<a href="../admin/example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)',
+    'csv'
+);
 $form->addElement('radio', 'sendMail', get_lang('SendMailToUsers'), get_lang('Yes'), 1);
 $form->addElement('radio', 'sendMail', null, get_lang('No'), 0);
 $form->addElement('submit', 'submit', get_lang('Ok'));

+ 321 - 152
main/newscorm/aicc.class.php

@@ -4,8 +4,8 @@
 /**
  * Defines the AICC class, which is meant to contain the aicc items (nuclear elements)
  * @package chamilo.learnpath
- * @author	Yannick Warnier <ywarnier@beeznest.org>
- * @license	GNU/GPL
+ * @author    Yannick Warnier <ywarnier@beeznest.org>
+ * @license    GNU/GPL
  */
 /**
  * Code
@@ -19,21 +19,22 @@ require_once 'aiccBlock.class.php';
  * Class
  * @package chamilo.learnpath
  */
-class aicc extends learnpath {
+class aicc extends learnpath
+{
 
     public $config = array();
-    public $config_basename = '';	// The configuration files might be multiple and might have
-                                    // funny names. We need to keep the name of that file while we
-                                    // install the content.
+    public $config_basename = ''; // The configuration files might be multiple and might have
+    // funny names. We need to keep the name of that file while we
+    // install the content.
     public $config_files = array();
     public $config_exts = array(
         'crs' => 0, // Course description file (mandatory)
-        'au'  => 0, // Assignable Unit file (mandatory)
+        'au' => 0, // Assignable Unit file (mandatory)
         'des' => 0, // Descriptor file (mandatory)
         'cst' => 0, // Course structure file (mandatory)
         'ore' => 0, // Objectives relationshops file (optional)
         'pre' => 0, // Prerequisites file (optional)
-        'cmp' => 0  // Completion Requirements file (optional)
+        'cmp' => 0 // Completion Requirements file (optional)
     );
     public $aulist = array();
     public $au_order_list = array();
@@ -42,20 +43,23 @@ class aicc extends learnpath {
     public $cstlist = array();
     public $orelist = array();
 
-    public $subdir = '';	// Path between the scorm/ directory and the config files e.g. maritime_nav/maritime_nav. This is the path that will be used in the lp_path when importing a package.
-    public $zipname = '';	// Keeps the zipfile safe for the object's life so that we can use it if there is no title available.
-    public $lastzipnameindex = 0;	// Keeps an index of the number of uses of the zipname so far.
+    public $subdir = ''; // Path between the scorm/ directory and the config files e.g. maritime_nav/maritime_nav. This is the path that will be used in the lp_path when importing a package.
+    public $zipname = ''; // Keeps the zipfile safe for the object's life so that we can use it if there is no title available.
+    public $lastzipnameindex = 0; // Keeps an index of the number of uses of the zipname so far.
     public $config_encoding = 'ISO-8859-1';
     public $debug = 0;
 
     /**
      * Class constructor. Based on the parent constructor.
-     * @param	string	Course code
-     * @param	integer	Learnpath ID in DB
-     * @param	integer	User ID
+     * @param    string    Course code
+     * @param    integer    Learnpath ID in DB
+     * @param    integer    User ID
      */
-    public function __construct($course_code = null, $resource_id = null, $user_id = null) {
-        if ($this->debug > 0) { error_log('In aicc::aicc()', 0); }
+    public function __construct($course_code = null, $resource_id = null, $user_id = null)
+    {
+        if ($this->debug > 0) {
+            error_log('In aicc::aicc()', 0);
+        }
         if (!empty($course_code) && !empty($resource_id) && !empty($user_id)) {
             parent::__construct($course_code, $resource_id, $user_id);
         } else {
@@ -65,20 +69,26 @@ class aicc extends learnpath {
 
     /**
      * Opens a resource
-     * @param	integer	Database ID of the resource
+     * @param    integer    Database ID of the resource
      */
-    public function open($id) {
-        if ($this->debug > 0) { error_log('In aicc::open()', 0); }
+    public function open($id)
+    {
+        if ($this->debug > 0) {
+            error_log('In aicc::open()', 0);
+        }
         // Redefine parent method.
     }
 
     /**
      * Parses a set of AICC config files and puts everything into the $config array
-     * @param	string	Path to the config files dir on the system. If not defined, uses the base path of the course's scorm dir
-     * @return	array	Structured array representing the config files' contents
+     * @param    string    Path to the config files dir on the system. If not defined, uses the base path of the course's scorm dir
+     * @return    array    Structured array representing the config files' contents
      */
-    function parse_config_files($dir = '') {
-        if ($this->debug > 0) {error_log('New LP - In aicc::parse_config_files('.$dir.')', 0); }
+    function parse_config_files($dir = '')
+    {
+        if ($this->debug > 0) {
+            error_log('New LP - In aicc::parse_config_files('.$dir.')', 0);
+        }
         if (empty($dir)) {
             // Get the path of the AICC config files dir.
             $dir = $this->subdir;
@@ -92,7 +102,9 @@ class aicc extends learnpath {
             $crs_file = $dir.'/'.$this->config_files['crs'];
             $crs_params = $this->parse_ini_file_quotes_safe($crs_file);
             //echo '<pre>crs:'.print_r($crs_params, true).'</pre>';
-            if ($this->debug > 1) { error_log('New LP - In aicc::parse_config_files() - '.$crs_file.' has been parsed', 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - In aicc::parse_config_files() - '.$crs_file.' has been parsed', 0);
+            }
 
             // CRS distribute crs params into the aicc object.
             if (!empty($crs_params['course']['course_creator'])) {
@@ -139,9 +151,11 @@ class aicc extends learnpath {
             $des_file = $dir.'/'.$this->config_files['des'];
             $des_params = $this->parse_csv_file($des_file);
             //echo '<pre>des:'.print_r($des_params, true).'</pre>';
-            if ($this->debug > 1) { error_log('New LP - In aicc::parse_config_files() - '.$des_file.' has been parsed', 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - In aicc::parse_config_files() - '.$des_file.' has been parsed', 0);
+            }
             // Distribute des params into the aicc object.
-            foreach ($des_params as $des){
+            foreach ($des_params as $des) {
                 // One AU in AICC is equivalent to one SCO in SCORM (scormItem class).
                 $oDes = new aiccResource('config', $des);
                 $this->deslist[$oDes->identifier] = $oDes;
@@ -151,7 +165,9 @@ class aicc extends learnpath {
             $au_file = $dir.'/'.$this->config_files['au'];
             $au_params = $this->parse_csv_file($au_file);
             //echo '<pre>au:'.print_r($au_params, true).'</pre>';
-            if ($this->debug > 1) { error_log('New LP - In aicc::parse_config_files() - '.$au_file.' has been parsed', 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - In aicc::parse_config_files() - '.$au_file.' has been parsed', 0);
+            }
             // Distribute au params into the aicc object.
             foreach ($au_params as $au) {
                 $oAu = new aiccItem('config', $au);
@@ -163,7 +179,9 @@ class aicc extends learnpath {
             $cst_file = $dir.'/'.$this->config_files['cst'];
             $cst_params = $this->parse_csv_file($cst_file, ',', '"', true);
             //echo '<pre>cst:'.print_r($cst_params, true).'</pre>';
-            if ($this->debug > 1) { error_log('New LP - In aicc::parse_config_files() - '.$cst_file.' has been parsed', 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - In aicc::parse_config_files() - '.$cst_file.' has been parsed', 0);
+            }
             // Distribute cst params into the aicc object.
             foreach ($cst_params as $cst) {
                 $oCst = new aiccBlock('config', $cst);
@@ -176,7 +194,9 @@ class aicc extends learnpath {
                 $ore_file = $dir.'/'.$this->config_files['ore'];
                 $ore_params = $this->parse_csv_file($ore_file, ',', '"', true);
                 //echo '<pre>ore:'.print_r($ore_params,true).'</pre>';
-                if ($this->debug > 1) { error_log('New LP - In aicc::parse_config_files() - '.$ore_file.' has been parsed', 0); }
+                if ($this->debug > 1) {
+                    error_log('New LP - In aicc::parse_config_files() - '.$ore_file.' has been parsed', 0);
+                }
                 // Distribute ore params into the aicc object.
                 foreach ($ore_params as $ore) {
                     $oOre = new aiccObjective('config', $ore);
@@ -189,17 +209,23 @@ class aicc extends learnpath {
                 $pre_file = $dir.'/'.$this->config_files['pre'];
                 $pre_params = $this->parse_csv_file($pre_file);
                 //echo '<pre>pre:'.print_r($pre_params, true).'</pre>';
-                if ($this->debug > 1) { error_log('New LP - In aicc::parse_config_files() - '.$pre_file.' has been parsed', 0); }
+                if ($this->debug > 1) {
+                    error_log('New LP - In aicc::parse_config_files() - '.$pre_file.' has been parsed', 0);
+                }
                 // Distribute pre params into the aicc object.
                 foreach ($pre_params as $pre) {
                     // Place a constraint on the corresponding block or AU.
                     if (in_array(api_strtolower($pre['structure_element']), array_keys($this->cstlist))) {
                         // If this references a block element:
-                        $this->cstlist[api_strtolower($pre['structure_element'])]->prereq_string = api_strtolower($pre['prerequisite']);
+                        $this->cstlist[api_strtolower($pre['structure_element'])]->prereq_string = api_strtolower(
+                            $pre['prerequisite']
+                        );
                     }
                     if (in_array(api_strtolower($pre['structure_element']), array_keys($this->aulist))) {
                         // If this references a block element:
-                        $this->aulist[api_strtolower($pre['structure_element'])]->prereq_string = api_strtolower($pre['prerequisite']);
+                        $this->aulist[api_strtolower($pre['structure_element'])]->prereq_string = api_strtolower(
+                            $pre['prerequisite']
+                        );
                     }
                 }
             }
@@ -210,7 +236,9 @@ class aicc extends learnpath {
                 $cmp_file = $dir.'/'.$this->config_files['cmp'];
                 $cmp_params = $this->parse_csv_file($cmp_file);
                 //echo '<pre>cmp:'.print_r($cmp_params, true).'</pre>';
-                if ($this->debug > 1) { error_log('New LP - In aicc::parse_config_files() - '.$cmp_file.' has been parsed', 0); }
+                if ($this->debug > 1) {
+                    error_log('New LP - In aicc::parse_config_files() - '.$cmp_file.' has been parsed', 0);
+                }
                 // Distribute cmp params into the aicc object.
                 foreach ($cmp_params as $cmp) {
                     //$oCmp = new aiccCompletionRequirements('config', $cmp);
@@ -218,18 +246,22 @@ class aicc extends learnpath {
                 }
             }
         }
+
         return $this->config;
     }
 
     /**
      * Import the aicc object (as a result from the parse_config_files function) into the database structure
-     * @param	string	Unique course code
-     * @return	bool	Returns -1 on error
+     * @param    string    Unique course code
+     * @return    bool    Returns -1 on error
      */
-    function import_aicc($course_code) {
+    function import_aicc($course_code)
+    {
         $course_id = api_get_course_int_id();
-        
-        if ($this->debug > 0) { error_log('New LP - In aicc::import_aicc('.$course_code.')', 0); }
+
+        if ($this->debug > 0) {
+            error_log('New LP - In aicc::import_aicc('.$course_code.')', 0);
+        }
         // Get table names.
         $new_lp = 'lp';
         $new_lp_item = 'lp_item';
@@ -237,9 +269,13 @@ class aicc extends learnpath {
         // The previous method wasn't safe to get the database name, so do it manually with the course_code.
         $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE code='$course_code'";
         $res = Database::query($sql);
-        if (Database::num_rows($res) < 1) { error_log('New LP - Database for '.$course_code.' not found '.__FILE__.' '.__LINE__, 0); return -1; }
+        if (Database::num_rows($res) < 1) {
+            error_log('New LP - Database for '.$course_code.' not found '.__FILE__.' '.__LINE__, 0);
+
+            return -1;
+        }
         $row = Database::fetch_array($res);
-                
+
         $new_lp = Database::get_course_table(TABLE_LP_MAIN);
         $new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
         $get_max = "SELECT MAX(display_order) FROM $new_lp WHERE c_id = $course_id";
@@ -253,17 +289,31 @@ class aicc extends learnpath {
 
         $this->config_encoding = "ISO-8859-1"; // TODO: We may apply detection for this value, see the function api_detect_encoding().
 
-        $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib, content_maker,display_order)" .
-                "VALUES " .
-                "($course_id, 3, '".$this->course_title."', '".$this->course_id."','".$this->course_description."'," .
-                "'".$this->subdir."', 0, 'embedded', '".$this->config_encoding."'," .
-                "'aicc_api.php','".$this->course_creator."',$dsp)";
-        if ($this->debug > 2) { error_log('New LP - In import_aicc(), inserting path: '. $sql, 0); }
+        $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib, content_maker,display_order)".
+            "VALUES ".
+            "($course_id, 3, '".$this->course_title."', '".$this->course_id."','".$this->course_description."',".
+            "'".$this->subdir."', 0, 'embedded', '".$this->config_encoding."',".
+            "'aicc_api.php','".$this->course_creator."',$dsp)";
+        if ($this->debug > 2) {
+            error_log('New LP - In import_aicc(), inserting path: '.$sql, 0);
+        }
         $res = Database::query($sql);
         $lp_id = Database::insert_id();
         $this->lp_id = $lp_id;
-        api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'LearnpathAdded', api_get_user_id());
-        api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'visible', api_get_user_id());
+        api_item_property_update(
+            api_get_course_info($course_code),
+            TOOL_LEARNPATH,
+            $this->lp_id,
+            'LearnpathAdded',
+            api_get_user_id()
+        );
+        api_item_property_update(
+            api_get_course_info($course_code),
+            TOOL_LEARNPATH,
+            $this->lp_id,
+            'visible',
+            api_get_user_id()
+        );
 
         $previous = 0;
         foreach ($this->aulist as $identifier => $dummy) {
@@ -286,15 +336,17 @@ class aicc extends learnpath {
             $previous = 0;
             $prereq = $oAu->prereq_string;
             //$previous = (!empty($this->au_order_list_new_id[x]) ? $this->au_order_list_new_id[x] : 0); // TODO: Deal with the previous.
-            $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order) " .
-                    "VALUES " .
-                    "($course_id, $lp_id, 'au','".$oAu->identifier."','".$title."'," .
-                    "'$path',0,100, $value_add" .
-                    "$parent, $previous, 0, " .
-                    "'$prereq', 0" .
-                    ")";
+            $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order) ".
+                "VALUES ".
+                "($course_id, $lp_id, 'au','".$oAu->identifier."','".$title."',".
+                "'$path',0,100, $value_add".
+                "$parent, $previous, 0, ".
+                "'$prereq', 0".
+                ")";
             $res_item = Database::query($sql_item);
-            if ($this->debug > 1) { error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : '.Database::error(), 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : '.Database::error(), 0);
+            }
             $item_id = Database::insert_id();
             // Now update previous item to change next_item_id.
             if ($previous != 0) {
@@ -306,52 +358,70 @@ class aicc extends learnpath {
         }
     }
 
-     /**
+    /**
      * Intermediate to import_package only to allow import from local zip files
-     * @param	string	Path to the zip file, from the dokeos sys root
-     * @param	string	Current path (optional)
-     * @return string	Absolute path to the AICC description files or empty string on error
+     * @param    string    Path to the zip file, from the dokeos sys root
+     * @param    string    Current path (optional)
+     * @return string    Absolute path to the AICC description files or empty string on error
      */
-    function import_local_package($file_path, $current_dir = '') {
+    function import_local_package($file_path, $current_dir = '')
+    {
         // TODO: Prepare info as given by the $_FILES[''] vector.
         $file_info = array();
         $file_info['tmp_name'] = $file_path;
         $file_info['name'] = basename($file_path);
+
         // Call the normal import_package function.
         return $this->import_package($file_info, $current_dir);
     }
 
     /**
      * Imports a zip file (presumably AICC) into the Chamilo structure
-     * @param	string	Zip file info as given by $_FILES['userFile']
-     * @return	string	Absolute path to the AICC config files directory or empty string on error
+     * @param    string    Zip file info as given by $_FILES['userFile']
+     * @return    string    Absolute path to the AICC config files directory or empty string on error
      */
-    function import_package($zip_file_info, $current_dir = '') {
-        if ($this->debug > 0) { error_log('In aicc::import_package('.print_r($zip_file_info, true).',"'.$current_dir.'") method', 0); }
+    function import_package($zip_file_info, $current_dir = '')
+    {
+        if ($this->debug > 0) {
+            error_log('In aicc::import_package('.print_r($zip_file_info, true).',"'.$current_dir.'") method', 0);
+        }
         //ini_set('error_log', 'E_ALL');
         $maxFilledSpace = 1000000000;
         $zip_file_path = $zip_file_info['tmp_name'];
         $zip_file_name = $zip_file_info['name'];
 
-        if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name, 0); }
-        $course_rel_dir  = api_get_course_path().'/scorm'; // Scorm dir web path starting from /courses
+        if ($this->debug > 0) {
+            error_log(
+                'New LP - aicc::import_package() - Zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name,
+                0
+            );
+        }
+        $course_rel_dir = api_get_course_path().'/scorm'; // Scorm dir web path starting from /courses
         $course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // The absolute system path of this course.
         $current_dir = replace_dangerous_char(trim($current_dir), 'strict'); // Current dir we are in, inside scorm/
-        if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Current_dir = '.$current_dir, 0); }
+        if ($this->debug > 0) {
+            error_log('New LP - aicc::import_package() - Current_dir = '.$current_dir, 0);
+        }
 
-         //$uploaded_filename = $_FILES['userFile']['name'];
+        //$uploaded_filename = $_FILES['userFile']['name'];
         // Get the name of the zip file without the extension.
-        if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Received zip file name: '.$zip_file_path, 0); }
+        if ($this->debug > 0) {
+            error_log('New LP - aicc::import_package() - Received zip file name: '.$zip_file_path, 0);
+        }
         $file_info = pathinfo($zip_file_name);
         $filename = $file_info['basename'];
         $extension = $file_info['extension'];
         $file_base_name = str_replace('.'.$extension, '', $filename); // Filename without its extension.
         $this->zipname = $file_base_name; // Save for later in case we don't have a title.
 
-        if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Base file name is : '.$file_base_name, 0); }
-        $new_dir = replace_dangerous_char(trim($file_base_name),'strict');
+        if ($this->debug > 0) {
+            error_log('New LP - aicc::import_package() - Base file name is : '.$file_base_name, 0);
+        }
+        $new_dir = replace_dangerous_char(trim($file_base_name), 'strict');
         $this->subdir = $new_dir;
-        if($this->debug > 0) { error_log('New LP - aicc::import_package() - Subdir is first set to : '.$this->subdir, 0); }
+        if ($this->debug > 0) {
+            error_log('New LP - aicc::import_package() - Subdir is first set to : '.$this->subdir, 0);
+        }
 
         /*
         if (check_name_exist($course_sys_dir.$current_dir.'/'.$new_dir)) {
@@ -375,20 +445,38 @@ class aicc extends learnpath {
         foreach ($zipContentArray as $thisContent) {
             if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
                 // If a php file is found, do not authorize (security risk).
-                if ($this->debug > 1) {error_log('New LP - aicc::import_package() - Found unauthorized file: '.$thisContent['filename'], 0); }
+                if ($this->debug > 1) {
+                    error_log(
+                        'New LP - aicc::import_package() - Found unauthorized file: '.$thisContent['filename'],
+                        0
+                    );
+                }
+
                 return api_failure::set_failure('php_file_in_zip_file');
             } elseif (preg_match('?.*/aicc/$?', $thisContent['filename'])) {
                 // If a directory named 'aicc' is found, package type = aicc, but continue,
                 // because we need to find the right AICC files;
-                if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Found aicc directory: '.$thisContent['filename'], 0); }
+                if ($this->debug > 1) {
+                    error_log('New LP - aicc::import_package() - Found aicc directory: '.$thisContent['filename'], 0);
+                }
                 $package_type = 'aicc';
             } else {
                 // else, look for one of the files we're searching for (something.crs case insensitive).
                 $res = array();
                 if (preg_match('?^(.*)\.(crs|au|des|cst|ore|pre|cmp)$?i', $thisContent['filename'], $res)) {
-                    if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Found AICC config file: '.$thisContent['filename'].'. Now splitting: '.$res[1].' and '.$res[2], 0); }
+                    if ($this->debug > 1) {
+                        error_log(
+                            'New LP - aicc::import_package() - Found AICC config file: '.$thisContent['filename'].'. Now splitting: '.$res[1].' and '.$res[2],
+                            0
+                        );
+                    }
                     if ($thisContent['filename'] == basename($thisContent['filename'])) {
-                        if ($this->debug > 2) { error_log('New LP - aicc::import_package() - '.$thisContent['filename'].' is at root level', 0); }
+                        if ($this->debug > 2) {
+                            error_log(
+                                'New LP - aicc::import_package() - '.$thisContent['filename'].' is at root level',
+                                0
+                            );
+                        }
                         $at_root = true;
                         if (!is_array($files_found[$res[1]])) {
                             $files_found[$res[1]] = $this->config_exts; // Initialise list of expected extensions (defined in class definition).
@@ -397,7 +485,7 @@ class aicc extends learnpath {
                         $subdir_isset = true;
                     } else {
                         if (!$subdir_isset) {
-                            if (preg_match('?^.*/aicc$?i',dirname($thisContent['filename']))) {
+                            if (preg_match('?^.*/aicc$?i', dirname($thisContent['filename']))) {
                                 //echo "Cutting subdir<br/>";
                                 $this->subdir .= '/'.substr(dirname($thisContent['filename']), 0, -5);
                             } else {
@@ -406,7 +494,12 @@ class aicc extends learnpath {
                             }
                             $subdir_isset = true;
                         }
-                        if ($this->debug > 2) { error_log('New LP - aicc::import_package() - '.$thisContent['filename'].' is not at root level - recording subdir '.$this->subdir, 0); }
+                        if ($this->debug > 2) {
+                            error_log(
+                                'New LP - aicc::import_package() - '.$thisContent['filename'].' is not at root level - recording subdir '.$this->subdir,
+                                0
+                            );
+                        }
                         $config_dir = dirname($thisContent['filename']); // Just the relative directory inside scorm/
                         if (!is_array($files_found[basename($res[1])])) {
                             $files_found[basename($res[1])] = $this->config_exts;
@@ -415,23 +508,34 @@ class aicc extends learnpath {
                     }
                     $package_type = 'aicc';
                 } else {
-                    if ($this->debug > 3) { error_log('New LP - aicc::import_package() - File '.$thisContent['filename'].' didnt match any check', 0); }
+                    if ($this->debug > 3) {
+                        error_log(
+                            'New LP - aicc::import_package() - File '.$thisContent['filename'].' didnt match any check',
+                            0
+                        );
+                    }
                 }
             }
             $realFileSize += $thisContent['size'];
         }
-        if ($this->debug > 2) { error_log('New LP - aicc::import_package() - $files_found: '.print_r($files_found, true), 0); }
-        if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Package type is now '.$package_type, 0); }
+        if ($this->debug > 2) {
+            error_log('New LP - aicc::import_package() - $files_found: '.print_r($files_found, true), 0);
+        }
+        if ($this->debug > 1) {
+            error_log('New LP - aicc::import_package() - Package type is now '.$package_type, 0);
+        }
         $mandatory = false;
         foreach ($files_found as $file_name => $file_exts) {
             $temp = (
                 !empty($files_found[$file_name]['crs'])
-                AND !empty($files_found[$file_name]['au'])
-                AND !empty($files_found[$file_name]['des'])
-                AND !empty($files_found[$file_name]['cst'])
+                    AND !empty($files_found[$file_name]['au'])
+                    AND !empty($files_found[$file_name]['des'])
+                        AND !empty($files_found[$file_name]['cst'])
             );
             if ($temp) {
-                if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Found all config files for '.$file_name, 0); }
+                if ($this->debug > 1) {
+                    error_log('New LP - aicc::import_package() - Found all config files for '.$file_name, 0);
+                }
                 $mandatory = true;
                 $package = $file_name;
                 // Store base config file name for reuse in parse_config_files().
@@ -443,13 +547,12 @@ class aicc extends learnpath {
             }
         }
 
-        if ($package_type == '' || !$mandatory)
-        // && defined('CHECK_FOR_AICC') && CHECK_FOR_AICC)
+        if ($package_type == '' || !$mandatory) // && defined('CHECK_FOR_AICC') && CHECK_FOR_AICC)
         {
             return api_failure::set_failure('not_aicc_content');
         }
 
-        if (!enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
+        if (!FileManager::enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
             return api_failure::set_failure('not_enough_space');
         }
 
@@ -470,9 +573,15 @@ class aicc extends learnpath {
             - parse & change relative html links
             - make sure the filenames are secure (filter funny characters or php extensions)
         */
-        if (is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir, api_get_permissions_for_new_directories())) {
+        if (is_dir($course_sys_dir.$new_dir) OR @mkdir(
+            $course_sys_dir.$new_dir,
+            api_get_permissions_for_new_directories()
+        )
+        ) {
             // PHP method - slower...
-            if ($this->debug >= 1) { error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir, 0); }
+            if ($this->debug >= 1) {
+                error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir, 0);
+            }
             $saved_dir = getcwd();
             chdir($course_sys_dir.$new_dir);
             $unzippingState = $zipFile->extract();
@@ -490,17 +599,21 @@ class aicc extends learnpath {
             }
             // Rename files, for example with \\ in it.
             if ($dir = @opendir($course_sys_dir.$new_dir)) {
-                if ($this->debug == 1) { error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0); }
+                if ($this->debug == 1) {
+                    error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0);
+                }
                 while ($file = readdir($dir)) {
                     if ($file != '.' && $file != '..') {
                         $filetype = 'file';
 
-                        if (is_dir($course_sys_dir.$new_dir.$file)) $filetype = 'folder';
+                        if (is_dir($course_sys_dir.$new_dir.$file)) {
+                            $filetype = 'folder';
+                        }
 
                         // TODO: RENAMING FILES CAN BE VERY DANGEROUS AICC-WISE, avoid that as much as possible!
                         //$safe_file = replace_dangerous_char($file, 'strict');
                         $find_str = array('\\', '.php', '.phtml');
-                        $repl_str = array('/',  '.txt', '.txt');
+                        $repl_str = array('/', '.txt', '.txt');
                         $safe_file = str_replace($find_str, $repl_str, $file);
 
                         if ($safe_file != $file) {
@@ -514,15 +627,21 @@ class aicc extends learnpath {
                                         $mybasedir = $mybasedir.$mysubdir.'/';
                                         if (!is_dir($mybasedir)) {
                                             @mkdir($mybasedir, api_get_permissions_for_new_directories());
-                                            if ($this->debug == 1) { error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.', 0); }
+                                            if ($this->debug == 1) {
+                                                error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.', 0);
+                                            }
                                         }
                                     }
                                 }
                             }
                             @rename($course_sys_dir.$new_dir.$file, $course_sys_dir.$new_dir.$safe_file);
-                            if ($this->debug == 1) { error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file, 0); }
+                            if ($this->debug == 1) {
+                                error_log(
+                                    'New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file,
+                                    0
+                                );
+                            }
                         }
-                        //set_default_settings($course_sys_dir, $safe_file, $filetype);
                     }
                 }
 
@@ -532,21 +651,26 @@ class aicc extends learnpath {
         } else {
             return '';
         }
+
         return $course_sys_dir.$new_dir.$config_dir;
     }
 
     /**
      * Sets the proximity setting in the database
-     * @param	string	Proximity setting
+     * @param    string    Proximity setting
      */
-    function set_proximity($proxy = '') {
+    function set_proximity($proxy = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In aicc::set_proximity('.$proxy.') method', 0); }
+        if ($this->debug > 0) {
+            error_log('In aicc::set_proximity('.$proxy.') method', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE c_id = ".$course_id." id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -555,16 +679,20 @@ class aicc extends learnpath {
 
     /**
      * Sets the theme setting in the database
-     * @param	string	Theme setting
+     * @param    string    Theme setting
      */
-    function set_theme($theme = '') {
+    function set_theme($theme = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In aicc::set_theme('.$theme.') method', 0); }
+        if ($this->debug > 0) {
+            error_log('In aicc::set_theme('.$theme.') method', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE c_id = ".$course_id." id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -573,16 +701,20 @@ class aicc extends learnpath {
 
     /**
      * Sets the image LP in the database
-     * @param	string	Theme setting
+     * @param    string    Theme setting
      */
-    function set_preview_image($preview_image = '') {
+    function set_preview_image($preview_image = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) {error_log('In aicc::set_preview_image('.$preview_image.') method', 0); }
+        if ($this->debug > 0) {
+            error_log('In aicc::set_preview_image('.$preview_image.') method', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET preview_image = '$preview_image' WHERE c_id = ".$course_id." id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -591,16 +723,20 @@ class aicc extends learnpath {
 
     /**
      * Sets the Author LP in the database
-     * @param	string	Theme setting
+     * @param    string    Theme setting
      */
-    function set_author($author = '') {
+    function set_author($author = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In aicc::set_author('.$author.') method', 0); }
+        if ($this->debug > 0) {
+            error_log('In aicc::set_author('.$author.') method', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET author = '$author' WHERE c_id = ".$course_id." id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -609,16 +745,20 @@ class aicc extends learnpath {
 
     /**
      * Sets the content maker setting in the database
-     * @param	string	Proximity setting
+     * @param    string    Proximity setting
      */
-    function set_maker($maker = '') {
+    function set_maker($maker = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In aicc::set_maker method('.$maker.')', 0); }
+        if ($this->debug > 0) {
+            error_log('In aicc::set_maker method('.$maker.')', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE c_id = ".$course_id." id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -627,10 +767,13 @@ class aicc extends learnpath {
 
     /**
      * Exports the current AICC object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
-     * @param	integer	Learnpath ID (optional, taken from object context if not defined)
+     * @param    integer    Learnpath ID (optional, taken from object context if not defined)
      */
-    function export_zip($lp_id = null) {
-        if ($this->debug > 0) { error_log('In aicc::export_zip method('.$lp_id.')', 0); }
+    function export_zip($lp_id = null)
+    {
+        if ($this->debug > 0) {
+            error_log('In aicc::export_zip method('.$lp_id.')', 0);
+        }
         if (empty($lp_id)) {
             if (!is_object($this)) {
                 return false;
@@ -646,10 +789,8 @@ class aicc extends learnpath {
         //error_log('New LP - in export_zip()', 0);
         // Zip everything that is in the corresponding scorm dir.
         // Write the zip file somewhere (might be too big to return).
-        require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-        require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+
         require_once api_get_path(LIBRARY_PATH).'document.lib.php';
-        require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
         require_once 'learnpath_functions.inc.php';
         $course_id = api_get_course_int_id();
         $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
@@ -683,7 +824,7 @@ class aicc extends learnpath {
         //DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.".zip");
         DocumentManager :: file_send_for_download($zipfilename, true);
 
-        // Delete the temporary zip file and directory in fileManage.lib.php
+        // Delete the temporary zip file and directory in fileManager.lib.php
         FileManager::my_delete($zipfilename);
         FileManager::my_delete($zipfoldername);
 
@@ -692,26 +833,33 @@ class aicc extends learnpath {
 
     /**
      * Gets a resource's path if available, otherwise return empty string
-     * @param	string	Resource ID as used in resource array
-     * @return string	The resource's path as declared in config file course.crs
+     * @param    string    Resource ID as used in resource array
+     * @return string    The resource's path as declared in config file course.crs
      */
-    function get_res_path($id) {
-        if ($this->debug > 0) { error_log('In aicc::get_res_path('.$id.') method', 0); }
+    function get_res_path($id)
+    {
+        if ($this->debug > 0) {
+            error_log('In aicc::get_res_path('.$id.') method', 0);
+        }
         $path = '';
         if (isset($this->resources[$id])) {
             $oRes =& $this->resources[$id];
             $path = @$oRes->get_path();
         }
+
         return $path;
     }
 
     /**
      * Gets a resource's type if available, otherwise return empty string
-     * @param	string	Resource ID as used in resource array
-     * @return string	The resource's type as declared in the assignable unit (.au) file
+     * @param    string    Resource ID as used in resource array
+     * @return string    The resource's type as declared in the assignable unit (.au) file
      */
-    function get_res_type($id) {
-        if ($this->debug > 0) { error_log('In aicc::get_res_type('.$id.') method', 0); }
+    function get_res_type($id)
+    {
+        if ($this->debug > 0) {
+            error_log('In aicc::get_res_type('.$id.') method', 0);
+        }
         $type = '';
         if (isset($this->resources[$id])) {
             $oRes =& $this->resources[$id];
@@ -720,15 +868,19 @@ class aicc extends learnpath {
                 $type = $temptype;
             }
         }
+
         return $type;
     }
 
     /**
      * Gets the default organisation's title
-     * @return	string	The organization's title
+     * @return    string    The organization's title
      */
-    function get_title(){
-        if ($this->debug > 0) { error_log('In aicc::get_title() method', 0); }
+    function get_title()
+    {
+        if ($this->debug > 0) {
+            error_log('In aicc::get_title() method', 0);
+        }
         $title = '';
         if (isset($this->config['organizations']['default'])) {
             $title = $this->organizations[$this->config['organizations']['default']]->get_name();
@@ -739,6 +891,7 @@ class aicc extends learnpath {
                 break;
             }
         }
+
         return $title;
     }
 
@@ -747,8 +900,12 @@ class aicc extends learnpath {
      * updating the existing table... This will prove very useful in case initial data
      * from config files were not imported well enough.
      */
-    function reimport_aicc() {
-        if ($this->debug > 0) { error_log('In aicc::reimport_aicc() method', 0); }
+    function reimport_aicc()
+    {
+        if ($this->debug > 0) {
+            error_log('In aicc::reimport_aicc() method', 0);
+        }
+
         //query current items list
         //get the identifiers
         //parse the config files
@@ -760,10 +917,11 @@ class aicc extends learnpath {
     /**
      * Static function to parse AICC ini files.
      * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file()).
-     * @param	string	File path
-     * @return	array	Structured array
+     * @param    string    File path
+     * @return    array    Structured array
      */
-    function parse_ini_file_quotes_safe($f) {
+    function parse_ini_file_quotes_safe($f)
+    {
         $null = '';
         $r = $null;
         $sec = $null;
@@ -800,17 +958,19 @@ class aicc extends learnpath {
                 }
             }
         }
+
         return $r;
     }
 
     /**
      * Static function to parse AICC ini strings.
      * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file()).
-     * @param		string	INI File string
-     * @param		array	List of names of sections that should be considered as containing only hard string data (no variables), provided in lower case
-     * @return	array	Structured array
+     * @param        string    INI File string
+     * @param        array    List of names of sections that should be considered as containing only hard string data (no variables), provided in lower case
+     * @return    array    Structured array
      */
-    function parse_ini_string_quotes_safe($s, $pure_strings = array()) {
+    function parse_ini_string_quotes_safe($s, $pure_strings = array())
+    {
         $null = '';
         $r = $null;
         $sec = $null;
@@ -857,19 +1017,21 @@ class aicc extends learnpath {
                 }
             }
         }
+
         return $r;
     }
 
     /**
      * Static function that parses CSV files into simple arrays, based on a function
      * by spam at cyber-space dot nl published on php.net (fgetcsv()).
-     * @param	string	Filepath
-     * @param	string	CSV delimiter
-     * @param	string	CSV enclosure
-     * @param	boolean	Might one field name happen more than once on the same line? (then split by comma in the values)
-     * @return array	Simple structured array
+     * @param    string    Filepath
+     * @param    string    CSV delimiter
+     * @param    string    CSV enclosure
+     * @param    boolean    Might one field name happen more than once on the same line? (then split by comma in the values)
+     * @return array    Simple structured array
      */
-    function parse_csv_file($f, $delim = ',', $enclosure = '"', $multiples = false) {
+    function parse_csv_file($f, $delim = ',', $enclosure = '"', $multiples = false)
+    {
         $data = @file_get_contents($f);
         $data = api_convert_encoding($data, api_get_system_encoding(), $this->config_encoding);
         $enclosed = false;
@@ -880,40 +1042,46 @@ class aicc extends learnpath {
             $chr = $data{$i};
             switch ($chr) {
                 case $enclosure:
-                    if ($enclosed && $data{$i+1} == $enclosure) {
+                    if ($enclosed && $data{$i + 1} == $enclosure) {
                         $fldval .= $chr;
                         ++$i; // Skip the next character.
-                    } else
+                    } else {
                         $enclosed = !$enclosed;
+                    }
                     break;
                 case $delim:
                     if (!$enclosed) {
                         $ret_array[$linecount][$fldcount++] = $fldval;
                         $fldval = '';
-                    } else
+                    } else {
                         $fldval .= $chr;
+                    }
                     break;
                 case "\r":
-                    if (!$enclosed&&$data{$i+1} == "\n")
+                    if (!$enclosed && $data{$i + 1} == "\n") {
                         continue;
+                    }
                 case "\n":
                     if (!$enclosed) {
                         $ret_array[$linecount++][$fldcount] = $fldval;
                         $fldcount = 0;
                         $fldval = '';
-                    } else
+                    } else {
                         $fldval .= $chr;
+                    }
                     break;
                 case "\\r":
-                    if (!$enclosed&&$data{$i+1} == "\\n")
+                    if (!$enclosed && $data{$i + 1} == "\\n") {
                         continue;
+                    }
                 case "\\n":
                     if (!$enclosed) {
                         $ret_array[$linecount++][$fldcount] = $fldval;
                         $fldcount = 0;
                         $fldval = '';
-                    } else
+                    } else {
                         $fldval .= $chr;
+                    }
                     break;
                 default:
                     $fldval .= $chr;
@@ -939,6 +1107,7 @@ class aicc extends learnpath {
                 }
             }
         }
+
         return $ret_ret_array;
     }
 }

Fișier diff suprimat deoarece este prea mare
+ 335 - 219
main/newscorm/learnpath.class.php


Fișier diff suprimat deoarece este prea mare
+ 224 - 93
main/newscorm/learnpathItem.class.php


Fișier diff suprimat deoarece este prea mare
+ 321 - 179
main/newscorm/learnpath_functions.inc.php


+ 155 - 128
main/newscorm/lp_admin_view.php

@@ -9,10 +9,10 @@
  * @author Roan Embrechts, refactoring and code cleaning
  * @author Yannick Warnier <ywarnier@beeznest.org> - cleaning and update for new SCORM tool
  * @package chamilo.learnpath
-*/
+ */
 
 /**
- * INIT SECTION 
+ * INIT SECTION
  */
 
 $this_section = SECTION_COURSES;
@@ -31,18 +31,18 @@ $language_file = "learnpath";
 
 $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
 
-$tbl_lp      = Database::get_course_table(TABLE_LP_MAIN);
+$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
 $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
 
-$isStudentView  = (int) $_REQUEST['isStudentView'];
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-$submit			= $_POST['submit_button'];
+$isStudentView = (int)$_REQUEST['isStudentView'];
+$learnpath_id = (int)$_REQUEST['lp_id'];
+$submit = $_POST['submit_button'];
 
 /* MAIN CODE */
 
 // Using the resource linker as a tool for adding resources to the learning path.
 if ($action == 'add' and $type == 'learnpathitem') {
-     $htmlHeadXtra[] = "<script> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
+    $htmlHeadXtra[] = "<script> window.location=\"../resourcelinker/resourcelinker.php?source_id=5&action=$action&learnpath_id=$learnpath_id&chapter_id=$chapter_id&originalresource=no\"; </script>";
 }
 if ((!$is_allowed_to_edit) || ($isStudentView)) {
     error_log('New LP - User not authorized in lp_admin_view.php');
@@ -50,7 +50,7 @@ if ((!$is_allowed_to_edit) || ($isStudentView)) {
 }
 // From here on, we are admin because of the previous condition, so don't check anymore.
 
-$course_id = api_get_course_int_id(); 
+$course_id = api_get_course_int_id();
 
 $sql_query = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND id = $learnpath_id";
 $result = Database::query($sql_query);
@@ -63,15 +63,21 @@ if (isset($_SESSION['gradebook'])) {
 }
 
 if (!empty($gradebook) && $gradebook == 'view') {
-    $interbreadcrumb[] = array (
-            'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-            'name' => get_lang('ToolGradebook')
-        );
+    $interbreadcrumb[] = array(
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+        'name' => get_lang('ToolGradebook')
+    );
 }
 
 $interbreadcrumb[] = array('url' => 'lp_controller.php?action=list', 'name' => get_lang('LearningPaths'));
-$interbreadcrumb[] = array('url' => api_get_self()."?action=build&lp_id=$learnpath_id", "name" => stripslashes("{$therow['name']}"));
-$interbreadcrumb[] = array('url' => api_get_self()."?action=add_item&type=step&lp_id=$learnpath_id", 'name' => get_lang('NewStep'));
+$interbreadcrumb[] = array(
+    'url' => api_get_self()."?action=build&lp_id=$learnpath_id",
+    "name" => stripslashes("{$therow['name']}")
+);
+$interbreadcrumb[] = array(
+    'url' => api_get_self()."?action=add_item&type=step&lp_id=$learnpath_id",
+    'name' => get_lang('NewStep')
+);
 
 if (isset($_REQUEST['updateaudio'])) {
     $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('UpdateAllAudioFragments'));
@@ -88,10 +94,10 @@ $lp_theme_css = $_SESSION['oLP']->get_theme();
 
 // POST action handling (uploading mp3, deleting mp3)
 if (isset($_POST['save_audio'])) {
-    
+
     //Updating the lp.modified_on
-    $_SESSION['oLP']->set_modified_on();                
-                
+    $_SESSION['oLP']->set_modified_on();
+
     // Deleting the audio fragments.
     foreach ($_POST as $key => $value) {
         if (substr($key, 0, 9) == 'removemp3') {
@@ -101,10 +107,10 @@ if (isset($_POST['save_audio'])) {
             $in = implode(',', $lp_items_to_remove_audio);
         }
     }
-    if (count($lp_items_to_remove_audio)>0) {
-        $sql 	= "UPDATE $tbl_lp_item SET audio = '' WHERE c_id = $course_id AND id IN (".$in.")";
+    if (count($lp_items_to_remove_audio) > 0) {
+        $sql = "UPDATE $tbl_lp_item SET audio = '' WHERE c_id = $course_id AND id IN (".$in.")";
         $result = Database::query($sql);
-    }           
+    }
 
     // Uploading the audio files.
     foreach ($_FILES as $key => $value) {
@@ -117,19 +123,30 @@ if (isset($_POST['save_audio'])) {
             $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
             if (!is_dir($filepath.'audio')) {
                 mkdir($filepath.'audio', api_get_permissions_for_new_directories());
-                $audio_id = add_document($_course, '/audio', 'folder', 0, 'audio');
-                api_item_property_update($_course, TOOL_DOCUMENT, $audio_id, 'FolderCreated', api_get_user_id(), null, null, null, null, api_get_session_id());
+                $audio_id = FileManager::add_document($_course, '/audio', 'folder', 0, 'audio');
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $audio_id,
+                    'FolderCreated',
+                    api_get_user_id(),
+                    null,
+                    null,
+                    null,
+                    null,
+                    api_get_session_id()
+                );
             }
 
             // Check if file already exits into document/audio/
             $file_name = $_FILES[$key]['name'];
             $file_name = stripslashes($file_name);
             // Add extension to files without one (if possible).
-            $file_name = add_ext_on_mime($file_name, $_FILES[$key]['type']);
+            $file_name = FileManager::add_ext_on_mime($file_name, $_FILES[$key]['type']);
 
             $clean_name = replace_dangerous_char($file_name);
             // No "dangerous" files.
-            $clean_name = disable_dangerous_file($clean_name);
+            $clean_name = FileManager::disable_dangerous_file($clean_name);
 
             $check_file_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/audio/'.$clean_name;
 
@@ -141,14 +158,24 @@ if (isset($_POST['save_audio'])) {
                 // Adding something random to prevent overwriting.
                 $filename_components[count($filename_components) - 1] = time();
                 // Reconstructing the new filename.
-                $clean_name = implode($filename_components) .'.'.$file_extension;
+                $clean_name = implode($filename_components).'.'.$file_extension;
                 // Using the new name in the $_FILES superglobal.
                 $_FILES[$key]['name'] = $clean_name;
             }
 
-            // Upload the file in the documents tool.
-            include_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-            $file_path = handle_uploaded_document($_course, $_FILES[$key], api_get_path(SYS_COURSE_PATH).$_course['path'].'/document','/audio', api_get_user_id(), '', '', '', '', false);
+            // Upload the file in the documents tool
+            $file_path = FileManager::handle_uploaded_document(
+                $_course,
+                $_FILES[$key],
+                api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
+                '/audio',
+                api_get_user_id(),
+                '',
+                '',
+                '',
+                '',
+                false
+            );
 
             // Getting the filename only.
             $file_components = explode('/', $file_path);
@@ -156,7 +183,7 @@ if (isset($_POST['save_audio'])) {
 
             // Store the mp3 file in the lp_item table.
             $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
-            $sql_insert_audio = "UPDATE $tbl_lp_item SET audio = '".Database::escape_string($file)."' 
+            $sql_insert_audio = "UPDATE $tbl_lp_item SET audio = '".Database::escape_string($file)."'
                                  WHERE c_id = $course_id AND id = '".Database::escape_string($lp_item_id)."'";
             Database::query($sql_insert_audio);
         }
@@ -174,110 +201,110 @@ $suredel = trim(get_lang('AreYouSureToDelete'));
 ?>
 <script>
 
-var newOrderData= "";
-//source code found in http://www.swartzfager.org/blog/dspNestedList.cfm
+    var newOrderData = "";
+    //source code found in http://www.swartzfager.org/blog/dspNestedList.cfm
 
-$(function() {
+    $(function () {
     <?php
-    if (!isset($_REQUEST['updateaudio'])) { 
-    ?>
-	$("#lp_item_list").sortable({ 
-		items: "li",
-		handle: ".moved", //only the class "moved" 
-		cursor: "move",  
-		placeholder: "ui-state-highlight", //defines the yellow highlight			   
-	});	
-
-	$("#listSubmit").click(function () {
-		//Disable the submit button to prevent a double-click
-		$(this).attr("disabled","disabled");
-		//Initialize the variable that will contain the data to submit to the form
-		newOrderData= "";
-		//All direct descendants of the lp_item_list will have a parentId of 0
-		var parentId= 0;
-		
-		//Walk through the direct descendants of the lp_item_list <ul>
-		$("#lp_item_list").children().each(function () {
-			
-			/*Only process elements with an id attribute (in order to skip the blank,
-			unmovable <li> elements.*/
-			
-			if ($(this).attr("id")) {
-					/*Build a string of data with the child's ID and parent ID, 
-					 using the "|" as a delimiter between the two IDs and the "^" 
-					 as a record delimiter (these delimiters were chosen in case the data
-					 involved includes more common delimiters like commas within the content)
-					*/
-					newOrderData= newOrderData + $(this).attr("id") + "|" + "0" + "^";
-					
-					//Determine if this child is a containter
-					if ($(this).is(".li_container")) {
-						  //Process the child elements of the container
+    if (!isset($_REQUEST['updateaudio'])) {
+        ?>
+        $("#lp_item_list").sortable({
+            items:"li",
+            handle:".moved", //only the class "moved"
+            cursor:"move",
+            placeholder:"ui-state-highlight", //defines the yellow highlight
+        });
+
+        $("#listSubmit").click(function () {
+            //Disable the submit button to prevent a double-click
+            $(this).attr("disabled", "disabled");
+            //Initialize the variable that will contain the data to submit to the form
+            newOrderData = "";
+            //All direct descendants of the lp_item_list will have a parentId of 0
+            var parentId = 0;
+
+            //Walk through the direct descendants of the lp_item_list <ul>
+            $("#lp_item_list").children().each(function () {
+
+                /*Only process elements with an id attribute (in order to skip the blank,
+                unmovable <li> elements.*/
+
+                if ($(this).attr("id")) {
+                    /*Build a string of data with the child's ID and parent ID,
+                     using the "|" as a delimiter between the two IDs and the "^"
+                     as a record delimiter (these delimiters were chosen in case the data
+                     involved includes more common delimiters like commas within the content)
+                    */
+                    newOrderData = newOrderData + $(this).attr("id") + "|" + "0" + "^";
+
+                    //Determine if this child is a containter
+                    if ($(this).is(".li_container")) {
+                        //Process the child elements of the container
                         processChildren($(this).attr("id"));
-					}
-				}
-			
-		}); //end of lp_item_list children loop
-		
-		//Write the newOrderData string out to the listResults form element
-		//$("#listResults").val(newOrderData);
-		var order = "new_order="+ newOrderData + "&a=update_lp_item_order";
-		$.post("<?php echo api_get_path(WEB_AJAX_PATH)?>lp.ajax.php", order, function(reponse){
-            $("#message").html(reponse);
-        }); 
-
-		 setTimeout(function() {
-		        $("#message").html('');
-		    }, 3000);
-						
-		return false;
-		
-	}); //end of lp_item_list event assignment
-	
-	<?php } ?>
-	function processChildren(parentId) {
-		//Loop through the children of the UL element defined by the parentId
-		var ulParentID= "UL_" + parentId;
-		$("#" + ulParentID).children().each(function () {
-			
-			/*Only process elements with an id attribute (in order to skip the blank,
-				unmovable <li> elements.*/
-				
-			if ($(this).attr("id")) {
-                /*Build a string of data with the child's ID and parent ID, 
-                    using the "|" as a delimiter between the two IDs and the "^" 
-                    as a record delimiter (these delimiters were chosen in case the data
-                    involved includes more common delimiters like commas within the content)
-                */
-                newOrderData= newOrderData + $(this).attr("id") + "|" + parentId + "^";
-
-                //Determine if this child is a containter
-                if ($(this).is(".container")) {
-                    //Process the child elements of the container
-                    processChildren($(this).attr("id"));
+                    }
                 }
-            }				
-		});  //end of children loop		
-	} //end of processChildren function	
-});
-
-/* <![CDATA[ */
-function stripslashes(str) {
-    str=str.replace(/\\'/g,'\'');
-    str=str.replace(/\\"/g,'"');
-    str=str.replace(/\\\\/g,'\\');
-    str=str.replace(/\\0/g,'\0');
-    return str;
-}
 
-function confirmation(name) {
-    name=stripslashes(name);
-    if (confirm("<?php echo $suredel; ?> " + name + " ?")) {
-        return true;
-    } else {
-        return false;
+            }); //end of lp_item_list children loop
+
+            //Write the newOrderData string out to the listResults form element
+            //$("#listResults").val(newOrderData);
+            var order = "new_order=" + newOrderData + "&a=update_lp_item_order";
+            $.post("<?php echo api_get_path(WEB_AJAX_PATH)?>lp.ajax.php", order, function (reponse) {
+                $("#message").html(reponse);
+            });
+
+            setTimeout(function () {
+                $("#message").html('');
+            }, 3000);
+
+            return false;
+
+        }); //end of lp_item_list event assignment
+
+        <?php } ?>
+        function processChildren(parentId) {
+            //Loop through the children of the UL element defined by the parentId
+            var ulParentID = "UL_" + parentId;
+            $("#" + ulParentID).children().each(function () {
+
+                /*Only process elements with an id attribute (in order to skip the blank,
+                    unmovable <li> elements.*/
+
+                if ($(this).attr("id")) {
+                    /*Build a string of data with the child's ID and parent ID,
+                        using the "|" as a delimiter between the two IDs and the "^"
+                        as a record delimiter (these delimiters were chosen in case the data
+                        involved includes more common delimiters like commas within the content)
+                    */
+                    newOrderData = newOrderData + $(this).attr("id") + "|" + parentId + "^";
+
+                    //Determine if this child is a containter
+                    if ($(this).is(".container")) {
+                        //Process the child elements of the container
+                        processChildren($(this).attr("id"));
+                    }
+                }
+            });  //end of children loop
+        } //end of processChildren function
+    });
+
+    /* <![CDATA[ */
+    function stripslashes(str) {
+        str = str.replace(/\\'/g, '\'');
+        str = str.replace(/\\"/g, '"');
+        str = str.replace(/\\\\/g, '\\');
+        str = str.replace(/\\0/g, '\0');
+        return str;
+    }
+
+    function confirmation(name) {
+        name = stripslashes(name);
+        if (confirm("<?php echo $suredel; ?> " + name + " ?")) {
+            return true;
+        } else {
+            return false;
+        }
     }
-}
 </script>
 <?php
 
@@ -285,7 +312,7 @@ echo $_SESSION['oLP']->build_action_menu();
 
 echo '<div class="row-fluid">';
 echo '<div class="span3">';
-echo $_SESSION['oLP']->return_new_tree(null, true); 
+echo $_SESSION['oLP']->return_new_tree(null, true);
 echo '</div>';
 
 echo '<div class="span9">';

+ 45 - 35
main/newscorm/openoffice_document.class.php

@@ -6,14 +6,15 @@
  * Defines the OpenofficeDocument class, which is meant as a mother class
  * to help in the conversion of Office documents to learning paths
  * @package chamilo.learnpath
- * @author	Eric Marguin <eric.marguin@dokeos.com>
- * @license	GNU/GPL
+ * @author    Eric Marguin <eric.marguin@dokeos.com>
+ * @license    GNU/GPL
  */
 
 /**
  * Defines the "OpenofficeDocument" child of class "learnpath"
  */
-abstract class OpenofficeDocument extends learnpath {
+abstract class OpenofficeDocument extends learnpath
+{
 
     public $first_item = 0;
     public $original_charset = 'utf-8';
@@ -21,11 +22,12 @@ abstract class OpenofficeDocument extends learnpath {
 
     /**
      * Class constructor. Based on the parent constructor.
-     * @param	string	Course code
-     * @param	integer	Learnpath ID in DB
-     * @param	integer	User ID
+     * @param    string    Course code
+     * @param    integer    Learnpath ID in DB
+     * @param    integer    User ID
      */
-    public function __construct($course_code = null, $resource_id = null, $user_id = null) {
+    public function __construct($course_code = null, $resource_id = null, $user_id = null)
+    {
         if ($this->debug > 0) {
             error_log('In OpenofficeDocument::OpenofficeDocument()', 0);
         }
@@ -36,20 +38,21 @@ abstract class OpenofficeDocument extends learnpath {
         }
     }
 
-    public function convert_document($file, $action_after_conversion = 'make_lp') {
+    public function convert_document($file, $action_after_conversion = 'make_lp')
+    {
         global $_course, $_user, $_configuration;
-        $this->file_name = pathinfo($file['name'], PATHINFO_FILENAME);        
+        $this->file_name = pathinfo($file['name'], PATHINFO_FILENAME);
+        // Create the directory
+        $result = $this->generate_lp_folder($_course, $this->file_name);
+
         // Create the directory
-        $result = $this->generate_lp_folder($_course, $this->file_name);                        
-                
-         // Create the directory
         $this->base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
         ///learning_path/ppt_dirname directory
-        $this->created_dir = substr($result['dir'], 0, strlen($result['dir']) -1);        
+        $this->created_dir = substr($result['dir'], 0, strlen($result['dir']) - 1);
         $this->file_path = $this->created_dir.'/'.replace_dangerous_char($file['name'], 'strict');
-        
+
         //var_dump($this->file_name, $this->file_path, $this->base_work_dir, $this->created_dir);
-    
+
         /*
          * Original code
         global $_course, $_user, $_configuration;
@@ -68,10 +71,10 @@ abstract class OpenofficeDocument extends learnpath {
         // Create the directory.
         $this->base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
 
-        $this->created_dir = create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), 0, 0, $this->base_work_dir, $dir_name);
-       
+        $this->created_dir = FileManager::create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), 0, 0, $this->base_work_dir, $dir_name);
+
             var_dump($this->file_name, $this->file_path, $this->base_work_dir, $this->created_dir);
-        
+
         */
 
         $ppt2lp_host = api_get_setting('service_ppt2lp', 'host');
@@ -82,45 +85,49 @@ abstract class OpenofficeDocument extends learnpath {
             $perm = api_get_setting('permissions_for_new_files');
 
             if (IS_WINDOWS_OS) { // IS_WINDOWS_OS has been defined in main_api.lib.php
-                $converter_path = str_replace('/', '\\', api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png');
-                $class_path = $converter_path . ';' . $converter_path . '/jodconverter-2.2.2.jar;' . $converter_path . '/jodconverter-cli-2.2.2.jar';
+                $converter_path = str_replace('/', '\\', api_get_path(SYS_PATH).'main/inc/lib/ppt2png');
+                $class_path = $converter_path.';'.$converter_path.'/jodconverter-2.2.2.jar;'.$converter_path.'/jodconverter-cli-2.2.2.jar';
                 //$cmd = 'java -cp "'.$class_path.'" DokeosConverter';
-                $cmd = 'java -Dfile.encoding=UTF-8 -cp "' . $class_path . '" DokeosConverter';
+                $cmd = 'java -Dfile.encoding=UTF-8 -cp "'.$class_path.'" DokeosConverter';
             } else {
-                $converter_path = api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png';
+                $converter_path = api_get_path(SYS_PATH).'main/inc/lib/ppt2png';
                 //$class_path = '-cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar';
                 $class_path = ' -Dfile.encoding=UTF-8 -cp .:jodconverter-2.2.2.jar:jodconverter-cli-2.2.2.jar';
-                $cmd = 'cd ' . $converter_path . ' && java ' . $class_path . ' DokeosConverter';
+                $cmd = 'cd '.$converter_path.' && java '.$class_path.' DokeosConverter';
             }
 
-            $cmd .= ' -p ' . api_get_setting('service_ppt2lp', 'port');
+            $cmd .= ' -p '.api_get_setting('service_ppt2lp', 'port');
             // Call to the function implemented by child.
             $cmd .= $this->add_command_parameters();
-            // To allow openoffice to manipulate docs.            
+            // To allow openoffice to manipulate docs.
             @chmod($this->base_work_dir, 0777);
             @chmod($this->base_work_dir.$this->created_dir, 0777);
             @chmod($this->base_work_dir.$this->file_path, 0777);
 
             $locale = $this->original_locale; // TODO: Improve it because we're not sure this locale is present everywhere.
-            putenv('LC_ALL=' . $locale);
+            putenv('LC_ALL='.$locale);
 
             $files = array();
             $return = 0;
             $shell = exec($cmd, $files, $return);
-            
+
             if ($return != 0) { // If the java application returns an error code.
                 switch ($return) {
                     // Can't connect to openoffice.
-                    case 1: $this->error = get_lang('CannotConnectToOpenOffice');
+                    case 1:
+                        $this->error = get_lang('CannotConnectToOpenOffice');
                         break;
                     // Conversion failed in openoffice.
-                    case 2: $this->error = get_lang('OogieConversionFailed');
+                    case 2:
+                        $this->error = get_lang('OogieConversionFailed');
                         break;
                     // Conversion can't be launch because command failed.
-                    case 255: $this->error = get_lang('OogieUnknownError');
+                    case 255:
+                        $this->error = get_lang('OogieUnknownError');
                         break;
                 }
                 DocumentManager::delete_document($_course, $this->created_dir, $this->base_work_dir);
+
                 return false;
             }
         } else {
@@ -133,15 +140,15 @@ abstract class OpenofficeDocument extends learnpath {
             if (!empty($result['images'])) {
                 foreach ($result['images'] as $image => $img_data) {
                     $image_path = $this->base_work_dir.$this->created_dir;
-                    @file_put_contents($image_path . '/' . $image, base64_decode($img_data));
-                    @chmod($image_path . '/' . $image, 0777);
+                    @file_put_contents($image_path.'/'.$image, base64_decode($img_data));
+                    @chmod($image_path.'/'.$image, 0777);
                 }
             }
 
             // files info
             $files = $result['files'];
         }
-        
+
         if (!empty($files)) {
             // Create lp
             $this->lp_id = learnpath::add_lp($_course['id'], $this->file_name, '', 'guess', 'manual');
@@ -157,6 +164,7 @@ abstract class OpenofficeDocument extends learnpath {
             }
             chmod($this->base_work_dir, api_get_permissions_for_new_directories());
         }
+
         return $this->first_item;
     }
 
@@ -165,8 +173,9 @@ abstract class OpenofficeDocument extends learnpath {
      * @param   array current ppt file
      * @return  array images files
      */
-    private function _get_remote_ppt2lp_files($file) {
-        require_once api_get_path(LIBRARY_PATH) . 'nusoap/nusoap.php';
+    private function _get_remote_ppt2lp_files($file)
+    {
+        require_once api_get_path(LIBRARY_PATH).'nusoap/nusoap.php';
         // host
         $ppt2lp_host = api_get_setting('service_ppt2lp', 'host');
 
@@ -195,6 +204,7 @@ abstract class OpenofficeDocument extends learnpath {
         } else {
             return false;
         }
+
         return $result;
     }
 

+ 121 - 34
main/newscorm/openoffice_presentation.class.php

@@ -20,27 +20,34 @@ if (api_get_setting('search_enabled') == 'true') {
     require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
 }
 
-class OpenofficePresentation extends OpenofficeDocument {
+class OpenofficePresentation extends OpenofficeDocument
+{
 
     public $take_slide_name;
 
-    public function __construct($take_slide_name = false, $course_code = null, $resource_id = null, $user_id = null) {
+    public function __construct($take_slide_name = false, $course_code = null, $resource_id = null, $user_id = null)
+    {
         $this->take_slide_name = $take_slide_name;
         parent::__construct($course_code, $resource_id, $user_id);
     }
 
 
-    public function make_lp($files = array()) {
+    public function make_lp($files = array())
+    {
         global $_course;
         $previous = 0;
         $i = 0;
 
-        if (!is_dir($this->base_work_dir.$this->created_dir))
+        if (!is_dir($this->base_work_dir.$this->created_dir)) {
             return false;
+        }
 
         foreach ($files as $file) {
 
-            list($slide_name, $file_name, $slide_body) = explode('||', $file); // '||' is used as separator between fields: slide name (with accents) || file name (without accents) || all slide text (to be indexed).
+            list($slide_name, $file_name, $slide_body) = explode(
+                '||',
+                $file
+            ); // '||' is used as separator between fields: slide name (with accents) || file name (without accents) || all slide text (to be indexed).
 
             // Filename is utf8 encoded, but when we decode, some chars are not translated (like quote &rsquo;).
             // so we remove these chars by translating it in htmlentities and the reconvert it in want charset.
@@ -58,53 +65,105 @@ class OpenofficePresentation extends OpenofficeDocument {
 
             $i++;
             // Add the png to documents.
-            $document_id = add_document($_course, $this->created_dir.'/'.urlencode($file_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$file_name), $slide_name);
-            api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), 0, 0, null, null, api_get_session_id());
+            $document_id = FileManager::add_document(
+                $_course,
+                $this->created_dir.'/'.urlencode($file_name),
+                'file',
+                filesize($this->base_work_dir.$this->created_dir.'/'.$file_name),
+                $slide_name
+            );
+            api_item_property_update(
+                $_course,
+                TOOL_DOCUMENT,
+                $document_id,
+                'DocumentAdded',
+                api_get_user_id(),
+                0,
+                0,
+                null,
+                null,
+                api_get_session_id()
+            );
 
             // Generating the thumbnail.
-            $image = $this->base_work_dir.$this->created_dir .'/'. $file_name;
+            $image = $this->base_work_dir.$this->created_dir.'/'.$file_name;
 
             $pattern = '/(\w+)\.png$/';
             $replacement = '${1}_thumb.png';
             $thumb_name = preg_replace($pattern, $replacement, $file_name);
-            
+
             // Calculate thumbnail size.
             $image_size = api_getimagesize($image);
-            $width  = $image_size['width'];
+            $width = $image_size['width'];
             $height = $image_size['height'];
-            
+
             $thumb_width = 300;
             $thumb_height = floor($height * ($thumb_width / $width));
-  
+
             $my_new_image = new Image($image);
             $my_new_image->resize($thumb_width, $thumb_height);
-            $my_new_image->send_image($this->base_work_dir.$this->created_dir .'/'. $thumb_name, -1, 'png');
-  
+            $my_new_image->send_image($this->base_work_dir.$this->created_dir.'/'.$thumb_name, -1, 'png');
+
             // Adding the thumbnail to documents.
-            $document_id_thumb = add_document($_course, $this->created_dir.'/'.urlencode($thumb_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$thumb_name), $slide_name);
-            api_item_property_update($_course, TOOL_THUMBNAIL, $document_id_thumb, 'DocumentAdded', api_get_user_id(), 0, 0);
+            $document_id_thumb = FileManager::add_document(
+                $_course,
+                $this->created_dir.'/'.urlencode($thumb_name),
+                'file',
+                filesize($this->base_work_dir.$this->created_dir.'/'.$thumb_name),
+                $slide_name
+            );
+            api_item_property_update(
+                $_course,
+                TOOL_THUMBNAIL,
+                $document_id_thumb,
+                'DocumentAdded',
+                api_get_user_id(),
+                0,
+                0
+            );
 
             // Create an html file.
             $html_file = $file_name.'.html';
             $fp = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file, 'w+');
 
-            $slide_src = api_get_path(REL_COURSE_PATH).$_course['path'].'/document/'.$this->created_dir.'/'.utf8_encode($file_name);
+            $slide_src = api_get_path(REL_COURSE_PATH).$_course['path'].'/document/'.$this->created_dir.'/'.utf8_encode(
+                $file_name
+            );
             $slide_src = str_replace('//', '/', $slide_src);
-            fwrite($fp,
-'<html>
+            fwrite(
+                $fp,
+                '<html>
     <head>
     </head>
     <body>
         <img src="'.$slide_src.'" />
     </body>
-</html>');  // This indentation is to make the generated html files to look well.
+</html>'
+            ); // This indentation is to make the generated html files to look well.
 
             fclose($fp);
-            $document_id = add_document($_course,$this->created_dir.'/'.urlencode($html_file), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$html_file), $slide_name);
+            $document_id = FileManager::add_document(
+                $_course,
+                $this->created_dir.'/'.urlencode($html_file),
+                'file',
+                filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),
+                $slide_name
+            );
             if ($document_id) {
 
                 // Put the document in item_property update.
-                api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), 0, 0, null, null, api_get_session_id());
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $document_id,
+                    'DocumentAdded',
+                    api_get_user_id(),
+                    0,
+                    0,
+                    null,
+                    null,
+                    api_get_session_id()
+                );
 
                 $previous = $this->add_item(0, $previous, 'document', $document_id, $slide_name, '');
                 if ($this->first_item == 0) {
@@ -114,10 +173,10 @@ class OpenofficePresentation extends OpenofficeDocument {
             // Code for text indexing.
             if (api_get_setting('search_enabled') == 'true') {
 
-                if (isset($_POST['index_document']) && $_POST['index_document']) {                    
+                if (isset($_POST['index_document']) && $_POST['index_document']) {
                     $di = new ChamiloIndexer();
                     isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
-                    $di->connectDb(NULL, NULL, $lang);
+                    $di->connectDb(null, null, $lang);
                     $ic_slide = new IndexableChunk();
                     $ic_slide->addValue('title', $slide_name);
                     $specific_fields = get_specific_field_list();
@@ -125,7 +184,7 @@ class OpenofficePresentation extends OpenofficeDocument {
                     foreach ($specific_fields as $specific_field) {
                         if (isset($_REQUEST[$specific_field['code']])) {
                             $sterms = trim($_REQUEST[$specific_field['code']]);
-                            $all_specific_terms .= ' '. $sterms;
+                            $all_specific_terms .= ' '.$sterms;
                             if (!empty($sterms)) {
                                 $sterms = explode(',', $sterms);
                                 foreach ($sterms as $sterm) {
@@ -134,7 +193,7 @@ class OpenofficePresentation extends OpenofficeDocument {
                             }
                         }
                     }
-                    $slide_body = $all_specific_terms .' '. $slide_body;
+                    $slide_body = $all_specific_terms.' '.$slide_body;
                     $ic_slide->addValue('content', $slide_body);
                     /* FIXME:  cidReq:lp_id:doc_id al indexar  */
                     // Add a comment to say terms separated by commas.
@@ -165,28 +224,56 @@ class OpenofficePresentation extends OpenofficeDocument {
         }
     }
 
-    function add_command_parameters() {
-        if (empty($this->slide_width) || empty($this->slide_height))
-            list($this->slide_width, $this->slide_height) = explode('x', api_get_setting('service_ppt2lp', 'size'));
+    function add_command_parameters()
+    {
+        if (empty($this->slide_width) || empty($this->slide_height)) {
+            list($this->slide_width, $this->slide_height) = explode(
+                'x',
+                api_get_setting('service_ppt2lp', 'size')
+            );
+        }
+
         return ' -w '.$this->slide_width.' -h '.$this->slide_height.' -d oogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'.html"';
     }
 
-    function set_slide_size($width, $height) {
+    function set_slide_size($width, $height)
+    {
         $this->slide_width = $width;
         $this->slide_height = $height;
     }
 
-    function add_docs_to_visio($files = array()) {
+    function add_docs_to_visio($files = array())
+    {
         global $_course;
         foreach ($files as $file) {
-            list($slide_name,$file_name) = explode('||',$file); // '||' is used as separator between slide name (with accents) and file name (without accents).
+            list($slide_name, $file_name) = explode(
+                '||',
+                $file
+            ); // '||' is used as separator between slide name (with accents) and file name (without accents).
             $slide_name = api_htmlentities($slide_name, ENT_COMPAT, $this->original_charset);
             $slide_name = str_replace('&rsquo;', '\'', $slide_name);
             $slide_name = api_convert_encoding($slide_name, api_get_system_encoding(), $this->original_charset);
             $slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding());
-            $did = add_document($_course, $this->created_dir.'/'.urlencode($file_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$file_name), $slide_name);
+            $did = FileManager::add_document(
+                $_course,
+                $this->created_dir.'/'.urlencode($file_name),
+                'file',
+                filesize($this->base_work_dir.$this->created_dir.'/'.$file_name),
+                $slide_name
+            );
             if ($did) {
-                api_item_property_update($_course, TOOL_DOCUMENT, $did, 'DocumentAdded', $_SESSION['_uid'], 0, null, null, null, api_get_session_id());
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $did,
+                    'DocumentAdded',
+                    $_SESSION['_uid'],
+                    0,
+                    null,
+                    null,
+                    null,
+                    api_get_session_id()
+                );
             }
         }
     }

+ 113 - 48
main/newscorm/openoffice_text.class.php

@@ -22,33 +22,38 @@ if (api_get_setting('search_enabled') == 'true') {
 /**
  * @package chamilo.learnpath.OpenofficeDocument
  */
-class OpenofficeText extends OpenofficeDocument {
+class OpenofficeText extends OpenofficeDocument
+{
 
     public $split_steps;
 
     /**
      * Class constructor. Calls the parent class and initialises the local attribute split_steps
-     * @param	boolean	Whether to split steps (true) or make one large page (false)
-     * @param	string	Course code
-     * @param	integer	Resource ID
-     * @param	integer Creator user id
-     * @return	void
+     * @param    boolean    Whether to split steps (true) or make one large page (false)
+     * @param    string    Course code
+     * @param    integer    Resource ID
+     * @param    integer Creator user id
+     * @return    void
      */
-    function OpenofficeText($split_steps = false, $course_code = null, $resource_id = null, $user_id = null) {
-        $this -> split_steps = $split_steps;
+    function OpenofficeText($split_steps = false, $course_code = null, $resource_id = null, $user_id = null)
+    {
+        $this->split_steps = $split_steps;
         parent::__construct($course_code, $resource_id, $user_id);
     }
 
     /**
      * Gets html pages and compose them into a learning path
-     * @param	array	The files that will compose the generated learning path. Unused so far.
-     * @return	boolean	False if file does not exit. Nothing otherwise.
+     * @param    array    The files that will compose the generated learning path. Unused so far.
+     * @return    boolean    False if file does not exit. Nothing otherwise.
      */
-    function make_lp($files = array()) {
+    function make_lp($files = array())
+    {
 
         global $_course;
         // We get a content where ||page_break|| indicates where the page is broken.
-        if (!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')) { return false; }
+        if (!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')) {
+            return false;
+        }
         $content = file_get_contents($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');
 
         unlink($this->base_work_dir.'/'.$this->file_path);
@@ -64,7 +69,11 @@ class OpenofficeText extends OpenofficeDocument {
         $content = api_html_entity_decode($content, ENT_COMPAT, $charset);
 
         // Set the path to pictures to absolute (so that it can be modified in fckeditor).
-        $content = preg_replace("|src=\"([^\"]*)|i", "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1", $content);
+        $content = preg_replace(
+            "|src=\"([^\"]*)|i",
+            "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1",
+            $content
+        );
 
         list($header, $body) = explode('<BODY', $content);
 
@@ -75,9 +84,11 @@ class OpenofficeText extends OpenofficeDocument {
 
         // Chamilo styles.
         $my_style = api_get_setting('stylesheets');
-        if (empty($my_style)) { $my_style = 'chamilo'; }
+        if (empty($my_style)) {
+            $my_style = 'chamilo';
+        }
         $style_to_import = "<style type=\"text/css\">\r\n";
-        $style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";        
+        $style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";
         $style_to_import .= "</style>\r\n";
         $header = preg_replace("|</head>|i", "\r\n$style_to_import\r\n\\0", $header);
 
@@ -87,18 +98,23 @@ class OpenofficeText extends OpenofficeDocument {
         $header = str_replace('absolute', 'relative', $header);
 
         switch ($this->split_steps) {
-            case 'per_page': $this -> dealPerPage($header, $body); break;
-            case 'per_chapter': $this -> dealPerChapter($header, $body); break;
+            case 'per_page':
+                $this->dealPerPage($header, $body);
+                break;
+            case 'per_chapter':
+                $this->dealPerChapter($header, $body);
+                break;
         }
     }
 
     /**
      * Manages chapter splitting
-     * @param	string	Chapter header
-     * @param	string	Content
-     * @return	void
+     * @param    string    Chapter header
+     * @param    string    Content
+     * @return    void
      */
-    function dealPerChapter($header, $content) {
+    function dealPerChapter($header, $content)
+    {
 
         global $_course;
 
@@ -126,10 +142,11 @@ class OpenofficeText extends OpenofficeDocument {
 
         for ($i = 0; $i < count($matches[0]); $i++) {
 
-            if (empty($matches[1][$i]))
+            if (empty($matches[1][$i])) {
                 continue;
+            }
 
-            $content = strstr($content,$matches[0][$i]);
+            $content = strstr($content, $matches[0][$i]);
             if ($i + 1 !== count($matches[0])) {
                 $chapter_content = substr($content, 0, strpos($content, $matches[0][$i + 1]));
             } else {
@@ -149,12 +166,29 @@ class OpenofficeText extends OpenofficeDocument {
             fwrite($handle, $page_content);
             fclose($handle);
 
-            $document_id = add_document($_course, $this->created_dir.'/'.$html_file, 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$html_file), $html_file);
+            $document_id = FileManager::add_document(
+                $_course,
+                $this->created_dir.'/'.$html_file,
+                'file',
+                filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),
+                $html_file
+            );
 
-            if ($document_id){
+            if ($document_id) {
 
                 // Put the document in item_property update.
-                api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_SESSION['_uid'], 0, 0, null, null, api_get_session_id());
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $document_id,
+                    'DocumentAdded',
+                    $_SESSION['_uid'],
+                    0,
+                    0,
+                    null,
+                    null,
+                    api_get_session_id()
+                );
 
                 $infos = pathinfo($this->filepath);
                 $slide_name = strip_tags(nl2br($item_title));
@@ -170,11 +204,12 @@ class OpenofficeText extends OpenofficeDocument {
 
     /**
      * Manages page splitting
-     * @param	string	Page header
-     * @param	string	Page body
-     * @return	void
+     * @param    string    Page header
+     * @param    string    Page body
+     * @return    void
      */
-    function dealPerPage($header, $body) {
+    function dealPerPage($header, $body)
+    {
         global $_course;
         // Split document to pages.
         $pages = explode('||page_break||', $body);
@@ -192,14 +227,31 @@ class OpenofficeText extends OpenofficeDocument {
             fwrite($handle, $page_content);
             fclose($handle);
 
-            $document_id = add_document($_course, $this->created_dir.$html_file, 'file', filesize($this->base_work_dir.$this->created_dir.$html_file), $html_file);
+            $document_id = FileManager::add_document(
+                $_course,
+                $this->created_dir.$html_file,
+                'file',
+                filesize($this->base_work_dir.$this->created_dir.$html_file),
+                $html_file
+            );
 
             $slide_name = '';
 
             if ($document_id) {
 
                 // Put the document in item_property update.
-                api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_SESSION['_uid'], 0, 0, null, null, api_get_session_id());
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $document_id,
+                    'DocumentAdded',
+                    $_SESSION['_uid'],
+                    0,
+                    0,
+                    null,
+                    null,
+                    api_get_session_id()
+                );
 
                 $infos = pathinfo($this->filepath);
                 $slide_name = 'Page '.str_repeat('0', 2 - strlen($key)).$key;
@@ -212,8 +264,10 @@ class OpenofficeText extends OpenofficeDocument {
                     if (isset($_POST['index_document']) && $_POST['index_document']) {
                         //Display::display_normal_message(print_r($_POST));
                         $di = new ChamiloIndexer();
-                        isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
-                        $di->connectDb(NULL, NULL, $lang);
+                        isset($_POST['language']) ? $lang = Database::escape_string(
+                            $_POST['language']
+                        ) : $lang = 'english';
+                        $di->connectDb(null, null, $lang);
                         $ic_slide = new IndexableChunk();
                         $ic_slide->addValue('title', $slide_name);
                         $specific_fields = get_specific_field_list();
@@ -221,7 +275,7 @@ class OpenofficeText extends OpenofficeDocument {
                         foreach ($specific_fields as $specific_field) {
                             if (isset($_REQUEST[$specific_field['code']])) {
                                 $sterms = trim($_REQUEST[$specific_field['code']]);
-                                $all_specific_terms .= ' '. $sterms;
+                                $all_specific_terms .= ' '.$sterms;
                                 if (!empty($sterms)) {
                                     $sterms = explode(',', $sterms);
                                     foreach ($sterms as $sterm) {
@@ -230,17 +284,17 @@ class OpenofficeText extends OpenofficeDocument {
                                 }
                             }
                         }
-                        $page_content = $all_specific_terms .' '. $page_content;
+                        $page_content = $all_specific_terms.' '.$page_content;
                         $ic_slide->addValue('content', $page_content);
                         // Add a comment to say terms separated by commas.
-                        $courseid=api_get_course_id();
+                        $courseid = api_get_course_id();
                         $ic_slide->addCourseId($courseid);
                         $ic_slide->addToolId(TOOL_LEARNPATH);
                         $lp_id = $this->lp_id;
                         $xapian_data = array(
                             SE_COURSE_ID => $courseid,
                             SE_TOOL_ID => TOOL_LEARNPATH,
-                            SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => $document_id),
+                            SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => $document_id),
                             SE_USER => (int)api_get_user_id(),
                         );
                         $ic_slide->xapian_data = serialize($xapian_data);
@@ -252,7 +306,15 @@ class OpenofficeText extends OpenofficeDocument {
                             $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
                             $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
                                     VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
-                            $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
+                            $sql = sprintf(
+                                $sql,
+                                $tbl_se_ref,
+                                api_get_course_id(),
+                                TOOL_LEARNPATH,
+                                $lp_id,
+                                $previous,
+                                $did
+                            );
                             Database::query($sql);
                         }
                     }
@@ -263,21 +325,23 @@ class OpenofficeText extends OpenofficeDocument {
 
     /**
      * Returns additional Java command parameters
-     * @return	string	The additional parameters to be used in the Java call
+     * @return    string    The additional parameters to be used in the Java call
      */
-    function add_command_parameters(){
+    function add_command_parameters()
+    {
         return ' -d woogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'/'.$this->file_name.'.html"';
     }
 
     /**
      * Formats a page content by reorganising the HTML code a little
-     * @param	string	Page header
-     * @param	string	Page content
-     * @return	string	Formatted page content
+     * @param    string    Page header
+     * @param    string    Page content
+     * @return    string    Formatted page content
      */
-    function format_page_content($header, $content) {
+    function format_page_content($header, $content)
+    {
         // Limit the width of the doc.
-        list($max_width, $max_height) = explode('x',api_get_setting('service_ppt2lp','size'));
+        list($max_width, $max_height) = explode('x', api_get_setting('service_ppt2lp', 'size'));
 
         $content = preg_replace("|<body[^>]*>|i", "\\0\r\n<div style=\"width:".$max_width."\">", $content, -1, $count);
         if ($count < 1) {
@@ -310,7 +374,7 @@ class OpenofficeText extends OpenofficeDocument {
                 }
 
             } elseif ($img_width > $max_width - 10) {
-                $picture_resized = str_ireplace('width='.$img_width, 'width="'.($max_width-10).'"', $images[0][$key]);
+                $picture_resized = str_ireplace('width='.$img_width, 'width="'.($max_width - 10).'"', $images[0][$key]);
                 $content = str_replace($images[0][$key], $picture_resized, $content);
             }
         }
@@ -321,7 +385,8 @@ class OpenofficeText extends OpenofficeDocument {
     /**
      * Add documents to the visioconference (to be implemented)
      */
-    function add_docs_to_visio() {
+    function add_docs_to_visio()
+    {
 
     }
 }

+ 100 - 45
main/newscorm/openoffice_text_document.class.php

@@ -18,33 +18,38 @@ require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
 /**
  * @package chamilo.learnpath.openofficedocument
  */
-class OpenOfficeTextDocument extends OpenofficeDocument {
+class OpenOfficeTextDocument extends OpenofficeDocument
+{
 
     public $split_steps;
 
     /**
      * Class constructor. Calls the parent class and initialises the local attribute split_steps
-     * @param	boolean	Whether to split steps (true) or make one large page (false)
-     * @param	string	Course code
-     * @param	integer	Resource ID
-     * @param	integer Creator user id
-     * @return	void
+     * @param    boolean    Whether to split steps (true) or make one large page (false)
+     * @param    string    Course code
+     * @param    integer    Resource ID
+     * @param    integer Creator user id
+     * @return    void
      */
-    public function __construct($split_steps = false, $course_code = null, $resource_id = null, $user_id = null) {
-        $this -> split_steps = $split_steps;
+    public function __construct($split_steps = false, $course_code = null, $resource_id = null, $user_id = null)
+    {
+        $this->split_steps = $split_steps;
         parent::__construct($course_code, $resource_id, $user_id);
     }
 
     /**
      * Gets html pages and compose them into a learning path
-     * @param	array	The files that will compose the generated learning path. Unused so far.
-     * @return	boolean	False if file does not exit. Nothing otherwise.
+     * @param    array    The files that will compose the generated learning path. Unused so far.
+     * @return    boolean    False if file does not exit. Nothing otherwise.
      */
-    public function make_lp($files = array()) {
+    public function make_lp($files = array())
+    {
 
         global $_course;
         // We get a content where ||page_break|| indicates where the page is broken.
-        if (!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')) { return false; }
+        if (!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')) {
+            return false;
+        }
         $content = file_get_contents($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html');
 
         unlink($this->base_work_dir.'/'.$this->file_path);
@@ -60,7 +65,11 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
         $content = api_html_entity_decode($content, ENT_COMPAT, $charset);
 
         // Set the path to pictures to absolute (so that it can be modified in fckeditor).
-        $content = preg_replace("|src=\"([^\"]*)|i", "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1", $content);
+        $content = preg_replace(
+            "|src=\"([^\"]*)|i",
+            "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1",
+            $content
+        );
 
         list($header, $body) = explode('<BODY', $content);
 
@@ -71,9 +80,11 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
 
         // Chamilo styles.
         $my_style = api_get_setting('stylesheets');
-        if (empty($my_style)) { $my_style = 'chamilo'; }
+        if (empty($my_style)) {
+            $my_style = 'chamilo';
+        }
         $style_to_import = "<style type=\"text/css\">\r\n";
-        $style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";        
+        $style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n";
         $style_to_import .= "</style>\r\n";
         $header = preg_replace("|</head>|i", "\r\n$style_to_import\r\n\\0", $header);
 
@@ -83,18 +94,23 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
         $header = str_replace('absolute', 'relative', $header);
 
         switch ($this->split_steps) {
-            case 'per_page': $this -> dealPerPage($header, $body); break;
-            case 'per_chapter': $this -> dealPerChapter($header, $body); break;
+            case 'per_page':
+                $this->dealPerPage($header, $body);
+                break;
+            case 'per_chapter':
+                $this->dealPerChapter($header, $body);
+                break;
         }
     }
 
     /**
      * Manages chapter splitting
-     * @param	string	Chapter header
-     * @param	string	Content
-     * @return	void
+     * @param    string    Chapter header
+     * @param    string    Content
+     * @return    void
      */
-    function dealPerChapter($header, $content) {
+    function dealPerChapter($header, $content)
+    {
 
         global $_course;
 
@@ -117,10 +133,11 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
         $intro_content = api_substr($content, 0, api_strpos($content, $matches[0][0]));
         $items_to_create[get_lang('Introduction')] = $intro_content;
 
-        for ($i = 0; $i<count($matches[0]); $i++) {
+        for ($i = 0; $i < count($matches[0]); $i++) {
 
-            if (empty($matches[1][$i]))
+            if (empty($matches[1][$i])) {
                 continue;
+            }
 
             $content = api_strstr($content, $matches[0][$i]);
             if ($i + 1 !== count($matches[0])) {
@@ -141,12 +158,29 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
             fwrite($handle, $page_content);
             fclose($handle);
 
-            $document_id = add_document($_course, $this->created_dir.'/'.$html_file, 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$html_file), $html_file);
+            $document_id = FileManager::add_document(
+                $_course,
+                $this->created_dir.'/'.$html_file,
+                'file',
+                filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),
+                $html_file
+            );
 
             if ($document_id) {
 
                 // Put the document in item_property update.
-                api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_SESSION['_uid'], 0, 0, null, null, api_get_session_id());
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $document_id,
+                    'DocumentAdded',
+                    $_SESSION['_uid'],
+                    0,
+                    0,
+                    null,
+                    null,
+                    api_get_session_id()
+                );
 
                 $infos = pathinfo($this->filepath);
                 $slide_name = strip_tags(nl2br($item_title));
@@ -162,18 +196,19 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
 
     /**
      * Manages page splitting
-     * @param	string	Page header
-     * @param	string	Page body
-     * @return	void
+     * @param    string    Page header
+     * @param    string    Page body
+     * @return    void
      */
-    function dealPerPage($header, $body) {
+    function dealPerPage($header, $body)
+    {
         global $_course;
         // Split document to pages.
         $pages = explode('||page_break||', $body);
 
         $first_item = 0;
 
-        foreach($pages as $key => $page_content) {
+        foreach ($pages as $key => $page_content) {
             // For every pages, we create a new file.
 
             $key += 1;
@@ -184,14 +219,31 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
             fwrite($handle, $page_content);
             fclose($handle);
 
-            $document_id = add_document($_course, $this->created_dir.$html_file, 'file', filesize($this->base_work_dir.$this->created_dir.$html_file), $html_file);
+            $document_id = FileManager::add_document(
+                $_course,
+                $this->created_dir.$html_file,
+                'file',
+                filesize($this->base_work_dir.$this->created_dir.$html_file),
+                $html_file
+            );
 
             $slide_name = '';
 
             if ($document_id) {
 
                 // Put the document in item_property update.
-                api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_SESSION['_uid'], 0, 0, null, null, api_get_session_id());
+                api_item_property_update(
+                    $_course,
+                    TOOL_DOCUMENT,
+                    $document_id,
+                    'DocumentAdded',
+                    $_SESSION['_uid'],
+                    0,
+                    0,
+                    null,
+                    null,
+                    api_get_session_id()
+                );
 
                 $infos = pathinfo($this->filepath);
                 $slide_name = 'Page '.str_repeat('0', 2 - strlen($key)).$key;
@@ -204,7 +256,7 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
                     //Display::display_normal_message(print_r($_POST));
                     $di = new ChamiloIndexer();
                     isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
-                    $di->connectDb(NULL, NULL, $lang);
+                    $di->connectDb(null, null, $lang);
                     $ic_slide = new IndexableChunk();
                     $ic_slide->addValue('title', $slide_name);
                     $specific_fields = get_specific_field_list();
@@ -212,7 +264,7 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
                     foreach ($specific_fields as $specific_field) {
                         if (isset($_REQUEST[$specific_field['code']])) {
                             $sterms = trim($_REQUEST[$specific_field['code']]);
-                            $all_specific_terms .= ' '. $sterms;
+                            $all_specific_terms .= ' '.$sterms;
                             if (!empty($sterms)) {
                                 $sterms = explode(',', $sterms);
                                 foreach ($sterms as $sterm) {
@@ -221,7 +273,7 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
                             }
                         }
                     }
-                    $page_content = $all_specific_terms .' '. $page_content;
+                    $page_content = $all_specific_terms.' '.$page_content;
                     $ic_slide->addValue('content', $page_content);
                     // Add a comment to say terms separated by commas.
                     $courseid = api_get_course_id();
@@ -253,19 +305,21 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
 
     /**
      * Returns additional Java command parameters
-     * @return	string	The additional parameters to be used in the Java call
+     * @return    string    The additional parameters to be used in the Java call
      */
-    function add_command_parameters() {
+    function add_command_parameters()
+    {
         return ' -d woogie "'.$this->base_work_dir.'/'.$this->file_path.'"  "'.$this->base_work_dir.$this->created_dir.'/'.$this->file_name.'.html"';
     }
 
     /**
      * Formats a page content by reorganising the HTML code a little
-     * @param	string	Page header
-     * @param	string	Page content
-     * @return	string	Formatted page content
+     * @param    string    Page header
+     * @param    string    Page content
+     * @return    string    Formatted page content
      */
-    function format_page_content($header, $content) {
+    function format_page_content($header, $content)
+    {
 
         // Limit the width of the doc.
         list($max_width, $max_height) = explode('x', api_get_setting('service_ppt2lp', 'size'));
@@ -275,7 +329,7 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
             $content = '<body><div style="width:'.$max_width.'">'.$content;
         }
 
-        $content = preg_replace('|</body>|i','</div>\\0', $content, -1, $count);
+        $content = preg_replace('|</body>|i', '</div>\\0', $content, -1, $count);
         if ($count < 1) {
             $content = $content.'</div></body>';
         }
@@ -293,7 +347,7 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
             if (!$defined_width) {
 
                 $image_size = api_getimagesize($this->base_work_dir.$this->created_dir.'/'.$image);
-                $img_width  = $image_size['width']; 
+                $img_width = $image_size['width'];
                 $img_height = $image_size['height'];
 
                 $new_width = $max_width - 10;
@@ -303,7 +357,7 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
                 }
 
             } elseif ($img_width > $max_width - 10) {
-                $picture_resized = str_ireplace('width='.$img_width, 'width="'.($max_width-10).'"', $images[0][$key]);
+                $picture_resized = str_ireplace('width='.$img_width, 'width="'.($max_width - 10).'"', $images[0][$key]);
                 $content = str_replace($images[0][$key], $picture_resized, $content);
             }
         }
@@ -314,7 +368,8 @@ class OpenOfficeTextDocument extends OpenofficeDocument {
     /**
      * Add documents to the visioconference (to be implemented)
      */
-    function add_docs_to_visio() {
+    function add_docs_to_visio()
+    {
 
     }
 }

Fișier diff suprimat deoarece este prea mare
+ 452 - 181
main/newscorm/resourcelinker.inc.php


+ 323 - 209
main/newscorm/resourcelinker.php

@@ -97,9 +97,9 @@ if (!empty ($_POST['add_chapter']) && !empty ($_POST['title'])) {
     }*/
 
     // Get max display_order so far in this parent chapter.
-    $sql = "SELECT MAX(display_order) as maxi FROM $tbl_lp_item " .
-            "WHERE c_id = $course_id AND lp_id = $learnpath_id ".
-            " AND parent_item_id = $chapter_id";
+    $sql = "SELECT MAX(display_order) as maxi FROM $tbl_lp_item ".
+        "WHERE c_id = $course_id AND lp_id = $learnpath_id ".
+        " AND parent_item_id = $chapter_id";
     $res = Database::query($sql);
     $row = Database::fetch_array($res);
     $lastorder_item = $row['maxi'];
@@ -107,16 +107,16 @@ if (!empty ($_POST['add_chapter']) && !empty ($_POST['title'])) {
         $lastorder_item = 0;
         $previous = 0;
     } else {
-        $sql = "SELECT id FROM $tbl_lp_item " .
-                "WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id AND display_order = $lastorder_item";
+        $sql = "SELECT id FROM $tbl_lp_item ".
+            "WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id AND display_order = $lastorder_item";
         $result = Database::query($sql);
         $row = Database::fetch_array($result);
         $previous = $row['id'];
     }
     $order = $lastorder_item + 1;
 
-    $sql = "INSERT INTO $tbl_lp_item "."(c_id, lp_id,item_type,title,parent_item_id,previous_item_id, next_item_id, display_order) " .
-            "VALUES "."($course_id, $learnpath_id,'dokeos_chapter','$title', $chapter_id, $previous, 0, $order )";
+    $sql = "INSERT INTO $tbl_lp_item "."(c_id, lp_id,item_type,title,parent_item_id,previous_item_id, next_item_id, display_order) ".
+        "VALUES "."($course_id, $learnpath_id,'dokeos_chapter','$title', $chapter_id, $previous, 0, $order )";
     //error_log('New LP - Inserting new resource: '.$sql, 0);
     $res = Database::query($sql);
     $my_id = Database::insert_id($res);
@@ -183,8 +183,8 @@ if ($add) {
     if ($from_learnpath == 'yes') {
         $i = 0;
         // Calculating the last order of the items of this chapter.
-        $sql = "SELECT MAX(display_order) as maxi FROM $tbl_lp_item " .
-                "WHERE c_id = $course_id AND lp_id = $learnpath_id AND parent_item_id=$chapter_id";
+        $sql = "SELECT MAX(display_order) as maxi FROM $tbl_lp_item ".
+            "WHERE c_id = $course_id AND lp_id = $learnpath_id AND parent_item_id=$chapter_id";
         $result = Database::query($sql);
         $row = Database::fetch_array($result);
         $lastorder_item = $row['maxi'];
@@ -192,8 +192,8 @@ if ($add) {
             $lastorder_item = 0;
             $previous = 0;
         } else {
-            $sql = "SELECT id FROM $tbl_lp_item " .
-                    "WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id AND display_order = $lastorder_item";
+            $sql = "SELECT id FROM $tbl_lp_item ".
+                "WHERE lp_id = $learnpath_id AND parent_item_id=$chapter_id AND display_order = $lastorder_item";
             //error_log('New LP - resourcelinker.php - '.$sql, 0);
             $result = Database::query($sql);
             $row = Database::fetch_array($result);
@@ -203,9 +203,9 @@ if ($add) {
         foreach ($addedresource as $addedresource_item) {
             // In the case we added a chapter, add this into the chapters list with the correct parent_id.
             if ($addedresource_item == 'Chap') {
-                $sql = "INSERT INTO $tbl_lp_item " .
-                        "(c_id, lp_id,item_type,title,parent_item_id,previous_item_id,next_item_id,display_order) " .
-                        "VALUES ($course_id, ".$learnpath_id.",'dokeos_chapter','".$learnpath_chapter_name."',".$chapter_id.",$previous,0,".$lastorder.")";
+                $sql = "INSERT INTO $tbl_lp_item ".
+                    "(c_id, lp_id,item_type,title,parent_item_id,previous_item_id,next_item_id,display_order) ".
+                    "VALUES ($course_id, ".$learnpath_id.",'dokeos_chapter','".$learnpath_chapter_name."',".$chapter_id.",$previous,0,".$lastorder.")";
                 //error_log('New LP - Inserting new resource: '.$sql, 0);
                 $res = Database::query($sql);
                 $my_id = Database::insert_id($res);
@@ -265,7 +265,7 @@ if ($add) {
                         //get title from tool-type table
                         $tooltable = Database::get_course_table(TABLE_DOCUMENT);
                         $result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i]);
-                        $myrow=Database::fetch_array($result);
+                        $myrow = Database::fetch_array($result);
                         $title = $myrow['title'];
                         break;
                     case 'Exercise':
@@ -273,7 +273,7 @@ if ($add) {
                         //get title from tool-type table
                         $tooltable = Database::get_course_table(TABLE_QUIZ_TEST);
                         $result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i]);
-                        $myrow=Database::fetch_array($result);
+                        $myrow = Database::fetch_array($result);
                         $title = $myrow['title'];
                         break;
                     case 'Forum':
@@ -285,7 +285,7 @@ if ($add) {
                         //get title from tool-type table
                         $tooltable = Database::get_course_table(TABLE_AGENDA);
                         $result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i]);
-                        $myrow=Database::fetch_array($result);
+                        $myrow = Database::fetch_array($result);
                         $title = $myrow['title'];
                         break;
                     case 'Ad_Valvas':
@@ -293,13 +293,13 @@ if ($add) {
                         //get title from tool-type table
                         $tooltable = Database::get_course_table(TABLE_ANNOUNCEMENT);
                         $result = Database::query("SELECT * FROM $tooltable WHERE id=".$addedresourceid[$i]);
-                        $myrow=Database::fetch_array($result);
+                        $myrow = Database::fetch_array($result);
                         $title = $myrow['title'];
                         break;
 
                 }
-                $sql = "INSERT INTO $tbl_lp_item (c_id, lp_id, title, parent_item_id, item_type, ref, previous_item_id, next_item_id, display_order) " .
-                        "VALUES ($course_id, $learnpath_id, '$title','$chapter_id', '$addedresource_item','$addedresourceid[$i]',$previous,0,'".$lastorder."')";
+                $sql = "INSERT INTO $tbl_lp_item (c_id, lp_id, title, parent_item_id, item_type, ref, previous_item_id, next_item_id, display_order) ".
+                    "VALUES ($course_id, $learnpath_id, '$title','$chapter_id', '$addedresource_item','$addedresourceid[$i]',$previous,0,'".$lastorder."')";
                 //error_log('New LP - Inserting new resource: '.$sql, 0);
                 $result = Database::query($sql);
                 $my_id = Database::insert_id($result);
@@ -311,18 +311,18 @@ if ($add) {
                 $addedresourceassigned[$i] = 1;
                 $resource_added = true;
             }
-            $i ++;
-            $lastorder ++;
+            $i++;
+            $lastorder++;
         }
         //$_SESSION['addedresource']=null;
         //$_SESSION['addedresourceid']=null;
         // cleaning up the session once again
         $_SESSION['addedresource'] = null;
-           $_SESSION['addedresourceid'] = null;
-           $_SESSION['addedresourceassigned'] = null;
-           unset ($_SESSION['addedresource']);
-           unset ($_SESSION['addedresourceid']);
-           unset ($_SESSION['addedresourceassigned']);
+        $_SESSION['addedresourceid'] = null;
+        $_SESSION['addedresourceassigned'] = null;
+        unset ($_SESSION['addedresource']);
+        unset ($_SESSION['addedresourceid']);
+        unset ($_SESSION['addedresourceassigned']);
     }
 }
 
@@ -340,10 +340,10 @@ if (isset($_SESSION['gradebook'])) {
 }
 
 if (!empty($gradebook) && $gradebook == 'view') {
-    $interbreadcrumb[] = array (
-            'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-            'name' => get_lang('ToolGradebook')
-        );
+    $interbreadcrumb[] = array(
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+        'name' => get_lang('ToolGradebook')
+    );
 }
 
 if ($_GET['source_id']) {
@@ -351,47 +351,46 @@ if ($_GET['source_id']) {
         case '1': // coming from Agenda
             if ($action == 'edit') {
                 $url = "../calendar/agenda.php?action=edit&id=49&originalresource=$originalresource";
-            }
-            elseif ($action == 'add') {
+            } elseif ($action == 'add') {
                 $url = "../calendar/agenda.php?action=add&originalresource=$originalresource";
             } else {
                 $url = "../calendar/agenda.php?action=add";
             }
             $originaltoolname = get_lang('Agenda');
-            $breadcrumbelement = array ('url' => $url, 'name' => $originaltoolname);
+            $breadcrumbelement = array('url' => $url, 'name' => $originaltoolname);
             session_unregister('from_learnpath');
             unset ($from_learnpath);
             break;
         case '2': // coming from forum: new topic
             $url = "../phpbb/newtopic.php?forum=$source_forum&md5=$md5";
             $originaltoolname = get_lang('ForumAddNewTopic');
-            $breadcrumbelement = array ('url' => $url, 'name' => $originaltoolname);
+            $breadcrumbelement = array('url' => $url, 'name' => $originaltoolname);
             session_unregister('from_learnpath');
             unset ($from_learnpath);
             break;
         case '3': // coming from forum: edit topic
             $url = "../phpbb/editpost.php?post_id=$post_id&topic=$topic&forum=$forum&md5=$md5&originalresource=no";
             $originaltoolname = get_lang('ForumEditTopic');
-            $breadcrumbelement = array ('url' => $url, 'name' => $originaltoolname);
+            $breadcrumbelement = array('url' => $url, 'name' => $originaltoolname);
             session_unregister('from_learnpath');
             unset ($from_learnpath);
             break;
         case '4': // coming from exercises: edit topic
             $url = "../exercice/admin.php?modifyAnswers=$modifyAnswers";
             $originaltoolname = get_lang('ExerciseAnswers');
-            $breadcrumbelement = array ('url' => $url, 'name' => $originaltoolname);
+            $breadcrumbelement = array('url' => $url, 'name' => $originaltoolname);
             session_unregister('from_learnpath');
             unset ($from_learnpath);
             break;
         case '5': // coming from learning path
             $from_learnpath = 'yes';
-            Session::write('from_learnpath',$from_learnpath);
+            Session::write('from_learnpath', $from_learnpath);
             break;
         case '6': // coming from forum: reply
             $url = "../phpbb/reply.php?topic=$topic&forum=$forum&parentid=$parentid";
             $url = $_SESSION['origintoolurl'];
             $originaltoolname = get_lang('ForumReply');
-            $breadcrumbelement = array ('url' => $url, 'name' => $originaltoolname);
+            $breadcrumbelement = array('url' => $url, 'name' => $originaltoolname);
             session_unregister('from_learnpath');
             unset ($from_learnpath);
             break;
@@ -407,7 +406,7 @@ if ($_GET['source_id']) {
                 $url = "../announcements/announcements.php?action=add";
             }
             $originaltoolname = get_lang('AdValvas');
-            $breadcrumbelement = array ('url' => $url, 'name' => $originaltoolname);
+            $breadcrumbelement = array('url' => $url, 'name' => $originaltoolname);
             session_unregister('from_learnpath');
             unset ($from_learnpath);
             break;
@@ -430,7 +429,7 @@ if ($_GET['source_id']) {
 // the information from the session. Else we use the information of the learningpath itself.
 if ($from_learnpath != 'yes') {
     $nameTools = get_lang('Attachment');
-    $interbreadcrumb[] = array ('url' => $_SESSION['origintoolurl'], 'name' => $_SESSION['origintoolname']);
+    $interbreadcrumb[] = array('url' => $_SESSION['origintoolurl'], 'name' => $_SESSION['origintoolname']);
 } else {
     $learnpath_select_query = "	SELECT * FROM $tbl_lp
                                           WHERE id=$learnpath_id";
@@ -444,9 +443,18 @@ if ($from_learnpath != 'yes') {
 
     $from_learnpath = 'yes';
     session_register('from_learnpath');
-    $interbreadcrumb[] = array ('url' => "../newscorm/lp_controller.php?action=list", 'name' => get_lang('LearningPath'));
-    $interbreadcrumb[] = array ('url' => "../newscorm/lp_controller.php?action=admin_view&lp_id=$learnpath_id", 'name' => stripslashes("{$therow['name']}"));
-    $interbreadcrumb[] = array ('url' => api_get_self()."?action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no", 'name' => "{$therow2['title']}");
+    $interbreadcrumb[] = array(
+        'url' => "../newscorm/lp_controller.php?action=list",
+        'name' => get_lang('LearningPath')
+    );
+    $interbreadcrumb[] = array(
+        'url' => "../newscorm/lp_controller.php?action=admin_view&lp_id=$learnpath_id",
+        'name' => stripslashes("{$therow['name']}")
+    );
+    $interbreadcrumb[] = array(
+        'url' => api_get_self()."?action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no",
+        'name' => "{$therow2['title']}"
+    );
 }
 
 $htmlHeadXtra[] = '<script type="text/javascript">
@@ -473,7 +481,7 @@ $active_modules = array();
 $tool_table = Database::get_course_table(TABLE_TOOL_LIST);
 $sql_select_active = "SELECT * FROM $tool_table WHERE visibility='1'";
 $result_select_active = Database::query($sql_select_active);
-while ($row=Database::fetch_array($result_select_active)) {
+while ($row = Database::fetch_array($result_select_active)) {
     $active_modules[] = $row['name'];
 }
 ?>
@@ -481,154 +489,223 @@ while ($row=Database::fetch_array($result_select_active)) {
 <table width="100%" border="0" cellspacing="0" cellpadding="0">
   <tr>
     <td width="300" valign="top" style='padding-right:15px;'>
-      <table width="300" border="0" cellspacing="0" cellpadding="0" style='border-right:1px solid grey;'>
-<?php if ($from_learnpath != 'yes') { ?>
-        <tr>
-          <td width="26%"><b><?php echo get_lang('CourseResources'); ?></b></td>
-        </tr>
+    <table width="300" border="0" cellspacing="0" cellpadding="0" style='border-right:1px solid grey;'>
+    <?php if ($from_learnpath != 'yes') { ?>
+    <tr>
+        <td width="26%"><b><?php echo get_lang('CourseResources'); ?></b></td>
+    </tr>
         <?php
         if (api_is_allowed_to_edit() || in_array(TOOL_DOCUMENT, $active_modules)) {
-        ?>
+            ?>
         <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Document&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Documents')."</a>"; ?></td>
+            <td><?php echo "<a href=\"".api_get_self(
+            )."?content=Document&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+                'Documents'
+            )."</a>"; ?></td>
         </tr>
-        <?php
+            <?php
         }
         if (api_is_allowed_to_edit() || in_array(TOOL_CALENDAR_EVENT, $active_modules)) {
-        ?>
+            ?>
         <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Agenda&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Agenda')."</a>"; ?></td>
+            <td><?php echo "<a href=\"".api_get_self(
+            )."?content=Agenda&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+                'Agenda'
+            )."</a>"; ?></td>
         </tr>
-        <?php
+            <?php
         }
         if (api_is_allowed_to_edit() || in_array(TOOL_ANNOUNCEMENT, $active_modules)) {
-        ?>
+            ?>
         <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Ad_Valvas&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('AdValvas')."</a>"; ?></td>
+            <td><?php echo "<a href=\"".api_get_self(
+            )."?content=Ad_Valvas&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+                'AdValvas'
+            )."</a>"; ?></td>
         </tr>
-        <?php
+            <?php
         }
         if (api_is_allowed_to_edit() || in_array(TOOL_BB_FORUM, $active_modules)) {
-        ?>
+            ?>
         <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Forum&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Forum')."</a>"; ?></td>
+            <td><?php echo "<a href=\"".api_get_self(
+            )."?content=Forum&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+                'Forum'
+            )."</a>"; ?></td>
         </tr>
-        <?php
+            <?php
         }
         if (api_is_allowed_to_edit() || in_array(TOOL_LINK, $active_modules)) {
-        ?>
+            ?>
         <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Link&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Links')."</a>"; ?></td>
+            <td><?php echo "<a href=\"".api_get_self(
+            )."?content=Link&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+                'Links'
+            )."</a>"; ?></td>
         </tr>
-        <?php
+            <?php
         }
         if (api_is_allowed_to_edit() || in_array(TOOL_QUIZ, $active_modules)) {
-        ?>
+            ?>
         <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Exercise&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Exercise')."</a>"; ?></td>
+            <td><?php echo "<a href=\"".api_get_self(
+            )."?content=Exercise&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+                'Exercise'
+            )."</a>"; ?></td>
         </tr>
-        <?php
+            <?php
         }
-} else {
-?>
-        <!--tr>
+    } else {
+        ?>
+    <!--tr>
           <td width="26%"><b><?php echo get_lang('ExportableCourseResources'); ?></b></td>
         </tr-->
-<?php if ($multi_level_learnpath === true ) { ?>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=chapter&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Chapter')."</a>"; ?></td>
-        </tr>
-<?php } ?>
+        <?php if ($multi_level_learnpath === true) { ?>
         <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Document&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Document')."</a>"; ?></td>
+            <td><?php echo "<a href=\"".api_get_self(
+            )."?content=chapter&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+                'Chapter'
+            )."</a>"; ?></td>
         </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Exercise&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Exercise')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Link&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Link')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Forum&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Forum')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Agenda&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Agenda')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Ad_Valvas&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('AdValvas')."</a>"; ?></td>
-        </tr>
-        <!--tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Course_description&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('CourseDescription')."</a>"; ?></td>
-        </tr-->
-        <!--tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Introduction_text&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('IntroductionText')."</a>"; ?></td>
+            <?php } ?>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Document&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Document'
+        )."</a>"; ?></td>
+    </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Exercise&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Exercise'
+        )."</a>"; ?></td>
+    </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Link&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Link'
+        )."</a>"; ?></td>
+    </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Forum&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Forum'
+        )."</a>"; ?></td>
+    </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Agenda&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Agenda'
+        )."</a>"; ?></td>
+    </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Ad_Valvas&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'AdValvas'
+        )."</a>"; ?></td>
+    </tr>
+    <!--tr>
+          <td><?php echo "<a href=\"".api_get_self(
+    )."?content=Course_description&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+        'CourseDescription'
+    )."</a>"; ?></td>
         </tr-->
-        <!--tr>
-          <td>&nbsp;</td>
+    <!--tr>
+          <td><?php echo "<a href=\"".api_get_self(
+    )."?content=Introduction_text&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+        'IntroductionText'
+    )."</a>"; ?></td>
         </tr-->
-        <!--tr>
+    <!--tr>
+      <td>&nbsp;</td>
+    </tr-->
+    <!--tr>
           <td width="26%"><b><?php echo get_lang('DokeosRelatedCourseMaterial'); ?></b></td>
         </tr-->
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Dropbox&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Dropbox')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Assignment&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Assignments')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Groups&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Groups')."</a>"; ?></td>
-        </tr>
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Users&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('Users')."</a>"; ?></td>
-        </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Dropbox&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Dropbox'
+        )."</a>"; ?></td>
+    </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Assignment&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Assignments'
+        )."</a>"; ?></td>
+    </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Groups&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Groups'
+        )."</a>"; ?></td>
+    </tr>
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Users&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'Users'
+        )."</a>"; ?></td>
+    </tr>
 
         <?php
-}
-?>
-        <!--tr>
-          <td>&nbsp;</td>
-        </tr-->
-        <!--tr>
+    }
+    ?>
+    <!--tr>
+      <td>&nbsp;</td>
+    </tr-->
+    <!--tr>
           <td><b><?php echo get_lang('ExternalResources'); ?></b></td>
         </tr-->
-        <tr>
-          <td><?php echo "<a href=\"".api_get_self()."?content=Externallink&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('ExternalLink')."</a>"; ?></td>
-        </tr>
-        <?php
+    <tr>
+        <td><?php echo "<a href=\"".api_get_self(
+        )."?content=Externallink&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'ExternalLink'
+        )."</a>"; ?></td>
+    </tr>
+    <?php
 
-if ($from_learnpath != 'yes') {
-    echo "<tr><td>&nbsp;</td></tr>";
-    echo "<tr><td><b>".get_lang('ResourcesAdded')." (";
-    echo count($addedresource);
-    echo ")</b></td></tr>";
-    echo "<tr><td nowrap><a href=\"".api_get_self()."?showresources=true&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang('ShowDelete')."</a>";
-    echo "</td></tr>";
-}
-?>
-        <tr>
-          <td>&nbsp;</td>
-        </tr>
-        <!--<tr>
+    if ($from_learnpath != 'yes') {
+        echo "<tr><td>&nbsp;</td></tr>";
+        echo "<tr><td><b>".get_lang('ResourcesAdded')." (";
+        echo count($addedresource);
+        echo ")</b></td></tr>";
+        echo "<tr><td nowrap><a href=\"".api_get_self(
+        )."?showresources=true&action=$action&id=$id&lp_id=$learnpath_id&parent_item_id=$chapter_id&source_forum=$source_forum&originalresource=no\">".get_lang(
+            'ShowDelete'
+        )."</a>";
+        echo "</td></tr>";
+    }
+    ?>
+    <tr>
+        <td>&nbsp;</td>
+    </tr>
+    <!--<tr>
           <td><b><?php echo get_lang('BackTo'); ?></b></td>
         </tr>//-->
-        <tr>
-          <td>
+    <tr>
+        <td>
 
-          <?php
+            <?php
 
-if ($from_learnpath != 'yes') {
-    echo "<form method=\"post\" action=\"{$_SESSION['origintoolurl']}\" style=\"margin: 0px;\"><input type=\"submit\" value=\"".'  '.get_lang('Ok').'  '."\"></form>";
-} else {
-    echo "<form method=\"get\" action=\"lp_controller.php\" style=\"margin: 0px;\"><input type=\"hidden\" name=\"lp_id\" value=\"".htmlentities($learnpath_id)."\"><input type=\"hidden\" name=\"action\" value=\"admin_view\"><input type=\"submit\" value=\"".'  '.get_lang('Ok').'  '."\"></form>";
-}
-?>
+            if ($from_learnpath != 'yes') {
+                echo "<form method=\"post\" action=\"{$_SESSION['origintoolurl']}\" style=\"margin: 0px;\"><input type=\"submit\" value=\"".'  '.get_lang(
+                    'Ok'
+                ).'  '."\"></form>";
+            } else {
+                echo "<form method=\"get\" action=\"lp_controller.php\" style=\"margin: 0px;\"><input type=\"hidden\" name=\"lp_id\" value=\"".htmlentities(
+                    $learnpath_id
+                )."\"><input type=\"hidden\" name=\"action\" value=\"admin_view\"><input type=\"submit\" value=\"".'  '.get_lang(
+                    'Ok'
+                ).'  '."\"></form>";
+            }
+            ?>
 
-          </td>
-        </tr>
-        <tr>
-          <td>&nbsp;</td>
-        </tr>
-      </table>
+        </td>
+    </tr>
+    <tr>
+        <td>&nbsp;</td>
+    </tr>
+    </table>
     </td>
     <td valign="top">
       <?php
@@ -674,8 +751,12 @@ if ($content == 'Agenda') {
 
 if ($content == 'chapter') {
     echo '<table><form name="add_chapter" action="'.'" method="POST">'."\n";
-    echo '  <tr><td>'.get_lang('Title').'</td><td><input type="text" name="title" value="'.$title.'"></input></td></tr>'."\n";
-    echo '  <tr><td>'.get_lang('Description').'</td><td><input type="text" name="description" value="'.$description.'"></input></td></tr>'."\n";
+    echo '  <tr><td>'.get_lang(
+        'Title'
+    ).'</td><td><input type="text" name="title" value="'.$title.'"></input></td></tr>'."\n";
+    echo '  <tr><td>'.get_lang(
+        'Description'
+    ).'</td><td><input type="text" name="description" value="'.$description.'"></input></td></tr>'."\n";
     echo '  <tr><td></td><td><input type="submit" name="add_chapter" value="'.get_lang('AddIt').'"/></td></tr>'."\n";
     echo '</form></table>'."\n";
     //echo "<hr />";
@@ -688,7 +769,11 @@ if ($content == 'chapter') {
 // 2. we come to the resource linker for the first time (documents = default). In this case it can only be shown if
 //  			a. one is a teacher (documents can be shown even if the tool is inactive)
 //				b. one is a student AND the documents tool is active. Student cannot add documents if the documents tool is inactive (teacher can do this)
-if ($content == 'Document' || (empty($content) && (api_is_allowed_to_edit() || in_array(TOOL_DOCUMENT, $active_modules))) && !$_GET['showresources']) {
+if ($content == 'Document' || (empty($content) && (api_is_allowed_to_edit() || in_array(
+    TOOL_DOCUMENT,
+    $active_modules
+))) && !$_GET['showresources']
+) {
     // setting variables for file locations
     $baseServDir = $_configuration['root_sys'];
     $courseDir = $_course['path'].'/document';
@@ -696,7 +781,7 @@ if ($content == 'Document' || (empty($content) && (api_is_allowed_to_edit() || i
     // showing the link to move one folder up (when not in the root folder)
     show_folder_up();
     // showing the blue bar with the path in it when we are not in the root
-    if (get_levels($folder)) {
+    if (FileManager::get_levels($folder)) {
         echo "<table width=\"100%\"><tr><td bgcolor=\"#4171B5\">";
         echo "<img src=\"../img/opendir.gif\" alt='directory'><font color=\"#ffffff\"><b>";
         echo $folder."</b></font></td></tr></table>";
@@ -745,7 +830,8 @@ if ($content == 'Forum') {
                 echo "<tr><td bgcolor='#4171B5' colspan='2'><font color='white'><b>".$myrow['cat_title']."</b></font></td></tr>";
             }
             $old_cat_title = $myrow['cat_title'];
-            echo "<tr><td><img src='../img/forum.gif'><a href='".api_get_self()."?content=Forum&category=".$myrow['cat_id']."&forum=".$myrow['forum_id']."&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".$myrow['forum_name']."</td><td>";
+            echo "<tr><td><img src='../img/forum.gif'><a href='".api_get_self(
+            )."?content=Forum&category=".$myrow['cat_id']."&forum=".$myrow['forum_id']."&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".$myrow['forum_name']."</td><td>";
             showorhide_addresourcelink('Forum', $myrow['forum_id']);
             echo "</td></tr>";
         }
@@ -769,7 +855,8 @@ if ($content == 'Forum') {
             $sql = "SELECT * FROM ".$TBL_FORUMTOPICS." WHERE forum_id=$forum";
             $result = Database::query($sql);
             while ($myrow = Database::fetch_array($result)) {
-                echo "<tr><td><a href='".api_get_self()."?content=Forum&category=$category&forum=1&thread=".$myrow['topic_id']."&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".$myrow['topic_title']."</a>  (".$myrow['prenom']." ".$myrow['nom'].")</td><td>";
+                echo "<tr><td><a href='".api_get_self(
+                )."?content=Forum&category=$category&forum=1&thread=".$myrow['topic_id']."&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".$myrow['topic_title']."</a>  (".$myrow['prenom']." ".$myrow['nom'].")</td><td>";
                 showorhide_addresourcelink("Thread", $myrow['topic_id']);
                 echo "</td></tr>";
             }
@@ -802,7 +889,9 @@ if ($content == 'Link') {
     $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
     if (($learnpath_id != '') and ($content == 'Link')) {
         echo "<form name='learnpath_link'><table>";
-        echo "<tr></td><td align='left'>".get_lang('LinkTarget')." :</td><td align='left'><select name='target' onchange='javascript: targetfunc();'><option value='_self' ";
+        echo "<tr></td><td align='left'>".get_lang(
+            'LinkTarget'
+        )." :</td><td align='left'><select name='target' onchange='javascript: targetfunc();'><option value='_self' ";
         if ($target == '_self') {
             echo "selected";
         }
@@ -872,90 +961,115 @@ if (($content == 'Exercise') || ($content == 'HotPotatoes')) {
 /* External Links */
 
 if ($content == 'Externallink') {
-?>
-  <form name="form1" method="post" action="">
-  <table width="80%" border="0" cellspacing="0" cellpadding="0">
-    <tr>
-      <td align="right"><?php echo get_lang('ExternalLink'); ?> : &nbsp;</td>
-      <td align="left"><input name="external_link" type="text" id="external_link" value="http://"></td>
-      <?php
-
-    if ($learnpath_id != '') {
-        echo "</tr><tr><td align='right'>".get_lang('LinkTarget')." :</td><td align='left'><select name='target'><option value='_self'>".get_lang('SameWindow')."</option><option value='_blank'>".get_lang('NewWindow')."</option></select></td>";
-    }
-?>
-    </tr>
-    <tr>
-      <td><?php if ($is_allowedToEdit) {echo get_lang('AddToLinks');} ?></td>
-      <td>
-        <?php if ($is_allowedToEdit){?>
-      <select name="add_2_links" id="add_2_links">
-      <option value="niet toevoegen" selected="selected">-<?php echo get_lang('DontAdd'); ?>-</option>
-      <option value="0"><?php echo get_lang('MainCategory'); ?></option>
-        <?php
-
-    $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
-    $sql = "SELECT * FROM $tbl_categories ORDER BY display_order ASC";
-    echo $sql;
-    $result = Database::query($sql);
-    while ($row = Database::fetch_array($result)) {
-        echo "<option value='".$row['id']."'>".$row['category_title']."</option>";
-    }
-?>
-
-      </select><?php } ?></td>
-    </tr>
-    <tr>
-      <td>&nbsp;</td>
-      <td><input name="external_link_submit" type="submit" id="external_link_submit" value="<?php echo get_lang('AddIt'); ?>"></td>
-    </tr>
-    <tr>
-      <td>&nbsp;</td>
-      <td>&nbsp;</td>
-    </tr>
-    <tr>
-      <td colspan="2">&nbsp;</td>
-    </tr>
-  </table>
+    ?>
+<form name="form1" method="post" action="">
+    <table width="80%" border="0" cellspacing="0" cellpadding="0">
+        <tr>
+            <td align="right"><?php echo get_lang('ExternalLink'); ?> : &nbsp;</td>
+            <td align="left"><input name="external_link" type="text" id="external_link" value="http://"></td>
+            <?php
+
+            if ($learnpath_id != '') {
+                echo "</tr><tr><td align='right'>".get_lang(
+                    'LinkTarget'
+                )." :</td><td align='left'><select name='target'><option value='_self'>".get_lang(
+                    'SameWindow'
+                )."</option><option value='_blank'>".get_lang('NewWindow')."</option></select></td>";
+            }
+            ?>
+        </tr>
+        <tr>
+            <td><?php if ($is_allowedToEdit) {
+                echo get_lang('AddToLinks');
+            } ?></td>
+            <td>
+                <?php if ($is_allowedToEdit) { ?>
+                <select name="add_2_links" id="add_2_links">
+                    <option value="niet toevoegen" selected="selected">-<?php echo get_lang('DontAdd'); ?>-</option>
+                    <option value="0"><?php echo get_lang('MainCategory'); ?></option>
+                    <?php
+
+                    $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
+                    $sql = "SELECT * FROM $tbl_categories ORDER BY display_order ASC";
+                    echo $sql;
+                    $result = Database::query($sql);
+                    while ($row = Database::fetch_array($result)) {
+                        echo "<option value='".$row['id']."'>".$row['category_title']."</option>";
+                    }
+                    ?>
+
+                </select><?php } ?></td>
+        </tr>
+        <tr>
+            <td>&nbsp;</td>
+            <td><input name="external_link_submit" type="submit" id="external_link_submit"
+                       value="<?php echo get_lang('AddIt'); ?>"></td>
+        </tr>
+        <tr>
+            <td>&nbsp;</td>
+            <td>&nbsp;</td>
+        </tr>
+        <tr>
+            <td colspan="2">&nbsp;</td>
+        </tr>
+    </table>
 </form>
-    <?php
+<?php
 
 }
 
 /* Assignments */
 
 if ($content == 'Assignment') {
-    echo "<a href=".api_get_self()."?content=Ass&add=Ass&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no>".get_lang('AddAssignmentPage')."</a>";
+    echo "<a href=".api_get_self(
+    )."?content=Ass&add=Ass&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no>".get_lang(
+        'AddAssignmentPage'
+    )."</a>";
 }
 
 /* Dropbox */
 
 if ($content == 'Dropbox') {
-    echo "<a href='".api_get_self()."?content=Drop&add=Drop&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('DropboxAdd')."</a>";
+    echo "<a href='".api_get_self(
+    )."?content=Drop&add=Drop&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang(
+        'DropboxAdd'
+    )."</a>";
 }
 
 /* Introduction text */
 
 if ($content == 'Introduction_text') {
-    echo "<a href='".api_get_self()."?content=Intro&add=Intro&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('IntroductionTextAdd')."</a>";
+    echo "<a href='".api_get_self(
+    )."?content=Intro&add=Intro&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang(
+        'IntroductionTextAdd'
+    )."</a>";
 }
 
 /* Course description */
 
 if ($content == 'Course_description') {
-    echo "<a href='".api_get_self()."?content=Course_desc&add=Course_desc&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('CourseDescriptionAdd')."</a>";
+    echo "<a href='".api_get_self(
+    )."?content=Course_desc&add=Course_desc&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang(
+        'CourseDescriptionAdd'
+    )."</a>";
 }
 
 /* Groups */
 
 if ($content == 'Groups') {
-    echo "<a href='".api_get_self()."?content=Group&add=Group&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('GroupsAdd')."</a>";
+    echo "<a href='".api_get_self(
+    )."?content=Group&add=Group&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang(
+        'GroupsAdd'
+    )."</a>";
 }
 
 /* Users */
 
 if ($content == 'Users') {
-    echo "<a href='".api_get_self()."?content=User&add=User&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang('UsersAdd')."</a>";
+    echo "<a href='".api_get_self(
+    )."?content=User&add=User&action=$action&lp_id=$learnpath_id&parent_item_id=$chapter_id&originalresource=no'>".get_lang(
+        'UsersAdd'
+    )."</a>";
 }
 
 if ($showresources) {

+ 292 - 131
main/newscorm/scorm.class.php

@@ -4,7 +4,7 @@
 /**
  * Defines the scorm class, which is meant to contain the scorm items (nuclear elements)
  * @package chamilo.learnpath.scorm
- * @author	Yannick Warnier <ywarnier@beeznest.org>
+ * @author    Yannick Warnier <ywarnier@beeznest.org>
  */
 
 /**
@@ -19,7 +19,8 @@ require_once 'scormResource.class.php';
  * Defines the "scorm" child of class "learnpath"
  * @package chamilo.learnpath
  */
-class scorm extends learnpath {
+class scorm extends learnpath
+{
     public $manifest = array();
     public $resources = array();
     public $resources_att = array();
@@ -37,12 +38,18 @@ class scorm extends learnpath {
 
     /**
      * Class constructor. Based on the parent constructor.
-     * @param	string	Course code
-     * @param	integer	Learnpath ID in DB
-     * @param	integer	User ID
+     * @param    string    Course code
+     * @param    integer    Learnpath ID in DB
+     * @param    integer    User ID
      */
-    function __construct($course_code = null, $resource_id = null, $user_id = null) {
-        if ($this->debug > 0) { error_log('New LP - scorm::scorm('.$course_code.','.$resource_id.','.$user_id.') - In scorm constructor', 0); }
+    function __construct($course_code = null, $resource_id = null, $user_id = null)
+    {
+        if ($this->debug > 0) {
+            error_log(
+                'New LP - scorm::scorm('.$course_code.','.$resource_id.','.$user_id.') - In scorm constructor',
+                0
+            );
+        }
         if (!empty($course_code) && !empty($resource_id) && !empty($user_id)) {
             parent::__construct($course_code, $resource_id, $user_id);
         } else {
@@ -52,10 +59,13 @@ class scorm extends learnpath {
 
     /**
      * Opens a resource
-     * @param	integer	Database ID of the resource
+     * @param    integer    Database ID of the resource
      */
-    function open($id) {
-        if ($this->debug > 0) { error_log('New LP - scorm::open() - In scorm::open method', 0); }
+    function open($id)
+    {
+        if ($this->debug > 0) {
+            error_log('New LP - scorm::open() - In scorm::open method', 0);
+        }
         // redefine parent method
     }
 
@@ -69,11 +79,14 @@ class scorm extends learnpath {
 
     /**
      * Parses an imsmanifest.xml file and puts everything into the $manifest array
-     * @param	string	Path to the imsmanifest.xml file on the system. If not defined, uses the base path of the course's scorm dir
-     * @return	array	Structured array representing the imsmanifest's contents
+     * @param    string    Path to the imsmanifest.xml file on the system. If not defined, uses the base path of the course's scorm dir
+     * @return    array    Structured array representing the imsmanifest's contents
      */
-    function parse_manifest($file = '') {
-        if ($this->debug > 0) { error_log('In scorm::parse_manifest('.$file.')', 0); }
+    function parse_manifest($file = '')
+    {
+        if ($this->debug > 0) {
+            error_log('In scorm::parse_manifest('.$file.')', 0);
+        }
         if (empty($file)) {
             // Get the path of the imsmanifest file.
         }
@@ -81,22 +94,37 @@ class scorm extends learnpath {
 
             // Parsing using PHP5 DOMXML methods.
 
-            if ($this->debug > 0) { error_log('In scorm::parse_manifest() - Parsing using PHP5 method', 0); }
+            if ($this->debug > 0) {
+                error_log('In scorm::parse_manifest() - Parsing using PHP5 method', 0);
+            }
 
             //$this->manifest_encoding = api_detect_encoding_xml($xml); // This is the usual way for reading the encoding.
-            $this->manifest_encoding = self::detect_manifest_encoding($xml); // This method reads the encoding, it tries to be correct even in cases of wrong or missing encoding declarations.
+            $this->manifest_encoding = self::detect_manifest_encoding(
+                $xml
+            ); // This method reads the encoding, it tries to be correct even in cases of wrong or missing encoding declarations.
 
-            $xml = api_utf8_encode_xml($xml, $this->manifest_encoding); // UTF-8 is supported by DOMDocument class, this is for sure.
+            $xml = api_utf8_encode_xml(
+                $xml,
+                $this->manifest_encoding
+            ); // UTF-8 is supported by DOMDocument class, this is for sure.
 
             $doc = new DOMDocument();
             $res = @$doc->loadXML($xml);
             if ($res === false) {
-                if ($this->debug > 0) { error_log('New LP - In scorm::parse_manifest() - Exception thrown when loading '.$file.' in DOMDocument', 0); }
+                if ($this->debug > 0) {
+                    error_log(
+                        'New LP - In scorm::parse_manifest() - Exception thrown when loading '.$file.' in DOMDocument',
+                        0
+                    );
+                }
+
                 // Throw exception?
                 return null;
             }
 
-            if ($this->debug > 1) { error_log('New LP - Called  (encoding:'.$doc->xmlEncoding.' - saved: '.$this->manifest_encoding.')', 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - Called  (encoding:'.$doc->xmlEncoding.' - saved: '.$this->manifest_encoding.')', 0);
+            }
 
             $root = $doc->documentElement;
             if ($root->hasAttributes()) {
@@ -118,7 +146,7 @@ class scorm extends learnpath {
                             switch ($child->tagName) {
                                 case 'metadata':
                                     // Parse items from inside the <metadata> element.
-                                    $this->metadata = new scormMetadata('manifest',$child);
+                                    $this->metadata = new scormMetadata('manifest', $child);
                                     break;
                                 case 'organizations':
                                     // Contains the course structure - this element appears 1 and only 1 time in a package imsmanifest. It contains at least one 'organization' sub-element.
@@ -210,10 +238,14 @@ class scorm extends learnpath {
             // End parsing using PHP5 DOMXML methods.
 
         } else {
-            if ($this->debug > 1) { error_log('New LP - Could not open/read file '.$file, 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - Could not open/read file '.$file, 0);
+            }
             $this->set_error_msg("File $file could not be read");
+
             return null;
         }
+
         // TODO: Close the DOM handler.
         return $this->manifest;
     }
@@ -225,7 +257,8 @@ class scorm extends learnpath {
      * @param string $xml    The input xml-text.
      * @return string        The detected value of the input xml.
      */
-    private function detect_manifest_encoding(& $xml) {
+    private function detect_manifest_encoding(& $xml)
+    {
 
         if (api_is_valid_utf8($xml)) {
             return 'UTF-8';
@@ -253,17 +286,21 @@ class scorm extends learnpath {
         if (empty($test_string)) {
             $test_string = $xml;
         }
+
         return api_detect_encoding($test_string);
 
     }
 
     /**
      * Import the scorm object (as a result from the parse_manifest function) into the database structure
-     * @param	string	Unique course code
-     * @return	bool	Returns -1 on error
+     * @param    string    Unique course code
+     * @return    bool    Returns -1 on error
      */
-    function import_manifest($course_code, $use_max_score = 1) {
-        if ($this->debug > 0) { error_log('New LP - Entered import_manifest('.$course_code.')', 0); }
+    function import_manifest($course_code, $use_max_score = 1)
+    {
+        if ($this->debug > 0) {
+            error_log('New LP - Entered import_manifest('.$course_code.')', 0);
+        }
         $course_info = api_get_course_info($course_code);
         $course_id = $course_info['real_id'];
 
@@ -291,17 +328,32 @@ class scorm extends learnpath {
             $myname = $oOrganization->get_name();
             $myname = api_utf8_decode($myname);
 
-            $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order, session_id, use_max_score)" .
-                    "VALUES ($course_id , 2,'".$myname."', '".$oOrganization->get_ref()."','','".$this->subdir."', 0, 'embedded', '".$this->manifest_encoding."', 'scorm_api.php', $dsp, $session_id, $use_max_score)";
-            if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting path: '. $sql, 0); }
+            $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order, session_id, use_max_score)".
+                "VALUES ($course_id , 2,'".$myname."', '".$oOrganization->get_ref(
+            )."','','".$this->subdir."', 0, 'embedded', '".$this->manifest_encoding."', 'scorm_api.php', $dsp, $session_id, $use_max_score)";
+            if ($this->debug > 1) {
+                error_log('New LP - In import_manifest(), inserting path: '.$sql, 0);
+            }
 
             $res = Database::query($sql);
             $lp_id = Database::insert_id();
             $this->lp_id = $lp_id;
 
             // Insert into item_property.
-            api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'LearnpathAdded', api_get_user_id());
-            api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'visible', api_get_user_id());
+            api_item_property_update(
+                api_get_course_info($course_code),
+                TOOL_LEARNPATH,
+                $this->lp_id,
+                'LearnpathAdded',
+                api_get_user_id()
+            );
+            api_item_property_update(
+                api_get_course_info($course_code),
+                TOOL_LEARNPATH,
+                $this->lp_id,
+                'visible',
+                api_get_user_id()
+            );
 
             // Now insert all elements from inside that learning path.
             // Make sure we also get the href and sco/asset from the resources.
@@ -323,7 +375,7 @@ class scorm extends learnpath {
                         $outdated_parent = array_pop($parents_stack);
                     }
                     $parent = array_pop($parents_stack); // Just save that value, then add it back.
-                    array_push($parents_stack,$parent);
+                    array_push($parents_stack, $parent);
                 }
                 $path = '';
                 $type = 'dir';
@@ -373,15 +425,17 @@ class scorm extends learnpath {
 
                 $prereq = Database::escape_string($item['prerequisites']);
 
-                $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters) VALUES " .
-                        "($course_id, $lp_id, '$type','$identifier', '$title', '$path' , 0, $max_score, $value_add" .
-                        "$parent, $previous, 0, " .
-                        "'$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."'," .
-                        "'".$item['parameters']."'" .
-                        ")";
+                $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters) VALUES ".
+                    "($course_id, $lp_id, '$type','$identifier', '$title', '$path' , 0, $max_score, $value_add".
+                    "$parent, $previous, 0, ".
+                    "'$prereq', ".$item['rel_order'].", '".$item['datafromlms']."',".
+                    "'".$item['parameters']."'".
+                    ")";
 
                 $res_item = Database::query($sql_item);
-                if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting item : '.$sql_item.' : '.Database::error(), 0); }
+                if ($this->debug > 1) {
+                    error_log('New LP - In import_manifest(), inserting item : '.$sql_item.' : '.Database::error(), 0);
+                }
                 $item_id = Database::insert_id();
                 // Now update previous item to change next_item_id.
                 $upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE c_id = $course_id AND id = $previous";
@@ -397,7 +451,7 @@ class scorm extends learnpath {
 
                     $di = new ChamiloIndexer();
                     isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
-                    $di->connectDb(NULL, NULL, $lang);
+                    $di->connectDb(null, null, $lang);
                     $ic_slide = new IndexableChunk();
                     $ic_slide->addValue('title', $title);
                     $specific_fields = get_specific_field_list();
@@ -405,7 +459,7 @@ class scorm extends learnpath {
                     foreach ($specific_fields as $specific_field) {
                         if (isset($_REQUEST[$specific_field['code']])) {
                             $sterms = trim($_REQUEST[$specific_field['code']]);
-                            $all_specific_terms .= ' '. $sterms;
+                            $all_specific_terms .= ' '.$sterms;
                             if (!empty($sterms)) {
                                 $sterms = explode(',', $sterms);
                                 foreach ($sterms as $sterm) {
@@ -414,7 +468,7 @@ class scorm extends learnpath {
                             }
                         }
                     }
-                    $body_to_index = $all_specific_terms .' '. $title;
+                    $body_to_index = $all_specific_terms.' '.$title;
                     $ic_slide->addValue("content", $body_to_index);
                     // TODO: Add a comment to say terms separated by commas.
                     $courseid = api_get_course_id();
@@ -423,7 +477,8 @@ class scorm extends learnpath {
                     $xapian_data = array(
                         SE_COURSE_ID => $courseid,
                         SE_TOOL_ID => TOOL_LEARNPATH,
-                        SE_DATA => array('lp_id' => $lp_id, 'lp_item'=> $previous, 'document_id' => ''), // TODO: Unify with other lp types.
+                        SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => ''),
+                        // TODO: Unify with other lp types.
                         SE_USER => (int)api_get_user_id(),
                     );
                     $ic_slide->xapian_data = serialize($xapian_data);
@@ -445,51 +500,69 @@ class scorm extends learnpath {
 
     /**
      * Intermediate to import_package only to allow import from local zip files
-     * @param	string	Path to the zip file, from the sys root
-     * @param	string	Current path (optional)
-     * @return string	Absolute path to the imsmanifest.xml file or empty string on error
+     * @param    string    Path to the zip file, from the sys root
+     * @param    string    Current path (optional)
+     * @return string    Absolute path to the imsmanifest.xml file or empty string on error
      */
-    function import_local_package($file_path, $current_dir = '') {
+    function import_local_package($file_path, $current_dir = '')
+    {
         // TODO: Prepare info as given by the $_FILES[''] vector.
         $file_info = array();
         $file_info['tmp_name'] = $file_path;
         $file_info['name'] = basename($file_path);
+
         // Call the normal import_package function.
         return $this->import_package($file_info, $current_dir);
     }
 
     /**
      * Imports a zip file into the Chamilo structure
-     * @param	string	Zip file info as given by $_FILES['userFile']
-     * @return	string	Absolute path to the imsmanifest.xml file or empty string on error
+     * @param    string    Zip file info as given by $_FILES['userFile']
+     * @return    string    Absolute path to the imsmanifest.xml file or empty string on error
      */
-    function import_package($zip_file_info, $current_dir = '') {
-        if ($this->debug > 0) { error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method', 0); }
+    function import_package($zip_file_info, $current_dir = '')
+    {
+        if ($this->debug > 0) {
+            error_log('In scorm::import_package('.print_r($zip_file_info, true).',"'.$current_dir.'") method', 0);
+        }
 
         $maxFilledSpace = DocumentManager :: get_course_quota();
 
         $zip_file_path = $zip_file_info['tmp_name'];
         $zip_file_name = $zip_file_info['name'];
 
-        if ($this->debug > 1) { error_log('New LP - import_package() - zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name, 0); }
-        $course_rel_dir     = api_get_course_path().'/scorm'; // scorm dir web path starting from /courses
-        $course_sys_dir     = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // Absolute system path for this course.
-        $current_dir        = replace_dangerous_char(trim($current_dir),'strict'); // Current dir we are in, inside scorm/
-        if ($this->debug > 1) { error_log('New LP - import_package() - current_dir = '.$current_dir, 0); }
+        if ($this->debug > 1) {
+            error_log(
+                'New LP - import_package() - zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name,
+                0
+            );
+        }
+        $course_rel_dir = api_get_course_path().'/scorm'; // scorm dir web path starting from /courses
+        $course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // Absolute system path for this course.
+        $current_dir = replace_dangerous_char(trim($current_dir), 'strict'); // Current dir we are in, inside scorm/
+        if ($this->debug > 1) {
+            error_log('New LP - import_package() - current_dir = '.$current_dir, 0);
+        }
 
-         //$uploaded_filename = $_FILES['userFile']['name'];
+        //$uploaded_filename = $_FILES['userFile']['name'];
         // Get name of the zip file without the extension.
-        if ($this->debug > 1) { error_log('New LP - Received zip file name: '.$zip_file_path, 0); }
+        if ($this->debug > 1) {
+            error_log('New LP - Received zip file name: '.$zip_file_path, 0);
+        }
         $file_info = pathinfo($zip_file_name);
         $filename = $file_info['basename'];
         $extension = $file_info['extension'];
-        $file_base_name = str_replace('.'.$extension,'',$filename); // Filename without its extension.
+        $file_base_name = str_replace('.'.$extension, '', $filename); // Filename without its extension.
         $this->zipname = $file_base_name; // Save for later in case we don't have a title.
 
-        if ($this->debug > 1) { error_log("New LP - base file name is : ".$file_base_name, 0); }
-        $new_dir = replace_dangerous_char(trim($file_base_name),'strict');
+        if ($this->debug > 1) {
+            error_log("New LP - base file name is : ".$file_base_name, 0);
+        }
+        $new_dir = replace_dangerous_char(trim($file_base_name), 'strict');
         $this->subdir = $new_dir;
-        if ($this->debug > 1) { error_log("New LP - subdir is first set to : ".$this->subdir, 0); }
+        if ($this->debug > 1) {
+            error_log("New LP - subdir is first set to : ".$this->subdir, 0);
+        }
 
         $zipFile = new PclZip($zip_file_path);
 
@@ -515,7 +588,9 @@ class scorm extends learnpath {
                     $at_root = true;
                 } else {
                     //$this->subdir .= '/'.dirname($thisContent['filename']);
-                    if ($this->debug > 2) { error_log("New LP - subdir is now ".$this->subdir, 0); }
+                    if ($this->debug > 2) {
+                        error_log("New LP - subdir is now ".$this->subdir, 0);
+                    }
                 }
                 $package_type = 'scorm';
                 $manifest_list[] = $thisContent['filename'];
@@ -531,7 +606,7 @@ class scorm extends learnpath {
         $slash_count = substr_count($shortest_path, '/');
         foreach ($manifest_list as $manifest_path) {
             $tmp_slash_count = substr_count($manifest_path, '/');
-            if ($tmp_slash_count<$slash_count) {
+            if ($tmp_slash_count < $slash_count) {
                 $shortest_path = $manifest_path;
                 $slash_count = $tmp_slash_count;
             }
@@ -539,17 +614,24 @@ class scorm extends learnpath {
         $this->subdir .= '/'.dirname($shortest_path); // Do not concatenate because already done above.
         $manifest = $shortest_path;
 
-        if ($this->debug > 1) { error_log('New LP - Package type is now '.$package_type, 0); }
+        if ($this->debug > 1) {
+            error_log('New LP - Package type is now '.$package_type, 0);
+        }
 
-        if ($package_type== '')
-        // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
+        if ($package_type == '') // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
         {
-            if ($this->debug > 1) { error_log('New LP - Package type is empty', 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - Package type is empty', 0);
+            }
+
             return api_failure::set_failure('not_scorm_content');
         }
 
-        if (!enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
-            if ($this->debug > 1) { error_log('New LP - Not enough space to store package', 0); }
+        if (!FileManager::enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
+            if ($this->debug > 1) {
+                error_log('New LP - Not enough space to store package', 0);
+            }
+
             return api_failure::set_failure('not_enough_space');
         }
 
@@ -558,8 +640,8 @@ class scorm extends learnpath {
             $new_dir = '/'.$new_dir;
         }
 
-        if ($new_dir[strlen($new_dir)-1] == '/') {
-            $new_dir = substr($new_dir,0,-1);
+        if ($new_dir[strlen($new_dir) - 1] == '/') {
+            $new_dir = substr($new_dir, 0, -1);
         }
 
         /* Uncompressing phase */
@@ -570,10 +652,16 @@ class scorm extends learnpath {
             - parse & change relative html links
             - make sure the filenames are secure (filter funny characters or php extensions)
         */
-        if (is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir, api_get_permissions_for_new_directories())) {
+        if (is_dir($course_sys_dir.$new_dir) OR @mkdir(
+            $course_sys_dir.$new_dir,
+            api_get_permissions_for_new_directories()
+        )
+        ) {
 
             // PHP method - slower...
-            if ($this->debug >= 1) { error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir, 0); }
+            if ($this->debug >= 1) {
+                error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir, 0);
+            }
             $saved_dir = getcwd();
             chdir($course_sys_dir.$new_dir);
             $unzippingState = $zipFile->extract();
@@ -583,7 +671,9 @@ class scorm extends learnpath {
 
                 // TODO: Fix relative links in html files (?)
                 $extension = strrchr($state['stored_filename'], '.');
-                if ($this->debug >= 1) { error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'], 0); }
+                if ($this->debug >= 1) {
+                    error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'], 0);
+                }
             }
 
             if (!empty($new_dir)) {
@@ -591,15 +681,21 @@ class scorm extends learnpath {
             }
             // Rename files, for example with \\ in it.
 
-            if ($this->debug >= 1) { error_log('New LP - try to open: '.$course_sys_dir.$new_dir, 0); }
+            if ($this->debug >= 1) {
+                error_log('New LP - try to open: '.$course_sys_dir.$new_dir, 0);
+            }
 
             if ($dir = @opendir($course_sys_dir.$new_dir)) {
-                if ($this->debug >= 1) { error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0); }
-                while ($file=readdir($dir)) {
+                if ($this->debug >= 1) {
+                    error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0);
+                }
+                while ($file = readdir($dir)) {
                     if ($file != '.' && $file != '..') {
                         $filetype = 'file';
 
-                        if (is_dir($course_sys_dir.$new_dir.$file)) $filetype = 'folder';
+                        if (is_dir($course_sys_dir.$new_dir.$file)) {
+                            $filetype = 'folder';
+                        }
 
                         // TODO: RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
                         //$safe_file = replace_dangerous_char($file, 'strict');
@@ -607,8 +703,12 @@ class scorm extends learnpath {
                         $repl_str = array('/', '.txt', '.txt');
                         $safe_file = str_replace($find_str, $repl_str, $file);
 
-                        if ($this->debug >= 1) { error_log('Comparing:  '.$safe_file, 0); }
-                        if ($this->debug >= 1) { error_log('and:  '.$file, 0); }
+                        if ($this->debug >= 1) {
+                            error_log('Comparing:  '.$safe_file, 0);
+                        }
+                        if ($this->debug >= 1) {
+                            error_log('and:  '.$file, 0);
+                        }
 
                         if ($safe_file != $file) {
                             //@rename($course_sys_dir.$new_dir, $course_sys_dir.'/'.$safe_file);
@@ -622,15 +722,21 @@ class scorm extends learnpath {
                                         $mybasedir = $mybasedir.$mysubdir.'/';
                                         if (!is_dir($mybasedir)) {
                                             @mkdir($mybasedir, api_get_permissions_for_new_directories());
-                                            if ($this->debug >= 1) { error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.', 0); }
+                                            if ($this->debug >= 1) {
+                                                error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.', 0);
+                                            }
                                         }
                                     }
                                 }
                             }
-                            @rename($course_sys_dir.$new_dir.$file,$course_sys_dir.$new_dir.$safe_file);
-                            if ($this->debug >= 1) { error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file, 0); }
+                            @rename($course_sys_dir.$new_dir.$file, $course_sys_dir.$new_dir.$safe_file);
+                            if ($this->debug >= 1) {
+                                error_log(
+                                    'New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file,
+                                    0
+                                );
+                            }
                         }
-                        //set_default_settings($course_sys_dir, $safe_file, $filetype);
                     }
                 }
 
@@ -638,26 +744,33 @@ class scorm extends learnpath {
                 chdir($saved_dir);
 
                 api_chmod_R($course_sys_dir.$new_dir, api_get_permissions_for_new_directories());
-                if ($this->debug > 1) { error_log('New LP - changed back to init dir: '.$course_sys_dir.$new_dir, 0); }
+                if ($this->debug > 1) {
+                    error_log('New LP - changed back to init dir: '.$course_sys_dir.$new_dir, 0);
+                }
             }
         } else {
             return '';
         }
+
         return $course_sys_dir.$new_dir.$manifest;
     }
 
     /**
      * Sets the proximity setting in the database
-     * @param	string	Proximity setting
+     * @param    string    Proximity setting
      */
-    function set_proximity($proxy = '') {
+    function set_proximity($proxy = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In scorm::set_proximity('.$proxy.') method', 0); }
+        if ($this->debug > 0) {
+            error_log('In scorm::set_proximity('.$proxy.') method', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE c_id = ".$course_id." AND id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -666,16 +779,20 @@ class scorm extends learnpath {
 
     /**
      * Sets the theme setting in the database
-     * @param	string	theme setting
+     * @param    string    theme setting
      */
-    function set_theme($theme = '') {
+    function set_theme($theme = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In scorm::set_theme('.$theme.') method', 0); }
+        if ($this->debug > 0) {
+            error_log('In scorm::set_theme('.$theme.') method', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE c_id = ".$course_id." AND id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -684,16 +801,20 @@ class scorm extends learnpath {
 
     /**
      * Sets the image setting in the database
-     * @param	string preview_image setting
+     * @param    string preview_image setting
      */
-    function set_preview_image($preview_image = '') {
+    function set_preview_image($preview_image = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In scorm::set_theme('.$preview_image.') method', 0); }
+        if ($this->debug > 0) {
+            error_log('In scorm::set_theme('.$preview_image.') method', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET preview_image = '$preview_image' WHERE c_id = ".$course_id." AND id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -702,16 +823,20 @@ class scorm extends learnpath {
 
     /**
      * Sets the author  setting in the database
-     * @param	string preview_image setting
+     * @param    string preview_image setting
      */
-    function set_author($author = '') {
+    function set_author($author = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In scorm::set_author('.$author.') method', 0); }
+        if ($this->debug > 0) {
+            error_log('In scorm::set_author('.$author.') method', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET author = '$author' WHERE c_id = ".$course_id." AND id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -720,16 +845,20 @@ class scorm extends learnpath {
 
     /**
      * Sets the content maker setting in the database
-     * @param	string	Proximity setting
+     * @param    string    Proximity setting
      */
-    function set_maker($maker = '') {
+    function set_maker($maker = '')
+    {
         $course_id = api_get_course_int_id();
-        if ($this->debug > 0) { error_log('In scorm::set_maker method('.$maker.')', 0); }
+        if ($this->debug > 0) {
+            error_log('In scorm::set_maker method('.$maker.')', 0);
+        }
         $lp = $this->get_id();
         if ($lp != 0) {
             $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
             $sql = "UPDATE $tbl_lp SET content_maker = '$maker' WHERE c_id = ".$course_id." AND id = ".$lp;
             $res = Database::query($sql);
+
             return $res;
         } else {
             return false;
@@ -738,10 +867,13 @@ class scorm extends learnpath {
 
     /**
      * Exports the current SCORM object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
-     * @param	integer	Learnpath ID (optional, taken from object context if not defined)
+     * @param    integer    Learnpath ID (optional, taken from object context if not defined)
      */
-    function export_zip($lp_id = null) {
-        if ($this->debug > 0) { error_log('In scorm::export_zip method('.$lp_id.')', 0); }
+    function export_zip($lp_id = null)
+    {
+        if ($this->debug > 0) {
+            error_log('In scorm::export_zip method('.$lp_id.')', 0);
+        }
         if (empty($lp_id)) {
             if (!is_object($this)) {
                 return false;
@@ -757,8 +889,7 @@ class scorm extends learnpath {
         //error_log('New LP - in export_zip()',0);
         //zip everything that is in the corresponding scorm dir
         //write the zip file somewhere (might be too big to return)
-        require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-        require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+
         require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 
         require_once 'learnpath_functions.inc.php';
@@ -794,7 +925,7 @@ class scorm extends learnpath {
         //DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.'.zip');
         DocumentManager :: file_send_for_download($zipfilename, true);
 
-        // Delete the temporary zip file and directory in fileManage.lib.php
+        // Delete the temporary zip file and directory in fileManager.lib.php
         FileManager::my_delete($zipfilename);
         FileManager::my_delete($zipfoldername);
 
@@ -803,26 +934,33 @@ class scorm extends learnpath {
 
     /**
      * Gets a resource's path if available, otherwise return empty string
-     * @param	string	Resource ID as used in resource array
-     * @return string	The resource's path as declared in imsmanifest.xml
+     * @param    string    Resource ID as used in resource array
+     * @return string    The resource's path as declared in imsmanifest.xml
      */
-    function get_res_path($id) {
-        if ($this->debug > 0) { error_log('In scorm::get_res_path('.$id.') method', 0); }
+    function get_res_path($id)
+    {
+        if ($this->debug > 0) {
+            error_log('In scorm::get_res_path('.$id.') method', 0);
+        }
         $path = '';
         if (isset($this->resources[$id])) {
             $oRes =& $this->resources[$id];
             $path = @$oRes->get_path();
         }
+
         return $path;
     }
 
     /**
      * Gets a resource's type if available, otherwise return empty string
-     * @param	string	Resource ID as used in resource array
-     * @return string	The resource's type as declared in imsmanifest.xml
+     * @param    string    Resource ID as used in resource array
+     * @return string    The resource's type as declared in imsmanifest.xml
      */
-    function get_res_type($id) {
-        if ($this->debug > 0) { error_log('In scorm::get_res_type('.$id.') method', 0); }
+    function get_res_type($id)
+    {
+        if ($this->debug > 0) {
+            error_log('In scorm::get_res_type('.$id.') method', 0);
+        }
         $type = '';
         if (isset($this->resources[$id])) {
             $oRes =& $this->resources[$id];
@@ -831,25 +969,30 @@ class scorm extends learnpath {
                 $type = $temptype;
             }
         }
+
         return $type;
     }
 
     /**
      * Gets the default organisation's title
-     * @return	string	The organization's title
+     * @return    string    The organization's title
      */
-    function get_title() {
-        if ($this->debug > 0) { error_log('In scorm::get_title() method', 0); }
+    function get_title()
+    {
+        if ($this->debug > 0) {
+            error_log('In scorm::get_title() method', 0);
+        }
         $title = '';
         if (isset($this->manifest['organizations']['default'])) {
             $title = $this->organizations[$this->manifest['organizations']['default']]->get_name();
-        } elseif (count($this->organizations)==1) {
+        } elseif (count($this->organizations) == 1) {
             // This will only get one title but so we don't need to know the index.
-            foreach($this->organizations as $id => $value) {
+            foreach ($this->organizations as $id => $value) {
                 $title = $this->organizations[$id]->get_name();
                 break;
             }
         }
+
         return $title;
     }
 
@@ -857,26 +1000,32 @@ class scorm extends learnpath {
      * // TODO @TODO Implement this function to restore items data from an imsmanifest,
      * updating the existing table... This will prove very useful in case initial data
      * from imsmanifest were not imported well enough
-     * @param	string	course Code
-     * @param string	LP ID (in database)
-     * @param string	Manifest file path (optional if lp_id defined)
-     * @return	integer	New LP ID or false on failure
+     * @param    string    course Code
+     * @param string    LP ID (in database)
+     * @param string    Manifest file path (optional if lp_id defined)
+     * @return    integer    New LP ID or false on failure
      * TODO @TODO Implement imsmanifest_path parameter
      */
-    function reimport_manifest($course, $lp_id = null, $imsmanifest_path = '') {
-        if ($this->debug > 0) { error_log('In scorm::reimport_manifest() method', 0); }
+    function reimport_manifest($course, $lp_id = null, $imsmanifest_path = '')
+    {
+        if ($this->debug > 0) {
+            error_log('In scorm::reimport_manifest() method', 0);
+        }
         global $_course;
         // RECOVERING PATH FROM DB
         $main_table = Database::get_main_table(TABLE_MAIN_COURSE);
         $course = Datbase::escape_string($course);
         $sql = "SELECT * FROM $main_table WHERE code = '$course'";
-        if ($this->debug > 2) { error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying course: '.$sql, 0); }
+        if ($this->debug > 2) {
+            error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying course: '.$sql, 0);
+        }
         //$res = Database::query($sql);
         $res = Database::query($sql);
         if (Database::num_rows($res) > 0) {
             $this->cc = $course;
         } else {
             $this->error = 'Course code does not exist in database ('.$sql.')';
+
             return false;
         }
 
@@ -886,7 +1035,9 @@ class scorm extends learnpath {
         $lp_table = Database::get_course_table(TABLE_LP_MAIN);
         $lp_id = intval($lp_id);
         $sql = "SELECT * FROM $lp_table WHERE c_id = ".$course_id." AND id = '$lp_id'";
-        if ($this->debug > 2) { error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying lp: '.$sql, 0); }
+        if ($this->debug > 2) {
+            error_log('New LP - scorm::reimport_manifest() '.__LINE__.' - Querying lp: '.$sql, 0);
+        }
         $res = Database::query($sql);
         if (Database::num_rows($res) > 0) {
             $this->lp_id = $lp_id;
@@ -917,14 +1068,24 @@ class scorm extends learnpath {
         echo $manifest_file;
         if (is_file($manifest_file) && is_readable($manifest_file)) {
             // Re-parse the manifest file.
-            if ($this->debug > 1) { error_log('New LP - In scorm::reimport_manifest() - Parsing manifest '.$manifest_file, 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - In scorm::reimport_manifest() - Parsing manifest '.$manifest_file, 0);
+            }
             $manifest = $this->parse_manifest($manifest_file);
             // Import new LP in DB (ignore the current one).
-            if ($this->debug > 1) { error_log('New LP - In scorm::reimport_manifest() - Importing manifest '.$manifest_file, 0); }
+            if ($this->debug > 1) {
+                error_log('New LP - In scorm::reimport_manifest() - Importing manifest '.$manifest_file, 0);
+            }
             $this->import_manifest(api_get_course_id());
         } else {
-            if ($this->debug > 0) { error_log('New LP - In scorm::reimport_manifest() - Could not find manifest file at '.$manifest_file, 0); }
+            if ($this->debug > 0) {
+                error_log(
+                    'New LP - In scorm::reimport_manifest() - Could not find manifest file at '.$manifest_file,
+                    0
+                );
+            }
         }
+
         return false;
     }
 }

Fișier diff suprimat deoarece este prea mare
+ 1708 - 1328
main/resourcelinker/resourcelinker.inc.php


Fișier diff suprimat deoarece este prea mare
+ 480 - 477
main/resourcelinker/resourcelinker.php


+ 11 - 11
main/social/friends.php

@@ -12,8 +12,6 @@ $language_file = array('userInfo');
 $cidReset = true;
 require_once '../inc/global.inc.php';
 require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 
 api_block_anonymous_users();
 if (api_get_setting('allow_social_tool') != 'true') {
@@ -114,28 +112,30 @@ if (count($friends) == 0) {
     $number_friends = count($friends);
     $j = 0;
 
-    $friend_html.= '<ul class="thumbnails">';
+    $friend_html .= '<ul class="thumbnails">';
     for ($k = 0; $k < $number_friends; $k++) {
         while ($j < $number_friends) {
 
             if (isset($friends[$j])) {
-                $friend_html.='<li class="span2">';
+                $friend_html .= '<li class="span2">';
                 $friend = $friends[$j];
                 $user_name = api_xml_http_response_encode($friend['firstName'].' '.$friend['lastName']);
                 $friends_profile = SocialManager::get_picture_user($friend['friend_user_id'], $friend['image'], 92);
-                $friend_html.='<div class="thumbnail" onMouseover="show_icon_delete(this)" onMouseout="hide_icon_delete(this)" class="image-social-content" id=div_'.$friends[$j]['friend_user_id'].'>';
-                $friend_html.='<img src="'.$friends_profile['file'].'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$user_name.'" />                                    ';
-                $friend_html.='<div class="caption">
+                $friend_html .= '<div class="thumbnail" onMouseover="show_icon_delete(this)" onMouseout="hide_icon_delete(this)" class="image-social-content" id=div_'.$friends[$j]['friend_user_id'].'>';
+                $friend_html .= '<img src="'.$friends_profile['file'].'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$user_name.'" />                                    ';
+                $friend_html .= '<div class="caption">
                                <a href="profile.php?u='.$friend['friend_user_id'].'"> <h5>'.$user_name.'</h5></a>';
-                $friend_html.='<p><button onclick="delete_friend(this)" id=img_'.$friend['friend_user_id'].'  />'.get_lang('Delete').'</button></p>
+                $friend_html .= '<p><button onclick="delete_friend(this)" id=img_'.$friend['friend_user_id'].'  />'.get_lang(
+                    'Delete'
+                ).'</button></p>
                         </div>';
-                $friend_html.='</li>';
+                $friend_html .= '</li>';
             }
             $j++;
         }
     }
-    $friend_html.='</ul>';
-    $friend_html.='</div>';
+    $friend_html .= '</ul>';
+    $friend_html .= '</div>';
     $social_right_content .= $friend_html;
 }
 $social_right_content .= '</div>';

+ 56 - 43
main/social/group_edit.php

@@ -13,16 +13,12 @@ $cidReset = true;
 require_once '../inc/global.inc.php';
 
 api_block_anonymous_users();
-if (api_get_setting('allow_social_tool') !='true') {
+if (api_get_setting('allow_social_tool') != 'true') {
     api_not_allowed();
 }
 
 $this_section = SECTION_SOCIAL;
 
-$libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileManage.lib.php';
-require_once $libpath.'fileUpload.lib.php';
-
 $htmlHeadXtra[] = '<script>
 var textarea = "";
 var num_characters_permited = 255;
@@ -39,21 +35,21 @@ function textarea_maxlength(){
 $group_id = isset($_GET['id']) ? intval($_GET['id']) : intval($_POST['id']);
 $tool_name = get_lang('GroupEdit');
 
-$interbreadcrumb[] = array('url' => 'home.php','name' => get_lang('Social'));
-$interbreadcrumb[] = array('url' => 'groups.php','name' => get_lang('Groups'));
+$interbreadcrumb[] = array('url' => 'home.php', 'name' => get_lang('Social'));
+$interbreadcrumb[] = array('url' => 'groups.php', 'name' => get_lang('Groups'));
 
 $table_group = Database::get_main_table(TABLE_MAIN_GROUP);
 
 $sql = "SELECT * FROM $table_group WHERE id = '".$group_id."'";
 $res = Database::query($sql);
 if (Database::num_rows($res) != 1) {
-	header('Location: groups.php?id='.$group_id);
-	exit;
+    header('Location: groups.php?id='.$group_id);
+    exit;
 }
 
 //only group admins can edit the group
 if (!GroupPortalManager::is_group_admin($group_id)) {
-	api_not_allowed();
+    api_not_allowed();
 }
 
 $group_data = Database::fetch_array($res, 'ASSOC');
@@ -63,34 +59,44 @@ $form = new FormValidator('group_edit', 'post', '', '');
 $form->addElement('hidden', 'id', $group_id);
 
 // name
-$form->addElement('text', 'name', get_lang('Name'), array('class'=>'span5', 'maxlength'=>120));
+$form->addElement('text', 'name', get_lang('Name'), array('class' => 'span5', 'maxlength' => 120));
 $form->applyFilter('name', 'html_filter');
 $form->applyFilter('name', 'trim');
 $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
 
 // Description
-$form->addElement('textarea', 'description', get_lang('Description'), array('class'=>'span5', 'cols'=>58, 'onKeyDown' => "textarea_maxlength()", 'onKeyUp' => "textarea_maxlength()"));
+$form->addElement(
+    'textarea',
+    'description',
+    get_lang('Description'),
+    array('class' => 'span5', 'cols' => 58, 'onKeyDown' => "textarea_maxlength()", 'onKeyUp' => "textarea_maxlength()")
+);
 $form->applyFilter('description', 'html_filter');
 $form->applyFilter('description', 'trim');
-$form->addRule('name', '', 'maxlength',255);
+$form->addRule('name', '', 'maxlength', 255);
 
 // url
-$form->addElement('text', 'url', get_lang('URL'), array('class'=>'span5'));
+$form->addElement('text', 'url', get_lang('URL'), array('class' => 'span5'));
 $form->applyFilter('url', 'html_filter');
 $form->applyFilter('url', 'trim');
 
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
-$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
+$allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
+$form->addRule(
+    'picture',
+    get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
+    'filetype',
+    $allowed_picture_types
+);
 if (strlen($group_data['picture_uri']) > 0) {
-	$form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
+    $form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
 }
 
 // Status
 $status = array();
-$status[GROUP_PERMISSION_OPEN] 		= get_lang('Open');
-$status[GROUP_PERMISSION_CLOSED]	= get_lang('Closed');
+$status[GROUP_PERMISSION_OPEN] = get_lang('Open');
+$status[GROUP_PERMISSION_CLOSED] = get_lang('Closed');
 $form->addElement('select', 'visibility', get_lang('GroupPermissions'), $status, array());
 
 
@@ -101,32 +107,39 @@ $form->addElement('style_submit_button', 'submit', get_lang('ModifyInformation')
 $form->setDefaults($group_data);
 
 // Validate form
-if ( $form->validate()) {
-	$group = $form->exportValues();
-	$picture_element = $form->getElement('picture');
-	$picture = $picture_element->getValue();
-	$picture_uri = $group_data['picture_uri'];
-
-	if ($group['delete_picture']) {
-		$picture_uri = GroupPortalManager::delete_group_picture($group_id);
-		}
-	elseif (!empty($picture['name'])) {
-		$picture_uri = GroupPortalManager::update_group_picture($group_id, $_FILES['picture']['name'], $_FILES['picture']['tmp_name']);
-	}
-
-	$name 			= $group['name'];
-	$description	= $group['description'];
-	$url 			= $group['url'];
-	$status 		= intval($group['visibility']);
-
-	GroupPortalManager::update($group_id, $name, $description, $url, $status, $picture_uri);
-	$tok = Security::get_token();
-	header('Location: groups.php?id='.$group_id.'&action=show_message&message='.urlencode(get_lang('GroupUpdated')).'&sec_token='.$tok);
-	exit();
+if ($form->validate()) {
+    $group = $form->exportValues();
+    $picture_element = $form->getElement('picture');
+    $picture = $picture_element->getValue();
+    $picture_uri = $group_data['picture_uri'];
+
+    if ($group['delete_picture']) {
+        $picture_uri = GroupPortalManager::delete_group_picture($group_id);
+    } elseif (!empty($picture['name'])) {
+        $picture_uri = GroupPortalManager::update_group_picture(
+            $group_id,
+            $_FILES['picture']['name'],
+            $_FILES['picture']['tmp_name']
+        );
+    }
+
+    $name = $group['name'];
+    $description = $group['description'];
+    $url = $group['url'];
+    $status = intval($group['visibility']);
+
+    GroupPortalManager::update($group_id, $name, $description, $url, $status, $picture_uri);
+    $tok = Security::get_token();
+    header(
+        'Location: groups.php?id='.$group_id.'&action=show_message&message='.urlencode(
+            get_lang('GroupUpdated')
+        ).'&sec_token='.$tok
+    );
+    exit();
 }
 
 // Group picture
-$image_path = GroupPortalManager::get_group_picture_path_by_id($group_id,'web');
+$image_path = GroupPortalManager::get_group_picture_path_by_id($group_id, 'web');
 $image_dir = $image_path['dir'];
 $image = $image_path['file'];
 $image_file = ($image != '' ? $image_dir.$image : api_get_path(WEB_CODE_PATH).'img/unknown_group.jpg');
@@ -139,7 +152,7 @@ $big_image_width = $big_image_size['width'];
 $big_image_height = $big_image_size['height'];
 $url_big_image = $big_image.'?rnd='.time();
 
-$social_left_content = SocialManager::show_social_menu('group_edit',$group_id);
+$social_left_content = SocialManager::show_social_menu('group_edit', $group_id);
 $social_right_content = '<div class="span9">';
 $social_right_content .= $form->return_form();
 $social_right_content .= '</div>';

+ 107 - 26
main/survey/create_new_survey.php

@@ -3,13 +3,13 @@
 /* For licensing terms, see /license.txt */
 
 /**
- * 	@package chamilo.survey
- * 	@author unknown, the initial survey that did not make it in 1.8 because of bad code
- * 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts (if not all) of the code
- * 	@author Julio Montoya Armas <gugli100@gmail.com>, Chamilo: Personality Test modification and rewriting large parts of the code
- * 	@version $Id: create_new_survey.php 22297 2009-07-22 22:08:30Z cfasanando $
+ * @package chamilo.survey
+ * @author unknown, the initial survey that did not make it in 1.8 because of bad code
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts (if not all) of the code
+ * @author Julio Montoya Armas <gugli100@gmail.com>, Chamilo: Personality Test modification and rewriting large parts of the code
+ * @version $Id: create_new_survey.php 22297 2009-07-22 22:08:30Z cfasanando $
  *
- * 	@todo only the available platform languages should be used => need an api get_languages and and api_get_available_languages (or a parameter)
+ * @todo only the available platform languages should be used => need an api get_languages and and api_get_available_languages (or a parameter)
  */
 // Language file that needs to be included
 $language_file = 'survey';
@@ -24,17 +24,24 @@ $this_section = SECTION_COURSES;
 /** @todo check if the starting / is needed. api_get_path probably ends with an / */
 //require_once api_get_path(LIBRARY_PATH).'survey.lib.php';
 require_once 'survey.lib.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
 
 $htmlHeadXtra[] = '<script>
     function advanced_parameters() {
         if(document.getElementById(\'options\').style.display == \'none\') {
                 document.getElementById(\'options\').style.display = \'block\';
-                document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif', get_lang('Hide'), array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+                document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon(
+    'div_hide.gif',
+    get_lang('Hide'),
+    array('style' => 'vertical-align:middle')
+).'&nbsp;'.get_lang('AdvancedParameters').'\';
         } else {
                 document.getElementById(\'options\').style.display = \'none\';
-                document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif', get_lang('Show'), array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+                document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon(
+    'div_show.gif',
+    get_lang('Show'),
+    array('style' => 'vertical-align:middle')
+).'&nbsp;'.get_lang('AdvancedParameters').'\';
         }
     }
 
@@ -55,7 +62,11 @@ $table_gradebook_link = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 /** @todo this has to be moved to a more appropriate place (after the display_header of the code) */
 // If user is not teacher or if he's a coach trying to access an element out of his session
 if (!api_is_allowed_to_edit()) {
-    if (!api_is_course_coach() || (!empty($_GET['survey_id']) && !api_is_element_in_the_session(TOOL_SURVEY, intval($_GET['survey_id'])))) {
+    if (!api_is_course_coach() || (!empty($_GET['survey_id']) && !api_is_element_in_the_session(
+        TOOL_SURVEY,
+        intval($_GET['survey_id'])
+    ))
+    ) {
         api_not_allowed(true);
         exit;
     }
@@ -93,7 +104,10 @@ if ($_GET['action'] == 'edit' && isset($survey_id) && is_numeric($survey_id)) {
     $gradebook_link_id = $link_info['id'];
 
     if ($link_info) {
-        if ($sql_result_array = Database::fetch_array(Database::query('SELECT weight FROM '.$table_gradebook_link.' WHERE id='.$gradebook_link_id))) {
+        if ($sql_result_array = Database::fetch_array(
+            Database::query('SELECT weight FROM '.$table_gradebook_link.' WHERE id='.$gradebook_link_id)
+        )
+        ) {
             $defaults['survey_qualify_gradebook'] = $gradebook_link_id;
             $defaults['survey_weight'] = number_format($sql_result_array['weight'], 2, '.', '');
         }
@@ -107,7 +121,9 @@ if ($_GET['action'] == 'edit' && isset($survey_id) && is_numeric($survey_id)) {
 }
 
 // Initialize the object
-$form = new FormValidator('survey', 'post', api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$survey_id);
+$form = new FormValidator('survey', 'post', api_get_self().'?action='.Security::remove_XSS(
+    $_GET['action']
+).'&survey_id='.$survey_id);
 
 $form->addElement('header', '', $tool_name);
 
@@ -116,30 +132,77 @@ if ($_GET['action'] == 'edit' && isset($survey_id) && is_numeric($survey_id)) {
     $form->addElement('hidden', 'survey_id');
 }
 
-$survey_code = $form->addElement('text', 'survey_code', get_lang('SurveyCode'), array('size' => '20', 'maxlength' => '20', 'id' => 'surveycode_title'));
-
-$form->addElement('html_editor', 'survey_title', get_lang('SurveyTitle'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '200'));
-$form->addElement('html_editor', 'survey_subtitle', get_lang('SurveySubTitle'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '100', 'ToolbarStartExpanded' => false));
+$survey_code = $form->addElement(
+    'text',
+    'survey_code',
+    get_lang('SurveyCode'),
+    array('size' => '20', 'maxlength' => '20', 'id' => 'surveycode_title')
+);
+
+$form->addElement(
+    'html_editor',
+    'survey_title',
+    get_lang('SurveyTitle'),
+    null,
+    array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '200')
+);
+$form->addElement(
+    'html_editor',
+    'survey_subtitle',
+    get_lang('SurveySubTitle'),
+    null,
+    array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '100', 'ToolbarStartExpanded' => false)
+);
 
 // Pass the language of the survey in the form
 $form->addElement('hidden', 'survey_language');
 $form->addElement('datepickerdate', 'start_date', get_lang('StartDate'), array('form_name' => 'survey'));
 $form->addElement('datepickerdate', 'end_date', get_lang('EndDate'), array('form_name' => 'survey'));
 $form->addElement('checkbox', 'anonymous', null, get_lang('Anonymous'));
-$form->addElement('html_editor', 'survey_introduction', get_lang('SurveyIntroduction'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
-$form->addElement('html_editor', 'survey_thanks', get_lang('SurveyThanks'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
+$form->addElement(
+    'html_editor',
+    'survey_introduction',
+    get_lang('SurveyIntroduction'),
+    null,
+    array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false)
+);
+$form->addElement(
+    'html_editor',
+    'survey_thanks',
+    get_lang('SurveyThanks'),
+    null,
+    array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false)
+);
 
 // Aditional Parameters
-$form->addElement('advanced_settings', '<a href="javascript: void(0);" onclick="javascript: advanced_parameters();" >
-        <span id="plus_minus">&nbsp;'.Display::return_icon('div_show.gif', null, array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'</span></a>');
+$form->addElement(
+    'advanced_settings',
+    '<a href="javascript: void(0);" onclick="javascript: advanced_parameters();" >
+        <span id="plus_minus">&nbsp;'.Display::return_icon(
+        'div_show.gif',
+        null,
+        array('style' => 'vertical-align:middle')
+    ).'&nbsp;'.get_lang('AdvancedParameters').'</span></a>'
+);
 
 $form->addElement('html', '<div id="options" style="display: none;">');
 
 if (Gradebook::is_active()) {
     // An option: Qualify the fact that survey has been answered in the gradebook
-    $form->addElement('checkbox', 'survey_qualify_gradebook', null, get_lang('QualifyInGradebook'), 'onclick="javascript: if (this.checked) { document.getElementById(\'gradebook_options\').style.display = \'block\'; } else { document.getElementById(\'gradebook_options\').style.display = \'none\'; }"');
+    $form->addElement(
+        'checkbox',
+        'survey_qualify_gradebook',
+        null,
+        get_lang('QualifyInGradebook'),
+        'onclick="javascript: if (this.checked) { document.getElementById(\'gradebook_options\').style.display = \'block\'; } else { document.getElementById(\'gradebook_options\').style.display = \'none\'; }"'
+    );
     $form->addElement('html', '<div id="gradebook_options"'.($gradebook_link_id ? '' : ' style="display:none"').'>');
-    $form->addElement('text', 'survey_weight', get_lang('QualifyWeight'), 'value="0.00" style="width: 40px;" onfocus="javascript: this.select();"');
+    $form->addElement(
+        'text',
+        'survey_weight',
+        get_lang('QualifyWeight'),
+        'value="0.00" style="width: 40px;" onfocus="javascript: this.select();"'
+    );
     $form->applyFilter('survey_weight', 'html_filter');
     $form->addElement('html', '</div>');
 }
@@ -166,7 +229,13 @@ if ($survey_data['survey_type'] == 1 || $_GET['action'] == 'add') {
 if ((isset($_GET['action']) && $_GET['action'] == 'edit') && !empty($survey_id)) {
     if ($survey_data['anonymous'] == 0) {
 
-        $form->addElement('checkbox', 'show_form_profile', null, get_lang('ShowFormProfile'), 'onclick="javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"');
+        $form->addElement(
+            'checkbox',
+            'show_form_profile',
+            null,
+            get_lang('ShowFormProfile'),
+            'onclick="javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"'
+        );
 
         if ($survey_data['show_form_profile'] == 1) {
             $form->addElement('html', '<div id="options_field" style="display:block">');
@@ -180,7 +249,7 @@ if ((isset($_GET['action']) && $_GET['action'] == 'edit') && !empty($survey_id))
             foreach ($field_list as $key => & $field) {
                 if ($field['visibility'] == 1) {
                     $form->addElement('checkbox', 'profile_'.$key, ' ', '&nbsp;&nbsp;'.$field['name']);
-                    $input_name_list.= 'profile_'.$key.',';
+                    $input_name_list .= 'profile_'.$key.',';
                 }
             }
             // Necesary to know the fields
@@ -256,9 +325,21 @@ if ($form->validate()) {
                 $link_info = is_resource_in_course_gradebook($course_id, $gradebook_link_type, $survey_id, $session_id);
                 $gradebook_link_id = $link_info['id'];
                 if (!$gradebook_link_id) {
-                    add_resource_to_course_gradebook($course_id, $gradebook_link_type, $survey_id, $title_gradebook, $survey_weight, $max_score, $description_gradebook, 1, $session_id);
+                    add_resource_to_course_gradebook(
+                        $course_id,
+                        $gradebook_link_type,
+                        $survey_id,
+                        $title_gradebook,
+                        $survey_weight,
+                        $max_score,
+                        $description_gradebook,
+                        1,
+                        $session_id
+                    );
                 } else {
-                    Database::query('UPDATE '.$table_gradebook_link.' SET weight='.$survey_weight.' WHERE id='.$gradebook_link_id);
+                    Database::query(
+                        'UPDATE '.$table_gradebook_link.' SET weight='.$survey_weight.' WHERE id='.$gradebook_link_id
+                    );
                 }
             }
         }

+ 44 - 52
main/upload/index.php

@@ -2,22 +2,22 @@
 /* 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 : - upload a file
-*
-* The script respects the strategical split between process and display, so the first
-* part is only processing code (init, process, display preparation) and the second
-* part is only display (HTML)
-*
-* @package chamilo.upload
-*/
+ * Main script for the documents tool
+ *
+ * This script allows the user to manage files and directories on a remote http server.
+ *
+ * The user can : - upload a file
+ *
+ * The script respects the strategical split between process and display, so the first
+ * part is only processing code (init, process, display preparation) and the second
+ * part is only display (HTML)
+ *
+ * @package chamilo.upload
+ */
 
 /**
  * INIT SECTION
-*/
+ */
 
 // name of the language file that needs to be included
 $language_file[] = "document";
@@ -30,7 +30,7 @@ $language_file[] = "learnpath";
 require_once '../inc/global.inc.php';
 
 $htmlHeadXtra[] =
-"<script type=\"text/javascript\">
+    "<script type=\"text/javascript\">
 <!-- //
 function check_unzip() {
 	if(document.upload.unzip.checked){
@@ -49,46 +49,38 @@ function check_unzip() {
 
 
 //$is_allowed_to_edit = api_is_allowed_to_edit();
-$is_allowed_to_edit = api_is_allowed_to_edit(null,true);
-if(!$is_allowed_to_edit){
-	api_not_allowed(true);
+$is_allowed_to_edit = api_is_allowed_to_edit(null, true);
+if (!$is_allowed_to_edit) {
+    api_not_allowed(true);
 }
 
-
-/*
-	Libraries
-*/
-
-//many useful functions in main_api.lib.php, by default included
-
-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).'document.lib.php');
 
 /*
 	Variables
 	- some need defining before inclusion of libraries
 */
-$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;
 $max_filled_space = DocumentManager::get_course_quota();
 
 //what's the current path?
-if(isset($_REQUEST['curdirpath'])) {
-	$path = $_REQUEST['curdirpath'];
-}else{
-	$path = '/';
+if (isset($_REQUEST['curdirpath'])) {
+    $path = $_REQUEST['curdirpath'];
+} else {
+    $path = '/';
 }
 // set calling tool
-if(isset($_REQUEST['tool'])) {
-	$my_tool = $_REQUEST['tool'];
-	$_SESSION['my_tool'] = $_REQUEST['tool'];
-}elseif(!empty($_SESSION['my_tool'])){
-	$my_tool = $_SESSION['my_tool'];
-}else{
-	$my_tool = 'document';
-	$_SESSION['my_tool'] = $my_tool;
+if (isset($_REQUEST['tool'])) {
+    $my_tool = $_REQUEST['tool'];
+    $_SESSION['my_tool'] = $_REQUEST['tool'];
+} elseif (!empty($_SESSION['my_tool'])) {
+    $my_tool = $_SESSION['my_tool'];
+} else {
+    $my_tool = 'document';
+    $_SESSION['my_tool'] = $my_tool;
 }
 
 // Check the path
@@ -103,7 +95,7 @@ if(isset($_REQUEST['tool'])) {
 event_access_tool(TOOL_UPLOAD);
 
 /**
- *	Prepare the header
+ *    Prepare the header
  */
 
 $htmlHeadXtra[] = '<script language="javascript" src="../inc/lib/javascript/upload.js" type="text/javascript"></script>';
@@ -114,15 +106,15 @@ $htmlHeadXtra[] = '<script type="text/javascript">
 /**
  * Now call the corresponding display script, the current script acting like a controller.
  */
-switch($my_tool){
-	case TOOL_LEARNPATH:
-		require('form.scorm.php');
-		break;
-	//the following cases need to be distinguished later on
-	case TOOL_DROPBOX:
-	case TOOL_STUDENTPUBLICATION:
-	case TOOL_DOCUMENT:
-	default:
-		require('form.document.php');
-		break;
+switch ($my_tool) {
+    case TOOL_LEARNPATH:
+        require('form.scorm.php');
+        break;
+    //the following cases need to be distinguished later on
+    case TOOL_DROPBOX:
+    case TOOL_STUDENTPUBLICATION:
+    case TOOL_DOCUMENT:
+    default:
+        require('form.document.php');
+        break;
 }

Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff