Browse Source

Merge branch '1.9.x' of ssh://github.com/chamilo/chamilo-lms into chamilo19

Julio Montoya 10 years ago
parent
commit
c011d01eed
100 changed files with 5993 additions and 4800 deletions
  1. 9 2
      documentation/changelog.html
  2. 30 26
      main/admin/configure_homepage.php
  3. 10 2
      main/admin/course_information.php
  4. 1 0
      main/admin/index.php
  5. 6 0
      main/admin/user_import.php
  6. 492 0
      main/admin/user_update_import.php
  7. 27 27
      main/auth/inscription.php
  8. 4 1
      main/auth/profile.php
  9. 4 0
      main/course_progress/thematic.php
  10. 6 0
      main/course_progress/thematic_controller.php
  11. 1 1
      main/course_progress/thematic_plan.php
  12. 1 1
      main/document/document_slideshow.inc.php
  13. 412 387
      main/dropbox/dropbox_functions.inc.php
  14. 9 4
      main/exercice/exercise_result.class.php
  15. 1 0
      main/exercice/global_multiple_answer.class.php
  16. 22 12
      main/exercice/hotspot_admin.inc.php
  17. 1 0
      main/exercice/multiple_answer.class.php
  18. 1 0
      main/exercice/multiple_answer_combination.class.php
  19. 1 0
      main/exercice/question.class.php
  20. 4 3
      main/exercice/question_admin.inc.php
  21. 3 3
      main/exercice/unique_answer_no_option.class.php
  22. 87 94
      main/forum/forumfunction.inc.php
  23. BIN
      main/img/icons/22/view_remove_na.png
  24. BIN
      main/img/icons/22/view_tree_na.png
  25. 36 14
      main/inc/ajax/skill.ajax.php
  26. 14 7
      main/inc/ajax/user_manager.ajax.php
  27. 147 138
      main/inc/lib/add_course.lib.inc.php
  28. 23 7
      main/inc/lib/course.lib.php
  29. 27 11
      main/inc/lib/course_category.lib.php
  30. 65 15
      main/inc/lib/course_request.lib.php
  31. 164 164
      main/inc/lib/database.lib.php
  32. 67 69
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_create_folder.php
  33. 4 0
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_delete_file.php
  34. 4 1
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_copy.php
  35. 3 1
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_cut.php
  36. 2 0
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_paste.php
  37. 4 2
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_upload.php
  38. 2 1
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_get_file_listing.php
  39. 2 0
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_save_name.php
  40. 1 1
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/class.manager.php
  41. 651 459
      main/inc/lib/link.lib.php
  42. 41 23
      main/inc/lib/mail.lib.inc.php
  43. 252 239
      main/inc/lib/main_api.lib.php
  44. 33 21
      main/inc/lib/notification.lib.php
  45. 33 1
      main/inc/lib/skill.lib.php
  46. 17 2
      main/inc/lib/social.lib.php
  47. 8 7
      main/inc/lib/thematic.lib.php
  48. 14 5
      main/inc/lib/usermanager.lib.php
  49. 3 3
      main/inc/lib/userportal.lib.php
  50. 2 0
      main/install/configuration.dist.php
  51. 419 374
      main/link/link.php
  52. 1770 1770
      main/mySpace/myspace.lib.php
  53. 20 20
      main/newscorm/openoffice_document.class.php
  54. 15 3
      main/social/profile.php
  55. 11 5
      main/template/default/skill/skill_wheel.js.tpl
  56. 37 20
      main/template/default/skill/skill_wheel.tpl
  57. 22 14
      main/user/user_add.php
  58. 121 0
      main/webservices/additional_webservices.php
  59. 160 0
      main/webservices/registration.soap.php
  60. 359 359
      main/work/work.lib.php
  61. 8 4
      plugin/clockworksms/config.php
  62. 0 2
      plugin/clockworksms/index.php
  63. 6 3
      plugin/clockworksms/install.php
  64. 87 87
      plugin/clockworksms/lang/english.php
  65. 87 87
      plugin/clockworksms/lang/spanish.php
  66. 49 13
      plugin/clockworksms/lib/clockworksms.lib.php
  67. 33 2
      plugin/clockworksms/lib/clockworksms_plugin.class.php
  68. 5 0
      plugin/clockworksms/plugin.php
  69. 2 252
      plugin/clockworksms/readme.txt
  70. 1 1
      plugin/clockworksms/sms_templates/account_approved_connect.tpl
  71. 1 1
      plugin/clockworksms/sms_templates/account_created_updated_login_password.tpl
  72. 1 1
      plugin/clockworksms/sms_templates/answer_open_question_test_reviewed.tpl
  73. 1 1
      plugin/clockworksms/sms_templates/assignment_been_created_course.tpl
  74. 1 1
      plugin/clockworksms/sms_templates/been_invited_complete_survey_course.tpl
  75. 1 1
      plugin/clockworksms/sms_templates/been_invited_join_group.tpl
  76. 1 1
      plugin/clockworksms/sms_templates/been_subscribed_course.tpl
  77. 1 1
      plugin/clockworksms/sms_templates/check_email_connect_more_info.tpl
  78. 1 1
      plugin/clockworksms/sms_templates/course_opening_request_code_registered.tpl
  79. 1 1
      plugin/clockworksms/sms_templates/course_opening_request_course_code.tpl
  80. 1 1
      plugin/clockworksms/sms_templates/course_opening_request_course_code_approved.tpl
  81. 1 1
      plugin/clockworksms/sms_templates/messages_sent_edited_group_added.tpl
  82. 1 1
      plugin/clockworksms/sms_templates/messages_sent_edited_group_edited.tpl
  83. 1 1
      plugin/clockworksms/sms_templates/new_answer_posted_forum.tpl
  84. 1 1
      plugin/clockworksms/sms_templates/new_course_been_created.tpl
  85. 1 1
      plugin/clockworksms/sms_templates/new_course_suggested_teacher.tpl
  86. 1 1
      plugin/clockworksms/sms_templates/new_file_shared_course_by.tpl
  87. 1 1
      plugin/clockworksms/sms_templates/new_system_announcement_added.tpl
  88. 1 1
      plugin/clockworksms/sms_templates/new_thread_started_forum.tpl
  89. 1 1
      plugin/clockworksms/sms_templates/new_user_pending_approval.tpl
  90. 1 1
      plugin/clockworksms/sms_templates/new_user_subscribed_course.tpl
  91. 1 1
      plugin/clockworksms/sms_templates/password_updated_login_password.tpl
  92. 1 1
      plugin/clockworksms/sms_templates/posted_forum_course.tpl
  93. 1 1
      plugin/clockworksms/sms_templates/received_new_personal_messages.tpl
  94. 1 1
      plugin/clockworksms/sms_templates/reminder_assignment_course_due.tpl
  95. 1 1
      plugin/clockworksms/sms_templates/request_open_course_code_rejected.tpl
  96. 1 1
      plugin/clockworksms/sms_templates/requested_password_change.tpl
  97. 1 1
      plugin/clockworksms/sms_templates/student_answered_test.tpl
  98. 1 1
      plugin/clockworksms/sms_templates/student_answered_test_open_question.tpl
  99. 1 1
      plugin/clockworksms/sms_templates/student_answered_test_voice_question.tpl
  100. 1 1
      plugin/clockworksms/sms_templates/subscribed_session.tpl

+ 9 - 2
documentation/changelog.html

@@ -44,12 +44,19 @@
 <p><i>Note: most #wxyz references are issue numbers you can find in <a href="http://support.chamilo.org/projects/chamilo-18/issues" target="_blank">our public bug tracking system</a>. Some references marked BT#xyz are developments made externally for BeezNest customers and integrated into Chamilo. The details of these tasks cannot be seen for confidentiality reasons, but the code change is public and can be reviewed by anyone.</i></p>
 <p>&nbsp;</p>
 
-<h1>Chamilo 1.9.8.3 - 21st of July, 2014</h1>
+<h1>Chamilo 1.9.10 - 30th of October, 2014</h1>
 <h3>Release notes - summary</h3>
-<p>Chamilo 1.9.8.3 is a small patch version with a few minor bugfixes and a new packaging. This will be packaged and promoted as 1.9.8, but the folder inside the 1.9.8 will be called 1.9.8.3, with a few changes to this changelog file and a few fixes throughout the code (as such, you can just overwrite previous files to upgrade from 1.9.8, 1.9.8.1 or 1.9.8.2 to 1.9.8.3).</p>
+<p>Chamilo 1.9.10 is a patch version with a few minor bugfixes and a new packaging. This will be packaged and promoted as 1.9.8, but the folder inside the 1.9.8 will be called 1.9.10, with a few changes to this changelog file and a few fixes throughout the code (as such, you can just overwrite previous files to upgrade from 1.9.8, 1.9.8.1 or 1.9.8.2 to 1.9.10).</p>
 <h3>Release name</h3>
 <p><a href="http://es.wikipedia.org/wiki/Departamento_de_Huánuco">Huánuco</a> is a small city in the Peruvian Andes, Northeast of Lima. This is a special version in memory of our cherished development team member César Perales, who passed away on July 22nd, 2014, at age 27. César contributed mostly "in the shadow" to Chamilo LMS, allowing the rest of the team to contribute more actively. He was a vibrant young man. He will be missed. César lived in calle Huánuco, in La Molina, Lima, Peru, where other team members bid him their last farewell for his last, eternal trip.</p>
 
+<h3>Possibly breaking changes</h3>
+<p>Two changes have been made to the forum tool code, which might make some of your forums disappear and require a direct database intervention.<br />
+First case: If you use forums with sessions and have placed a session forum inside a base-course forum category, the forum category will now no longer appear in any session, and as such, the session forums contained in that category will disappear. You can easily fix that by checking the c_forum_forum table for any record with session_id != 0 that points to a forum category that has session_id == 0. This is related to issue #7264.<br />
+Second case: if you use group forums and have had issues with posts appearing twice, then this release will fix this bug, but might also make some forum posts disappear. Although we could not reproduce the error, you should be able to fix it by changing the group_id column inside the c_forum_thread table. This is related to issue #7267<br />
+This is an exceptional event in the history of Chamilo, and we believe it should only affect very few portals, but we prefer to take precautionnary measures and warn you upfront.<br />
+</p>
+
 <h3>New Features</h3>
 <ul>
   <li>(eadeaf8 - BT#8317) Add sessions duration feature</li>

+ 30 - 26
main/admin/configure_homepage.php

@@ -15,30 +15,33 @@
  */
 function home_tabs($file_logged_in)
 {
-	$file_logged_out = str_replace('_logged_in','', $file_logged_in);
-
-	//variables initialization
-	$data_logged_out = array();
-	$data_logged_in  = array();
-
-	//we read the file with all links
-	$file = file($file_logged_in);
-	foreach ($file as $line) {
-		//not logged user only sees public links
-		if (!preg_match('/::private/',$line)) {
-			$data_logged_out[] = $line;
-		}
-		//logged user only sees all links
-		$data_logged_in[] = $line;
-	}
-	//tabs file for logged out users
-	$fp = fopen($file_logged_out, 'w');
-	fputs($fp, implode("\n", $data_logged_out));
-	fclose($fp);
-	//tabs file for logged in users
-	$fp = fopen($file_logged_in, 'w');
-	fputs($fp, implode("\n", $data_logged_in));
-	fclose($fp);
+    $post = strpos($file_logged_in, "_logged_in");
+    if ($post !== false) {
+        $file_logged_out = str_replace('_logged_in','', $file_logged_in);
+        //variables initialization
+        $data_logged_out = array();
+        $data_logged_in  = array();
+
+        //we read the file with all links
+        $file = file($file_logged_in);
+        foreach ($file as $line) {
+            $line = str_replace("\n", '',$line);
+            //not logged user only sees public links
+            if (!preg_match('/::private/',$line)) {
+                $data_logged_out[] = $line;
+            }
+            //logged user only sees all links
+            $data_logged_in[] = $line;
+        }
+        //tabs file for logged out users
+        $fp = fopen($file_logged_out, 'w');
+        fputs($fp, implode("\n", $data_logged_out));
+        fclose($fp);
+        //tabs file for logged in users
+        $fp = fopen($file_logged_in, 'w');
+        fputs($fp, implode("\n", $data_logged_in));
+        fclose($fp);
+    }
 }
 
 $language_file = array('index','admin', 'accessibility');
@@ -830,8 +833,9 @@ switch ($action) {
         $default['link_name'] = $link_name;
     	}
 		$default['link_url'] = empty($link_url) ? 'http://' : api_htmlentities($link_url, ENT_QUOTES);
-		$form->addElement('text', 'link_url', array(get_lang('LinkURL'), get_lang('Optional').'<br />'.get_lang('GlobalLinkUseDoubleColumnPrivateToShowPrivately')), array('size' => '30', 'maxlength' => '100', 'style' => 'width: 350px;'));
-
+        $linkUrlComment = ($action == 'insert_tabs') ? get_lang('Optional').'<br />'.get_lang('GlobalLinkUseDoubleColumnPrivateToShowPrivately') : '';
+        $form->addElement('text', 'link_url', array(get_lang('LinkURL'), $linkUrlComment), array('size' => '30', 'maxlength' => '100', 'style' => 'width: 350px;'));
+        
         $options = array('-1' => get_lang('FirstPlace'));
 
 		$selected = '';

+ 10 - 2
main/admin/course_information.php

@@ -110,8 +110,16 @@ $table->display();
 echo Display::page_header(get_lang('Users'));
 $table_course_user     = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $table_user            = Database :: get_main_table(TABLE_MAIN_USER);
-$sql                   = "SELECT *,cu.status as course_status FROM $table_course_user cu, $table_user u WHERE cu.user_id = u.user_id AND cu.course_code = '".$code."' AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
-$res                   = Database::query($sql);
+$sql = "SELECT *,cu.status as course_status 
+        FROM $table_course_user cu, $table_user u";
+if (api_is_multiple_url_enabled()) {
+    $sql .= " INNER JOIN ".Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER)." url_rel_user
+        ON u.user_id = url_rel_user.user_id
+        AND url_rel_user.access_url_id = ".intval(api_get_current_access_url_id());
+}
+$sql .= " WHERE cu.user_id = u.user_id AND cu.course_code = '".$code."'
+        AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH;
+$res = Database::query($sql);
 $is_western_name_order = api_is_western_name_order();
 if (Database::num_rows($res) > 0) {
     $users = array();

+ 1 - 0
main/admin/index.php

@@ -74,6 +74,7 @@ if (api_is_platform_admin()) {
 		array('url'=>'user_add.php', 	'label' => get_lang('AddUsers')),
 		array('url'=>'user_export.php', 'label' => get_lang('ExportUserListXMLCSV')),
 		array('url'=>'user_import.php', 'label' => get_lang('ImportUserListXMLCSV')),
+               array('url'=>'user_update_import.php', 'label' => get_lang('EditUserListCSV')),
 	);
 
 	if (api_get_setting('allow_social_tool') == 'true') {

+ 6 - 0
main/admin/user_import.php

@@ -56,6 +56,12 @@ function validate_data($users, $checkUniqueEmail = false)
                 $user['error'] = get_lang('UserNameTooLong');
                 $errors[] = $user;
             }
+            // 2.1.1
+            $hasDash = strpos($username, '-');
+            if ($hasDash !== false) {
+                $user['error'] = get_lang('UserNameHasDash');
+                $errors[] = $user;
+            }
             // 2.2. Check whether the username was used twice in import file.
             if (isset($usernames[$user['UserName']])) {
                 $user['error'] = get_lang('UserNameUsedTwice');

+ 492 - 0
main/admin/user_update_import.php

@@ -0,0 +1,492 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * This tool allows platform admins to add users by uploading a CSV or XML file
+ * @package chamilo.admin
+ */
+
+/**
+ * Validate the imported data.
+ */
+
+$language_file = array ('admin', 'registration');
+
+$cidReset = true;
+require '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+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).'usergroup.lib.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+
+// Set this option to true to enforce strict purification for usenames.
+$purification_option_for_usernames = false;
+
+function validate_data($users)
+{
+    global $defined_auth_sources;
+    $errors = array();
+    $usernames = array();
+
+    // 1. Check if mandatory fields are set.
+    $mandatory_fields = array('LastName', 'FirstName');
+
+    if (api_get_setting('registration', 'email') == 'true') {
+        $mandatory_fields[] = 'Email';
+    }
+    $classExistList = array();
+    $usergroup = new UserGroup();
+
+    foreach ($users as $user) {
+        foreach ($mandatory_fields as $field) {
+            if (isset($user[$field])) {
+                if (empty($user[$field])) {
+                    $user['error'] = get_lang($field.'Mandatory');
+                    $errors[] = $user;
+                }
+            }
+        }
+
+        // 2. Check username, first, check whether it is empty.
+        
+        if (isset($user['NewUserName'])) {
+            if (!UserManager::is_username_empty($user['NewUserName'])) {
+                // 2.1. Check whether username is too long.
+                if (UserManager::is_username_too_long($user['NewUserName'])) {
+                    $user['error'] = get_lang('UserNameTooLong');
+                    $errors[] = $user;
+                }
+                // 2.2. Check whether the username was used twice in import file.
+                if (isset($usernames[$user['NewUserName']])) {
+                    $user['error'] = get_lang('UserNameUsedTwice');
+                    $errors[] = $user;
+                }
+                $usernames[$user['UserName']] = 1;
+                // 2.3. Check whether username is allready occupied.
+                if (!UserManager::is_username_available($user['NewUserName']) && $user['NewUserName'] != $user['UserName']) {
+                    $user['error'] = get_lang('UserNameNotAvailable');
+                    $errors[] = $user;
+                }
+             }
+          }
+          
+        // 3. Check status.
+        if (isset($user['Status']) && !api_status_exists($user['Status'])) {
+            $user['error'] = get_lang('WrongStatus');
+            $errors[] = $user;
+        }
+
+        // 4. Check ClassId
+        if (!empty($user['ClassId'])) {
+            $classId = explode('|', trim($user['ClassId']));
+            foreach ($classId as $id) {
+                if (in_array($id, $classExistList)) {
+                    continue;
+                }
+                $info = $usergroup->get($id);
+                if (empty($info)) {
+                    $user['error'] = sprintf(get_lang('ClassIdDoesntExists'), $id);
+                    $errors[] = $user;
+                } else {
+                    $classExistList[] = $info['id'];
+                }
+            }
+        }
+
+        // 5. Check authentication source
+        if (!empty($user['AuthSource'])) {
+            if (!in_array($user['AuthSource'], $defined_auth_sources)) {
+                $user['error'] = get_lang('AuthSourceNotAvailable');
+                $errors[] = $user;
+            }
+        }
+    }
+
+    return $errors;
+}
+
+/**
+ * Add missing user-information (which isn't required, like password, username etc).
+ */
+function complete_missing_data($user)
+{
+    global $purification_option_for_usernames;
+    // 1. Create a username if necessary.
+    if (UserManager::is_username_empty($user['UserName'])) {
+        $user['UserName'] = UserManager::create_unique_username($user['FirstName'], $user['LastName']);
+    } else {
+        $user['UserName'] = UserManager::purify_username($user['UserName'], $purification_option_for_usernames);
+    }
+    // 2. Generate a password if necessary.
+    if (empty($user['Password'])) {
+        $user['Password'] = api_generate_password();
+    }
+    // 3. Set status if not allready set.
+    if (empty($user['Status'])) {
+        $user['Status'] = 'user';
+    }
+    // 4. Set authsource if not allready set.
+    if (empty($user['AuthSource'])) {
+        $user['AuthSource'] = PLATFORM_AUTH_SOURCE;
+    }
+    return $user;
+}
+
+/**
+ * Update users from the imported data
+ * @param   array   $users List of users
+ * @return  void
+ * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
+ */
+ 
+function updateUsers($users)
+{
+    global $insertedIn_course;
+    // Not all scripts declare the $inserted_in_course array (although they should).
+    if (!isset($inserted_in_course)) {
+        $inserted_in_course = array();
+    }
+    require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+    $usergroup = new UserGroup();
+    $send_mail = $_POST['sendMail'] ? true : false;
+    if (is_array($users)) {
+        foreach ($users as $user) {
+            $user = complete_missing_data($user);
+            $user['Status'] = api_status_key($user['Status']);
+            $userName = $user['UserName'];
+            $userInfo = api_get_user_info_from_username($userName);
+            $user_id = $userInfo['user_id'];
+            if ($user_id == 0) {
+                return false;
+            } 
+            $firstName = isset($user['FirstName']) ? $user['FirstName'] : $userInfo['firstname'];
+            $lastName = isset($user['LastName']) ? $user['LastName'] : $userInfo['lastname'];
+            $userName = isset($user['NewUserName']) ? $user['NewUserName'] : $userInfo['username'];
+            $password = isset($user['Password']) ? $user['Password'] : $userInfo['password'];
+            $authSource = isset($user['AuthSource']) ? $user['AuthSource'] : $userInfo['auth_source'];
+            $email = isset($user['Email']) ? $user['Email'] : $userInfo['email'];
+            $status = isset($user['Status']) ? $user['Status'] : $userInfo['status'];
+            $officialCode = isset($user['OfficialCode']) ? $user['OfficialCode'] : $userInfo['official_code'];
+            $phone = isset($user['PhoneNumber']) ? $user['PhoneNumber'] : $userInfo['phone'];
+            $pictureUrl = isset($user['PictureUri']) ? $user['PictureUri'] : $userInfo['picture_url'];
+            $expirationDate = isset($user['ExpiryDate']) ? $user['ExpiryDate'] : $userInfo['expiration_date'];
+            $active = isset($user['Active']) ? $user['Active'] : $userInfo['active'];
+            $creatorId = $userInfo['creator_id'];
+            $hrDeptId = $userInfo['hr_dept_id'];
+            $language = isset($user['Language']) ? $user['Language'] : $userInfo['language'];
+            $sendEmail = isset($user['SendEmail']) ? $user['SendEmail'] : $userInfo['language'];
+            $userUpdated = UserManager :: update_user(
+                $user_id,
+                $firstName,
+                $lastName,
+                $userName,
+                $password,
+                $authSource,
+                $email,
+                $status,
+                $officialCode,
+                $phone,
+                $pictureUrl,
+                $expirationDate,
+                $active,
+                $creatorId,
+                $hrDeptId,
+                null,
+                $language,
+                '',   
+                '',
+                ''
+                
+            );
+            if (!is_array($user['Courses']) && !empty($user['Courses'])) {
+                $user['Courses'] = array($user['Courses']);
+            }
+            if (is_array($user['Courses'])) {
+                foreach ($user['Courses'] as $course) {
+                    if (CourseManager::course_exists($course)) {
+                        CourseManager::subscribe_user($user_id, $course, $user['Status']);
+                        $course_info = CourseManager::get_course_information($course);
+                        $inserted_in_course[$course] = $course_info['title'];
+                    }
+                    if (CourseManager :: course_exists($course, true)) {
+                        // Also subscribe to virtual courses through check on visual code.
+                        $list = CourseManager :: get_courses_info_from_visual_code($course);
+                        foreach ($list as $vcourse) {
+                            if ($vcourse['code'] == $course) {
+                                // Ignore, this has already been inserted.
+                            } else {
+                                CourseManager :: subscribe_user($user_id, $vcourse['code'], $user['Status']);
+                                $inserted_in_course[$vcourse['code']] = $vcourse['title'];
+                            }
+                        }
+                    }
+                }
+            }
+            if (!empty($user['ClassId'])) {
+                $classId = explode('|', trim($user['ClassId']));
+                foreach ($classId as $id) {
+                    $usergroup->subscribe_users_to_usergroup($id, array($user_id), false);
+                }
+            }
+
+            // Saving extra fields.
+            global $extra_fields;
+
+            // We are sure that the extra field exists.
+            foreach ($extra_fields as $extras) {
+                if (isset($user[$extras[1]])) {
+                    $key 	= $extras[1];
+                    $value 	= $user[$extras[1]];
+                    UserManager::update_extra_field_value($user_id, $key, $value);
+                }
+            }
+        }
+    }
+}
+
+
+/**
+ * Read the CSV-file
+ * @param string $file Path to the CSV-file
+ * @return array All userinformation read from the file
+ */
+function parse_csv_data($file)
+{
+    $users = Import :: csv_to_array($file);
+    foreach ($users as $index => $user) {
+        if (isset ($user['Courses'])) {
+            $user['Courses'] = explode('|', trim($user['Courses']));
+        }
+        $users[$index] = $user;
+    }
+    return $users;
+}
+/**
+ * XML-parser: handle start of element
+ * @param   string  $parser Deprecated?
+ * @param   string  $data The data to be parsed
+ */
+function element_start($parser, $data)
+{
+    $data = api_utf8_decode($data);
+    global $user;
+    global $current_tag;
+    switch ($data) {
+        case 'Contact':
+            $user = array ();
+            break;
+        default:
+            $current_tag = $data;
+    }
+}
+
+/**
+ * XML-parser: handle end of element
+ * @param   string  $parser Deprecated?
+ * @param   string  $data   The data to be parsed
+ */
+function element_end($parser, $data)
+{
+    $data = api_utf8_decode($data);
+    global $user;
+    global $users;
+    global $current_value;
+    switch ($data) {
+        case 'Contact':
+            if ($user['Status'] == '5') {
+                $user['Status'] = STUDENT;
+            }
+            if ($user['Status'] == '1') {
+                $user['Status'] = COURSEMANAGER;
+            }
+            $users[] = $user;
+            break;
+        default:
+            $user[$data] = $current_value;
+            break;
+    }
+}
+
+/**
+ * XML-parser: handle character data
+ * @param   string  $parser Parser (deprecated?)
+ * @param   string  $data The data to be parsed
+ * @return  void
+ */
+function character_data($parser, $data)
+{
+    $data = trim(api_utf8_decode($data));
+    global $current_value;
+    $current_value = $data;
+}
+
+/**
+ * Read the XML-file
+ * @param string $file Path to the XML-file
+ * @return array All user information read from the file
+ */
+function parse_xml_data($file)
+{
+    global $users;
+    $users = array();
+    $parser = xml_parser_create('UTF-8');
+    xml_set_element_handler($parser, 'element_start', 'element_end');
+    xml_set_character_data_handler($parser, 'character_data');
+    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
+    xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
+    xml_parser_free($parser);
+    return $users;
+}
+
+$this_section = SECTION_PLATFORM_ADMIN;
+api_protect_admin_script(true, null, 'login');
+
+
+$defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
+
+if (is_array($extAuthSource)) {
+    $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
+}
+
+$tool_name = get_lang('ImportUserListXMLCSV');
+$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+
+set_time_limit(0);
+$extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
+$user_id_error = array();
+$error_message = '';
+
+if (isset($_POST['formSent']) && $_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
+    
+    $file_type = 'csv';    
+   
+    Security::clear_token();
+    $tok = Security::get_token();
+    $allowed_file_mimetype = array('csv', 'xml');
+    $error_kind_file = false;
+
+    $uploadInfo = pathinfo($_FILES['import_file']['name']);
+    $ext_import_file = $uploadInfo['extension'];
+
+    if (in_array($ext_import_file, $allowed_file_mimetype)) {
+        if (strcmp($file_type, 'csv') === 0 && $ext_import_file == $allowed_file_mimetype[0]) {
+            $users	= parse_csv_data($_FILES['import_file']['tmp_name']);
+            $errors = validate_data($users);
+            $error_kind_file = false;
+        } elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
+            $users = parse_xml_data($_FILES['import_file']['tmp_name']);
+            $errors = validate_data($users);
+            $error_kind_file = false;
+        } else {
+        
+            $error_kind_file = true;
+        }
+    } else {
+        $error_kind_file = true;
+    }
+
+    // List user id with error.
+    $users_to_insert = $user_id_error = array();
+
+    if (is_array($errors)) {
+        foreach ($errors as $my_errors) {
+            $user_id_error[] = $my_errors['UserName'];
+        }
+    }
+
+    if (is_array($users)) {
+        foreach ($users as $my_user) {
+            if (!in_array($my_user['UserName'], $user_id_error)) {
+                $users_to_insert[] = $my_user;
+            }
+        }
+    }
+
+    $inserted_in_course = array();
+    if (strcmp($file_type, 'csv') === 0) {
+        updateUsers($users_to_insert);
+    } else {
+        $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption1');
+    }
+
+    if (count($errors) > 0) {
+        $see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
+    } else {
+        $see_message_import = get_lang('FileImported');
+    }
+
+    if (count($errors) != 0) {
+        $warning_message = '<ul>';
+        foreach ($errors as $index => $error_user) {
+            $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
+            $warning_message .=
+                '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.
+                api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
+            $warning_message .= '</li>';
+        }
+        $warning_message .= '</ul>';
+    }
+
+    // if the warning message is too long then we display the warning message trough a session
+
+    $_SESSION['session_message_import_users'] = $warning_message;
+    $warning_message = 'session_message';
+
+    if ($error_kind_file) {
+        $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
+    } else {
+        header('Location: '.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=show_message&warn='.urlencode($warning_message).'&message='.urlencode($see_message_import).'&sec_token='.$tok);
+        exit;
+    }
+
+}
+Display :: display_header($tool_name);
+
+if (!empty($error_message)) {
+    Display::display_error_message($error_message);
+}
+
+$form = new FormValidator('user_update_import','post','user_update_import.php');
+$form->addElement('header', '', $tool_name);
+$form->addElement('hidden', 'formSent');
+$form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
+
+$group = array();
+
+$form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
+$defaults['formSent'] = 1;
+$defaults['sendMail'] = 0;
+$defaults['file_type'] = 'csv';
+$form->setDefaults($defaults);
+$form->display();
+
+$list = array();
+$list_reponse = array();
+$result_xml = '';
+$i = 0;
+$count_fields = count($extra_fields);
+if ($count_fields > 0) {
+    foreach ($extra_fields as $extra) {
+        $list[] = $extra[1];
+        $list_reponse[] = 'xxx';
+        $spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+        $result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
+        if ($i != $count_fields - 1) {
+            $result_xml .= '<br/>';
+        }
+        $i++;
+    }
+}
+
+?>
+    <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+     
+        <blockquote>
+            <pre>
+                <b>UserName</b>;LastName;FirstName;Email;NewUserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;ExpiryDate;Active;Language;Courses;ClassId;
+                xxx;xxx;xxx;xxx;xxx;xxx;xxx;xxx;xxx;user/teacher/drh;0000-00-00 00:00:00;0/1;xxx;<span style="color:red;"><?php if (count($list_reponse) > 0) echo implode(';', $list_reponse).';'; ?></span>xxx1|xxx2|xxx3;1;<br />
+            </pre>
+        </blockquote>
+    <p><?php
+
+Display :: display_footer();

+ 27 - 27
main/auth/inscription.php

@@ -2,8 +2,8 @@
 /* For licensing terms, see /license.txt */
 
 /**
- *	This script displays a form for registering new users.
- *	@package	 chamilo.auth
+ *  This script displays a form for registering new users.
+ *  @package    chamilo.auth
  */
 
 use \ChamiloSession as Session;
@@ -51,11 +51,11 @@ if (!empty($course_code_redirect)) {
 if ($user_already_registered_show_terms == false) {
 
     if (api_is_western_name_order()) {
-        //	FIRST NAME and LAST NAME
+        // 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
+        // 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));
     }
@@ -63,7 +63,7 @@ if ($user_already_registered_show_terms == false) {
     $form->addRule('lastname',  get_lang('ThisFieldIsRequired'), 'required');
     $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 
-    //	EMAIL
+    // EMAIL
     $form->addElement('text', 'email', get_lang('Email'), array('size' => 40));
     if (api_get_setting('registration', 'email') == 'true') {
         $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
@@ -83,14 +83,14 @@ if ($user_already_registered_show_terms == false) {
         $form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40));
     }
     // Enabled by Ivan Tcholakov, 06-APR-2009. CONFVAL_ASK_FOR_OFFICIAL_CODE = false by default.
-    //	OFFICIAL CODE
+    // OFFICIAL CODE
     if (CONFVAL_ASK_FOR_OFFICIAL_CODE) {
         $form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
         if (api_get_setting('registration', 'officialcode') == 'true')
             $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
     }
 
-    //	USERNAME
+    // USERNAME
     if (api_get_setting('login_is_email') != 'true') {
         $form->addElement('text', 'username', get_lang('UserName'), array('id' => 'username', 'size' => USERNAME_MAX_LENGTH));
         $form->applyFilter('username','trim');
@@ -100,7 +100,7 @@ if ($user_already_registered_show_terms == false) {
         $form->addRule('username', get_lang('UserTaken'), 'username_available');
     }
 
-    //	PASSWORD
+    // PASSWORD
     $form->addElement('password', 'pass1', get_lang('Pass'), array('id' => 'pass1', 'size' => 20, 'autocomplete' => 'off'));
 
     if (isset($_configuration['allow_strength_pass_checker']) && $_configuration['allow_strength_pass_checker']) {
@@ -115,7 +115,7 @@ if ($user_already_registered_show_terms == false) {
     if (CHECK_PASS_EASY_TO_FIND)
         $form->addRule('password1', get_lang('PassTooEasy').': '.api_generate_password(), 'callback', 'api_check_password');
 
-    //	PHONE
+    // PHONE
     $form->addElement('text', 'phone', get_lang('Phone'), array('size' => 20));
     if (api_get_setting('registration', 'phone') == 'true')
         $form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
@@ -127,11 +127,11 @@ if ($user_already_registered_show_terms == false) {
         $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
     }*/
 
-    //	LANGUAGE
+    // LANGUAGE
     if (api_get_setting('registration', 'language') == 'true') {
         $form->addElement('select_language', 'language', get_lang('Language'));
     }
-    //	STUDENT/TEACHER
+    // STUDENT/TEACHER
     if (api_get_setting('allow_registration_as_teacher') != 'false') {
         $form->addElement('radio', 'status', get_lang('Profile'), get_lang('RegStudent'), STUDENT);
         $form->addElement('radio', 'status', null, get_lang('RegAdmin'), COURSEMANAGER);
@@ -165,7 +165,7 @@ if ($user_already_registered_show_terms == false) {
         $form->addRule('captcha', get_lang('TheTextYouEnteredDoesNotMatchThePicture'), 'CAPTCHA', $captcha_question);
     }
 
-    //	EXTENDED FIELDS
+    // EXTENDED FIELDS
     if (api_get_setting('extended_profile') == 'true' && api_get_setting('extendedprofile_registration', 'mycomptetences') == 'true') {
         $form->add_html_editor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'register', 'Width' => '100%', 'Height' => '130'));
     }
@@ -485,26 +485,26 @@ if ($form->validate()) {
                 Database::query($sql);
 
                 // 2. Send mail to all platform admin
-                $emailsubject	 = get_lang('ApprovalForNewAccount',null,$values['language']).': '.$values['username'];
-                $emailbody		 = get_lang('ApprovalForNewAccount',null,$values['language'])."\n";
-                $emailbody		.= get_lang('UserName',null,$values['language']).': '.$values['username']."\n";
+                $emailsubject  = get_lang('ApprovalForNewAccount',null,$values['language']).': '.$values['username'];
+                $emailbody = get_lang('ApprovalForNewAccount',null,$values['language'])."\n";
+                $emailbody .= get_lang('UserName',null,$values['language']).': '.$values['username']."\n";
 
                 if (api_is_western_name_order()) {
-                    $emailbody	.= get_lang('FirstName',null,$values['language']).': '.$values['firstname']."\n";
-                    $emailbody	.= get_lang('LastName',null,$values['language']).': '.$values['lastname']."\n";
+                    $emailbody .= get_lang('FirstName',null,$values['language']).': '.$values['firstname']."\n";
+                    $emailbody .= get_lang('LastName',null,$values['language']).': '.$values['lastname']."\n";
                 } else {
-                    $emailbody	.= get_lang('LastName',null,$values['language']).': '.$values['lastname']."\n";
-                    $emailbody	.= get_lang('FirstName',null,$values['language']).': '.$values['firstname']."\n";
+                    $emailbody .= get_lang('LastName',null,$values['language']).': '.$values['lastname']."\n";
+                    $emailbody .= get_lang('FirstName',null,$values['language']).': '.$values['firstname']."\n";
                 }
-                $emailbody		.= get_lang('Email',null,$values['language']).': '.$values['email']."\n";
-                $emailbody		.= get_lang('Status',null,$values['language']).': '.$values['status']."\n\n";
+                $emailbody .= get_lang('Email',null,$values['language']).': '.$values['email']."\n";
+                $emailbody .= get_lang('Status',null,$values['language']).': '.$values['status']."\n\n";
 
                 $url_edit = Display::url(
                     api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user_id,
                     api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user_id
                 );
 
-                $emailbody		.= get_lang('ManageUser',null,$values['language']).": $url_edit";
+                $emailbody .= get_lang('ManageUser',null,$values['language']).": $url_edit";
 
                 $admins = UserManager::get_all_administrators();
                 foreach ($admins as $admin_info) {
@@ -521,7 +521,7 @@ if ($form->validate()) {
                         $user_id
                     );
                 }
-                
+
                 // 3. exit the page
                 unset($user_id);
 
@@ -551,10 +551,10 @@ if ($form->validate()) {
     /* SESSION REGISTERING */
     /* @todo move this in a function */
     $_user['firstName'] = stripslashes($values['firstname']);
-    $_user['lastName'] 	= stripslashes($values['lastname']);
-    $_user['mail'] 		= $values['email'];
-    $_user['language'] 	= $values['language'];
-    $_user['user_id']	= $user_id;
+    $_user['lastName'] = stripslashes($values['lastname']);
+    $_user['mail'] = $values['email'];
+    $_user['language'] = $values['language'];
+    $_user['user_id'] = $user_id;
     $is_allowedCreateCourse = $values['status'] == 1;
     $usersCanCreateCourse = (api_get_setting('allow_users_to_create_courses') == 'true');
 

+ 4 - 1
main/auth/profile.php

@@ -115,6 +115,9 @@ $value_array = $array_list_key[$id_temp_key];
 $user_data['api_key_generate'] = $value_array;
 
 if ($user_data !== false) {
+    if (api_get_setting('login_is_email') == 'true') {
+        $user_data['username'] = $user_data['email'];
+    }
     if (is_null($user_data['language'])) {
         $user_data['language'] = api_get_setting('platformLanguage');
     }
@@ -145,7 +148,7 @@ $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 
 //    USERNAME
 $form->addElement('text', 'username', get_lang('UserName'), array('id' => 'username', 'maxlength' => USERNAME_MAX_LENGTH, 'size' => USERNAME_MAX_LENGTH));
-if (api_get_setting('profile', 'login') !== 'true') {
+if (api_get_setting('profile', 'login') !== 'true' || api_get_setting('login_is_email') == 'true') {
     $form->freeze('username');
 }
 $form->applyFilter('username', 'stripslashes');

+ 4 - 0
main/course_progress/thematic.php

@@ -53,6 +53,10 @@ if ($action == 'thematic_list') {
 	$table->display();
 	
 } elseif ($action == 'thematic_details') {
+    
+    if (isset($_GET['thematic_plan_save_message']) && $_GET['thematic_plan_save_message'] == 'ok') {
+        Display::display_confirmation_message(get_lang('ThematicSectionHasBeenCreatedSuccessfull'));
+    }
 
 	if (isset($last_id) && $last_id) {
 		$link_to_thematic_plan = '<a href="index.php?'.api_get_cidreq().'&action=thematic_plan_list&thematic_id='.$last_id.'">'.Display::return_icon('lesson_plan.png', get_lang('ThematicPlan'), array('style'=>'vertical-align:middle;float:none;'),ICON_SIZE_SMALL).'</a>';

+ 6 - 0
main/course_progress/thematic_controller.php

@@ -286,6 +286,12 @@ class ThematicController
                             }
                             unset($_SESSION['thematic_plan_token']);
                             $data['message'] = 'ok';
+                            
+                            $saveRedirect = api_get_path(WEB_PATH) . 'main/course_progress/index.php?';
+                            $saveRedirect.= api_get_cidreq() . '&';
+                            $saveRedirect.= 'thematic_plan_save_message=ok';
+
+                            header("Location: $saveRedirect");
                         }
                         $data['action'] = 'thematic_plan_list';
                     }

+ 1 - 1
main/course_progress/thematic_plan.php

@@ -40,7 +40,7 @@ if ($action == 'thematic_plan_list') {
         
         foreach ($default_thematic_plan_title as $id => $title) {
             $form->addElement('hidden', 'description_type['.$id.']', $id);
-            $form->add_textfield('title['.$id.']', get_lang('Title'), true, array('size'=>'50'));
+            $form->add_textfield('title['.$id.']', get_lang('Title'), false, array('size'=>'50'));
             $form->add_html_editor('description['.$id.']', get_lang('Description'), false, false, array('ToolbarStartExpanded'=>'false', 'ToolbarSet' => 'TrainingDescription', 'Width' => '80%', 'Height' => '150'));
             //$form->addElement('textarea', 'description['.$id.']', get_lang('Description'));                            
             if (!empty($thematic_simple_list) && in_array($id, $thematic_simple_list)) {

+ 1 - 1
main/document/document_slideshow.inc.php

@@ -36,7 +36,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'exit_slideshow') {
 // We check if there are images in this folder by searching the extensions for .jpg, .gif, .png
 // grabbing the list of all the documents of this folder
 //$all_files = $fileList['name'];
-$array_to_search = !empty($docs_and_folders) && is_array($docs_and_folders) ? $docs_and_folders : array();
+$array_to_search = !empty($documentAndFolders) && is_array($documentAndFolders) ? $documentAndFolders : array();
 
 if (count($array_to_search) > 0) {
 	while (list($key) = each($array_to_search)) {

File diff suppressed because it is too large
+ 412 - 387
main/dropbox/dropbox_functions.inc.php


+ 9 - 4
main/exercice/exercise_result.class.php

@@ -193,10 +193,15 @@ class ExerciseResult
 				$return[$i] = array();
 				if (empty($user_id)) {
                     $return[$i]['official_code']   = $result['official_code'];
-					$return[$i]['first_name']   = $result['userpart1'];
-					$return[$i]['last_name']    = $result['userpart2'];
-					$return[$i]['user_id']      = $result['excruid'];
-					$return[$i]['email']        = $result['exemail'];
+                    if (api_is_western_name_order()) {
+                        $return[$i]['first_name']   = $results[$i]['userpart1'];
+                        $return[$i]['last_name']    = $results[$i]['userpart2'];
+                    } else {
+                        $return[$i]['first_name']   = $results[$i]['userpart2'];
+                        $return[$i]['last_name']    = $results[$i]['userpart1'];
+                    }
+					$return[$i]['user_id']      = $results[$i]['excruid'];
+					$return[$i]['email']        = $results[$i]['exemail'];
 				}
 				$return[$i]['title'] = $result['extitle'];
 				$return[$i]['start_date'] = api_get_local_time($result['exstart']);

+ 1 - 0
main/exercice/global_multiple_answer.class.php

@@ -55,6 +55,7 @@ class GlobalMultipleAnswer extends Question
         $correct = 0;
 
         /* Mise en variable du nombre de reponse */
+        $answer = false;
         if (!empty($this->id)) {
             $answer = new Answer($this->id);
             $answer->read();

+ 22 - 12
main/exercice/hotspot_admin.inc.php

@@ -69,6 +69,10 @@ if ($modifyIn) {
 $hotspot_admin_url = api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidreq() . '&exerciseId=' . $exerciseId;
 
 // the answer form has been submitted
+
+$submitAnswers = isset($submitAnswers) ? $submitAnswers : false;
+$buttonBack = isset($buttonBack) ? $buttonBack : false;
+$nbrAnswers = isset($nbrAnswers) ? $nbrAnswers : 0;
 if ($submitAnswers || $buttonBack) {
 
     if ($answerType == HOT_SPOT) {
@@ -231,7 +235,7 @@ if ($submitAnswers || $buttonBack) {
         }  // end for()
 
         //now the noerror section
-        $select_question_noerror = $_POST['select_question_noerror'];
+        $selectQuestionNoError = $_POST['select_question_noerror'];
         $lp_noerror = $_POST['lp_noerror'];
         $try_noerror = $_POST['try_noerror'];
         $url_noerror = $_POST['url_noerror'];
@@ -256,10 +260,10 @@ if ($submitAnswers || $buttonBack) {
             $url_str = $url_noerror;
         }
 
-        if ($select_question_noerror == '') {
+        if ($selectQuestionNoError == '') {
             $question_str = 0;
         } else {
-            $question_str = $select_question_noerror;
+            $question_str = $selectQuestionNoError;
         }
 
         $destination_noerror = $threadhold_total . '@@' . $try_str . '@@' . $lp_str . '@@' . $question_str . '@@' . $url_str;
@@ -380,7 +384,7 @@ if ($modifyAnswers) {
 
         $try_noerror = $destination_items[1];
         $lp_noerror = $destination_items[2];
-        $select_question_noerror = $destination_items[3];
+        $selectQuestionNoError = $destination_items[3];
         $url_noerror = $destination_items[4];
     }
 
@@ -396,6 +400,7 @@ if ($modifyAnswers) {
         $_SESSION['tmp_answers']['destination'] = $destination;
     }
 
+    $lessAnswers = isset($lessAnswers) ? $lessAnswers : false;
     if ($lessAnswers) {
         if ($answerType == HOT_SPOT_DELINEATION) {
             $lest_answer = 1;
@@ -433,6 +438,7 @@ if ($modifyAnswers) {
         }
     }
 
+    $moreAnswers = isset($moreAnswers) ? $moreAnswers : false;
     if ($moreAnswers) {
         if ($nbrAnswers < 12) {
             $nbrAnswers++;
@@ -451,6 +457,7 @@ if ($modifyAnswers) {
         }
     }
 
+    $moreOARAnswers = isset($moreOARAnswers) ? $moreOARAnswers : false;
     if ($moreOARAnswers) {
         if ($nbrAnswers < 12) {
             // Add a new answer
@@ -571,17 +578,17 @@ if ($modifyAnswers) {
                                 $option_lp = '';
 
                                 // setting the LP
-                                $is_selected = false;
+                                $isSelected = false;
                                 foreach ($flat_list as $id => $details) {
                                     $select_lp_id[$id] = $details['lp_name'];
                                     $selected = '';
                                     if ($id == $lp[$i]) {
-                                        $is_selected = true;
+                                        $isSelected = true;
                                         $selected = 'selected="selected"';
                                     }
                                     $option_lp.='<option value="' . $id . '" ' . $selected . '>' . $details['lp_name'] . '</option>';
                                 }
-                                if ($is_selected) {
+                                if ($isSelected) {
                                     $option_lp = '<option value="0">' . get_lang('SelectTargetLP') . '</option>' . $option_lp;
                                 } else {
                                     $option_lp = '<option value="0" selected="selected" >' . get_lang('SelectTargetLP') . '</option>' . $option_lp;
@@ -871,18 +878,18 @@ if ($modifyAnswers) {
                         $flat_list = $list->get_flat_list();
                         $select_lp_id = array();
                         $option_lp = '';
-                        //$option_lp.='<option value="0">'.get_lang('SelectTargetLP').'</option>';
+                        $isSelected = false;
                         foreach ($flat_list as $id => $details) {
                             $selected = '';
                             $select_lp_id[$id] = $details['lp_name'];
                             if ($id == $lp_noerror) {
                                 $selected = 'selected="selected"';
-                                $is_selected = true;
+                                $isSelected = true;
                             }
                             $option_lp.='<option value="' . $id . '" ' . $selected . '>' . $details['lp_name'] . '</option>';
                         }
 
-                        if ($is_selected) {
+                        if ($isSelected) {
                             $option_lp = '<option value="0">' . get_lang('SelectTargetLP') . '</option>' . $option_lp;
                         } else {
                             $option_lp = '<option value="0" selected="selected" >' . get_lang('SelectTargetLP') . '</option>' . $option_lp;
@@ -893,17 +900,20 @@ if ($modifyAnswers) {
                         $question_list = $objExercise->selectQuestionList();
                         $option_feed = '';
                         $option_feed.='<option value="0">' . get_lang('SelectTargetQuestion') . '</option>';
+                        $details = isset($details) ? $details : null;
+                        $id = isset($id) ? $id : 0;
+                        $selectQuestionNoError = isset($selectQuestionNoError) ? $selectQuestionNoError : null;
                         foreach ($question_list as $key => $questionid) {
                             $selected = '';
                             $question = Question::read($questionid);
                             $val = 'Q' . $key . ' :' . substrwords($question->selectTitle(), ICON_SIZE_SMALL);
                             $select_lp_id[$id] = $details['lp_name'];
-                            if ($questionid == $select_question_noerror) {
+                            if ($questionid == $selectQuestionNoError) {
                                 $selected = 'selected="selected"';
                             }
                             $option_feed.='<option value="' . $questionid . '" ' . $selected . ' >' . $val . '</option>';
                         }
-                        if ($select_question_noerror == -1)
+                        if ($selectQuestionNoError == -1)
                             $option_feed.='<option value="-1" selected="selected" >' . get_lang('ExitTest') . '</option>';
                         else
                             $option_feed.='<option value="-1">' . get_lang('ExitTest') . '</option>';

+ 1 - 0
main/exercice/multiple_answer.class.php

@@ -61,6 +61,7 @@ class MultipleAnswer extends Question
 
 		$defaults = array();
 		$correct = 0;
+        $answer = false;
 		if(!empty($this -> id))	{
 			$answer = new Answer($this -> id);
 			$answer -> read();

+ 1 - 0
main/exercice/multiple_answer_combination.class.php

@@ -53,6 +53,7 @@ class MultipleAnswerCombination extends Question
 
 		$defaults = array();
 		$correct = 0;
+        $answer = false;
 		if(!empty($this -> id))	{
 			$answer = new Answer($this -> id);
 			$answer -> read();

+ 1 - 0
main/exercice/question.class.php

@@ -1470,6 +1470,7 @@ abstract class Question
         }
 
         if ($this->type == FREE_ANSWER || $this->type == ORAL_EXPRESSION) {
+            $score['revised'] = isset($score['revised']) ? $score['revised'] : false;
             if ($score['revised'] == true) {
                 $score_label = get_lang('Revised');
                 $class = '';

+ 4 - 3
main/exercice/question_admin.inc.php

@@ -27,15 +27,15 @@ if (is_object($objQuestion)) {
 	if (isset($_GET['editQuestion'])) {
 		$class="btn save";
 		$text=get_lang('ModifyQuestion');
-		$type = Security::remove_XSS($_GET['type']);
+		$type = isset($_GET['type']) ? Security::remove_XSS($_GET['type']) : null;
 	} else {
 		$class="btn add";
 		$text=get_lang('AddQuestionToExercise');
 		$type = $_REQUEST['answerType'];
 	}
 
-	$types_information = Question::get_question_type_list();
-	$form_title_extra = get_lang($types_information[$type][1]);
+	$typesInformation = Question::get_question_type_list();
+	$form_title_extra = isset($typesInformation[$type][1]) ? get_lang($typesInformation[$type][1]) : null;
 
 	// form title
 	$form->addElement('header', $text.': '.$form_title_extra);
@@ -59,6 +59,7 @@ if (is_object($objQuestion)) {
 	    $objQuestion->processCreation($form, $objExercise);
 
 	    // answers
+	    $nb_answers = isset($nb_answers) ? $nb_answers : 0;
 	    $objQuestion->processAnswersCreation($form, $nb_answers);
 
         // TODO: maybe here is the better place to index this tool, including answers text

+ 3 - 3
main/exercice/unique_answer_no_option.class.php

@@ -83,7 +83,7 @@ class UniqueAnswerNoOption extends Question
 
 		$defaults = array();
 		$correct = 0;
-
+        $answer = false;
 		if (!empty($this -> id)) {
 			$answer = new Answer($this -> id);
 			$answer -> read();
@@ -98,8 +98,8 @@ class UniqueAnswerNoOption extends Question
 			$nb_answers = 1;
 			Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
 		}
-        if ($_GET['editQuestion']) {
-
+        $editQuestion = isset($_GET['editQuestion']) ? $_GET['editQuestion'] : false;
+        if ($editQuestion) {
             //fixing $nb_answers
             $new_list = array();
             $count = 1;

+ 87 - 94
main/forum/forumfunction.inc.php

@@ -55,14 +55,9 @@ function handle_forum_and_forumcategories($lp_id = null)
     $get_content = isset($_GET['content']) ? $_GET['content'] : '';
     $post_submit_cat = isset($_POST['SubmitForumCategory']) ? true : false;
     $post_submit_forum = isset($_POST['SubmitForum']) ? true : false;
-    $get_id = isset($_GET['id']) ? $_GET['id'] : '';
+    $get_id = isset($_GET['id']) ? intval($_GET['id']) : '';
     $forum_categories_list = get_forum_categories();
 
-    // Verify if exist content and action
-    if ((($action_forum_cat == '' || $get_content == '') && !$post_submit_cat) && !$post_submit_forum) {
-        return null;
-    }
-
     //Verify if forum category exists
     if (empty($forum_categories_list)) {
         $get_content = 'forumcategory';
@@ -82,10 +77,6 @@ function handle_forum_and_forumcategories($lp_id = null)
         show_add_forum_form($inputvalues, $lp_id);
     }
 
-    //Verify if id is set
-    if ($get_id == '') {
-        return null;
-    }
     // Edit a forum category
     if (($action_forum_cat == 'edit' && $get_content == 'forumcategory') || (isset($_POST['SubmitEditForumCategory'])) ? true : false) {
         $forum_category = get_forum_categories($get_id);
@@ -480,7 +471,7 @@ function store_forumcategory($values)
         $return_message = get_lang('ForumCategoryEdited');
     } else {
         $sql = "INSERT INTO ".$table_categories." (c_id, cat_title, cat_comment, cat_order, session_id)
-        		VALUES (".$course_id.", '".$clean_cat_title."','".Database::escape_string($values['forum_category_comment'])."','".Database::escape_string($new_max)."','".Database::escape_string($session_id)."')";
+                VALUES (".$course_id.", '".$clean_cat_title."','".Database::escape_string($values['forum_category_comment'])."','".Database::escape_string($new_max)."','".Database::escape_string($session_id)."')";
         Database::query($sql);
         $last_id = Database::insert_id();
         if ($last_id > 0) {
@@ -521,8 +512,8 @@ function store_forum($values)
     } else {
         $sql = "SELECT MAX(forum_order) as sort_max
                 FROM ".$table_forums."
-        		WHERE
-        		    c_id = $course_id AND
+                WHERE
+                    c_id = $course_id AND
                     forum_category='".Database::escape_string($values['forum_category'])."'";
         $result = Database::query($sql);
         $row = Database::fetch_array($result);
@@ -619,8 +610,8 @@ function store_forum($values)
 
         $sql = "INSERT INTO ".$table_forums." (c_id, forum_title, forum_image, forum_comment, forum_category, allow_anonymous, allow_edit, approval_direct_post, allow_attachments, allow_new_threads, default_view, forum_of_group, forum_group_public_private, forum_order, session_id)
             VALUES (
-            	".$course_id.",
-            	'".$clean_title."',
+                ".$course_id.",
+                '".$clean_title."',
                 ".$sql_image."
                 '".Database::escape_string(isset($values['forum_comment']) ? $values['forum_comment'] : null)."',
                 '".Database::escape_string(isset($values['forum_category']) ? $values['forum_category'] : null)."',
@@ -1145,7 +1136,7 @@ function get_forum_categories($id = '')
     $session_id = api_get_session_id();
     $course_id = api_get_course_int_id();
 
-    $condition_session = api_get_session_condition($session_id, true, true);
+    $condition_session = api_get_session_condition($session_id, true, false);
     $condition_session .= " AND forum_categories.c_id = $course_id AND item_properties.c_id = $course_id";
 
     if (empty($id)) {
@@ -1221,11 +1212,11 @@ function get_forums_in_category($cat_id)
         $sql = "SELECT * FROM ".$table_forums." forum , ".$table_item_property." item_properties
                 WHERE
                     forum.forum_category = '".Database::escape_string($cat_id)."' AND
-                	forum.forum_id = item_properties.ref AND
-                	item_properties.visibility <> 2 AND
-                	item_properties.tool = '".TOOL_FORUM."' AND
+                    forum.forum_id = item_properties.ref AND
+                    item_properties.visibility <> 2 AND
+                    item_properties.tool = '".TOOL_FORUM."' AND
                     item_properties.c_id = $course_id AND
-                	forum.c_id = $course_id
+                    forum.c_id = $course_id
                 ORDER BY forum_order ASC";
     }
     $result = Database::query($sql);
@@ -1272,7 +1263,7 @@ function get_forums(
         $session_id = $sessionId;
     }
 
-    $condition_session = api_get_session_condition($session_id, true, true);
+    $condition_session = api_get_session_condition($session_id, true, false);
     $course_id = $course_info['real_id'];
 
     $forum_list = array();
@@ -1503,8 +1494,8 @@ function get_last_post_by_thread($course_id, $thread_id, $forum_id, $show_visibl
 /**
  * This function gets all the last post information of a certain forum
  *
- * @param int 	$forum_id the id of the forum we want to know the last post information of.
- * @param bool 	$show_invisibles
+ * @param int   $forum_id the id of the forum we want to know the last post information of.
+ * @param bool  $show_invisibles
  * @param string course db name
  * @return array containing all the information about the last post
  * (last_post_id, last_poster_id, last_post_date, last_poster_name, last_poster_lastname, last_poster_firstname)
@@ -1568,7 +1559,7 @@ function get_last_post_information($forum_id, $show_invisibles = false, $course_
 /**
  * Retrieve all the threads of a given forum
  *
- * @param int 	forum id
+ * @param int   forum id
  * @param string course db name
  * @return an array containing all the information about the threads
  *
@@ -1583,16 +1574,16 @@ function get_threads($forum_id, $course_code = null)
     }
 
     $course_id = $course_info['real_id'];
-
+    $groupId = api_get_group_id();
     $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
     $table_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
     $table_users = Database :: get_main_table(TABLE_MAIN_USER);
 
-    // important note: 	it might seem a little bit awkward that we have 'thread.locked as locked' in the sql statement
+    // important note:  it might seem a little bit awkward that we have 'thread.locked as locked' in the sql statement
     // because we also have thread.* in it. This is because thread has a field locked and post also has the same field
     // since we are merging these we would have the post.locked value but in fact we want the thread.locked value
     // This is why it is added to the end of the field selection
-
+    $groupCondition = api_get_group_id() != 0 ? " AND item_properties.to_group_id = '$groupId' AND item_properties.c_id = '$course_id'" : "";
     $sql = "SELECT
                 thread.*,
                 item_properties.*,
@@ -1605,7 +1596,7 @@ function get_threads($forum_id, $course_code = null)
                 ON  thread.thread_id=item_properties.ref AND
                     item_properties.c_id = $course_id AND
                     thread.c_id = $course_id AND
-                    item_properties.tool='".TABLE_FORUM_THREAD."'
+                    item_properties.tool='".TABLE_FORUM_THREAD."'$groupCondition
             LEFT JOIN $table_users users
                 ON thread.thread_poster_id=users.user_id
             WHERE
@@ -1614,10 +1605,11 @@ function get_threads($forum_id, $course_code = null)
             ORDER BY thread.thread_sticky DESC, thread.thread_date DESC";
 
     if (is_allowed_to_edit()) {
-        // important note: 	it might seem a little bit awkward that we have 'thread.locked as locked' in the sql statement
+        // important note:  it might seem a little bit awkward that we have 'thread.locked as locked' in the sql statement
         // because we also have thread.* in it. This is because thread has a field locked and post also has the same field
         // since we are merging these we would have the post.locked value but in fact we want the thread.locked value
         //This is why it is added to the end of the field selection
+        $groupCondition = api_get_group_id() != 0 ? " AND item_properties.to_group_id = '$groupId' AND item_properties.c_id = '$course_id'" : "";
         $sql = "SELECT
                     thread.*,
                     item_properties.*,
@@ -1630,7 +1622,7 @@ function get_threads($forum_id, $course_code = null)
                     ON  thread.thread_id=item_properties.ref AND
                         item_properties.c_id = $course_id AND
                         thread.c_id = $course_id AND
-                        item_properties.tool='".TABLE_FORUM_THREAD."'
+                        item_properties.tool='".TABLE_FORUM_THREAD."'$groupCondition
                 LEFT JOIN $table_users users
                     ON thread.thread_poster_id=users.user_id
                 WHERE
@@ -1742,10 +1734,10 @@ function get_thread_information($thread_id)
             WHERE
                 item_properties.tool= '".TOOL_FORUM_THREAD."' AND
                 item_properties.c_id = $course_id AND
-                item_properties.ref	= '".Database::escape_string($thread_id)."' AND
-                threads.thread_id	= '".Database::escape_string($thread_id)."' AND
+                item_properties.ref = '".Database::escape_string($thread_id)."' AND
+                threads.thread_id   = '".Database::escape_string($thread_id)."' AND
                 threads.c_id = $course_id
-   			";
+            ";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
 
@@ -1754,9 +1746,9 @@ function get_thread_information($thread_id)
 
 /**
  * This function retrieves forum thread users details
- * @param 	int Thread ID
- * @param	string	Course DB name (optional)
- * @return	resource array Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
+ * @param   int Thread ID
+ * @param   string  Course DB name (optional)
+ * @return  resource array Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
  * @author Christian Fasanando <christian.fasanando@dokeos.com>,
  * @todo     this function need to be improved
  * @version octubre 2008, dokeos 1.8
@@ -1812,9 +1804,9 @@ function get_thread_users_details($thread_id)
 
 /**
  * This function retrieves forum thread users qualify
- * @param 	int Thread ID
- * @param	string	Course DB name (optional)
- * @return	array Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
+ * @param   int Thread ID
+ * @param   string  Course DB name (optional)
+ * @return  array Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
  * @author Jhon Hinojosa<jhon.hinojosa@dokeos.com>,
  * @todo     this function need to be improved
  * @version octubre 2008, dokeos 1.8
@@ -1882,9 +1874,9 @@ function get_thread_users_qualify($thread_id)
 
 /**
  * This function retrieves forum thread users not qualify
- * @param 	int Thread ID
- * @param	string	Course DB name (optional)
- * @return	array Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
+ * @param   int Thread ID
+ * @param   string  Course DB name (optional)
+ * @return  array Array of type ([user_id=>w,lastname=>x,firstname=>y,thread_id=>z],[])
  * @author   Jhon Hinojosa<jhon.hinojosa@dokeos.com>,
  * @version oct 2008, dokeos 1.8
  */
@@ -1966,12 +1958,12 @@ function get_forum_information($forum_id)
 
     $sql = "SELECT * FROM ".$table_forums." forums, ".$table_item_property." item_properties
             WHERE
-                item_properties.tool	= '".TOOL_FORUM."' AND
-                item_properties.ref		= '".Database::escape_string($forum_id)."' AND
+                item_properties.tool    = '".TOOL_FORUM."' AND
+                item_properties.ref     = '".Database::escape_string($forum_id)."' AND
                 item_properties.c_id    = ".api_get_course_int_id()." AND
-                forums.forum_id			= '".Database::escape_string($forum_id)."' AND
+                forums.forum_id         = '".Database::escape_string($forum_id)."' AND
                 forums.c_id = ".api_get_course_int_id()."
-   			";
+            ";
 
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
@@ -2013,7 +2005,7 @@ function get_forumcategory_information($cat_id)
  *
  * @param $cat_id the id of the forum category
  * @todo an additional parameter that takes the visibility into account. For instance $countinvisible=0 would return the number
- * 		of visible forums, $countinvisible=1 would return the number of visible and invisible forums
+ *      of visible forums, $countinvisible=1 would return the number of visible and invisible forums
  * @return int the number of forums inside the given category
  *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
@@ -2084,10 +2076,10 @@ function store_thread($current_forum, $values)
                     '".Database::escape_string(stripslashes(isset($values['poster_name']) ? $values['poster_name'] : null))."',
                     '".Database::escape_string($post_date)."',
                     '".Database::escape_string(isset($values['thread_sticky']) ? $values['thread_sticky'] : null)."',".
-                    "'".Database::escape_string(stripslashes($values['calification_notebook_title']))."',".
-                    "'".Database::escape_string($values['numeric_calification'])."',".
-                    "'".Database::escape_string($values['weight_calification'])."',".
-                    "'".api_get_session_id()."')";
+            "'".Database::escape_string(stripslashes($values['calification_notebook_title']))."',".
+            "'".Database::escape_string($values['numeric_calification'])."',".
+            "'".Database::escape_string($values['weight_calification'])."',".
+            "'".api_get_session_id()."')";
         Database::query($sql);
         $last_thread_id = Database::insert_id();
 
@@ -2203,10 +2195,10 @@ function store_thread($current_forum, $values)
 /**
  * This function displays the form that is used to add a post. This can be a new thread or a reply.
  * @param $action is the parameter that determines if we are
-*  1. newthread: adding a new thread (both empty) => No I-frame
-*  2. replythread: Replying to a thread ($action = replythread) => I-frame with the complete thread (if enabled)
-*  3. replymessage: Replying to a message ($action =replymessage) => I-frame with the complete thread (if enabled) (I first thought to put and I-frame with the message only)
-*  4. quote: Quoting a message ($action= quotemessage) => I-frame with the complete thread (if enabled). The message will be in the reply. (I first thought not to put an I-frame here)
+ *  1. newthread: adding a new thread (both empty) => No I-frame
+ *  2. replythread: Replying to a thread ($action = replythread) => I-frame with the complete thread (if enabled)
+ *  3. replymessage: Replying to a message ($action =replymessage) => I-frame with the complete thread (if enabled) (I first thought to put and I-frame with the message only)
+ *  4. quote: Quoting a message ($action= quotemessage) => I-frame with the complete thread (if enabled). The message will be in the reply. (I first thought not to put an I-frame here)
  * @return void HMTL
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @version february 2006, dokeos 1.8
@@ -2233,14 +2225,14 @@ function show_add_post_form($current_forum, $forum_setting, $action = '', $id =
     }
 
     // Initialize the object.
-    $my_thread = isset($_GET['thread']) ? $_GET['thread'] : '';
+    $myThread = isset($_GET['thread']) ? $_GET['thread'] : '';
     $my_forum = isset($_GET['forum']) ? $_GET['forum'] : '';
     $my_post = isset($_GET['post']) ? $_GET['post'] : '';
     $my_gradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : '';
     $form = new FormValidator(
         'thread',
         'post',
-        api_get_self().'?forum='.Security::remove_XSS($my_forum).'&gradebook='.$gradebook.'&thread='.Security::remove_XSS($my_thread).'&post='.Security::remove_XSS($my_post).'&action='.$action
+        api_get_self().'?forum='.Security::remove_XSS($my_forum).'&gradebook='.$gradebook.'&thread='.Security::remove_XSS($myThread).'&post='.Security::remove_XSS($my_post).'&action='.$action
     );
     $form->setConstants(array('forum' => '5'));
 
@@ -2248,7 +2240,7 @@ function show_add_post_form($current_forum, $forum_setting, $action = '', $id =
 
     // Setting the form elements.
     $form->addElement('hidden', 'forum_id', intval($my_forum));
-    $form->addElement('hidden', 'thread_id', intval($my_thread));
+    $form->addElement('hidden', 'thread_id', intval($myThread));
     $form->addElement('hidden', 'gradebook', $my_gradebook);
 
     // If anonymous posts are allowed we also display a form to allow the user to put his name or username in.
@@ -2264,11 +2256,11 @@ function show_add_post_form($current_forum, $forum_setting, $action = '', $id =
 
     $form->addRule('post_text', get_lang('ThisFieldIsRequired'), 'required');
     $form->addElement('advanced_settings', '<a href="javascript://" onclick="return advanced_parameters()">
-    						  <span id="img_plus_and_minus">&nbsp;'.Display::return_icon('div_show.gif', get_lang('Show'), array('style' => 'vertical-align:middle')).' '.get_lang('AdvancedParameters').'</span></a>');
+                              <span id="img_plus_and_minus">&nbsp;'.Display::return_icon('div_show.gif', get_lang('Show'), array('style' => 'vertical-align:middle')).' '.get_lang('AdvancedParameters').'</span></a>');
 
     $form->addElement('html', '<div id="id_qualify" style="display:none">');
 
-    if ((api_is_course_admin() || api_is_course_coach() || api_is_course_tutor()) && !($my_thread)) {
+    if ((api_is_course_admin() || api_is_course_coach() || api_is_course_tutor()) && !($myThread)) {
 
         // Thread qualify
         if (Gradebook::is_active()) {
@@ -2335,7 +2327,7 @@ function show_add_post_form($current_forum, $forum_setting, $action = '', $id =
         // When we are quoting a message then we have to put that message into the wysiwyg editor.
         // Note: The style has to be hardcoded here because using class="quote" didn't work.
         if ($action == 'quote') {
-            $defaults['post_text'] = '<div>&nbsp;</div><div style="margin: 5px;"><div style="font-size: 90%; font-style: italic;">'.get_lang('Quoting').' '.api_get_person_name($values['firstname'], $values['lastname']).':</div><div style="color: #006600; font-size: 90%;	font-style: italic; background-color: #FAFAFA; border: #D1D7DC 1px solid; padding: 3px;">'.prepare4display($values['post_text']).'</div></div><div>&nbsp;</div><div>&nbsp;</div>';
+            $defaults['post_text'] = '<div>&nbsp;</div><div style="margin: 5px;"><div style="font-size: 90%; font-style: italic;">'.get_lang('Quoting').' '.api_get_person_name($values['firstname'], $values['lastname']).':</div><div style="color: #006600; font-size: 90%;  font-style: italic; background-color: #FAFAFA; border: #D1D7DC 1px solid; padding: 3px;">'.prepare4display($values['post_text']).'</div></div><div>&nbsp;</div><div>&nbsp;</div>';
         }
     }
     $form->setDefaults(isset($defaults) ? $defaults : null);
@@ -2366,10 +2358,11 @@ function show_add_post_form($current_forum, $forum_setting, $action = '', $id =
         $form->setConstants(array('sec_token' => $token));
 
         $iframe = null;
-
-        if ($forum_setting['show_thread_iframe_on_reply'] && $action != 'newthread') {
-            $iframe = "<iframe style=\"border: 1px solid black\" src=\"iframe_thread.php?forum=".Security::remove_XSS($my_forum)."&amp;thread=".Security::remove_XSS($my_thread)."#".Security::remove_XSS($my_post)."\" width=\"100%\"></iframe>";
+        $myThread = Security::remove_XSS($myThread);
+        if ($forum_setting['show_thread_iframe_on_reply'] && $action != 'newthread' && !empty($myThread)) {
+            $iframe = "<iframe style=\"border: 1px solid black\" src=\"iframe_thread.php?forum=".Security::remove_XSS($my_forum)."&amp;thread=".$myThread."#".Security::remove_XSS($my_post)."\" width=\"100%\"></iframe>";
         }
+
         if (!empty($iframe)) {
             $form->addElement('label', get_lang('Thread'), $iframe);
         }
@@ -2408,7 +2401,7 @@ function store_theme_qualify($user_id, $thread_id, $thread_qualify = 0, $qualify
 
             if ($row[0] == 0) {
                 $sql = "INSERT INTO $table_threads_qualify (c_id, user_id, thread_id,qualify,qualify_user_id,qualify_time,session_id)
-				VALUES (".$course_id.", '".$user_id."','".$thread_id."',".(float) $thread_qualify.", '".$qualify_user_id."','".$qualify_time."','".$session_id."')";
+                VALUES (".$course_id.", '".$user_id."','".$thread_id."',".(float) $thread_qualify.", '".$qualify_user_id."','".$qualify_time."','".$session_id."')";
                 $res = Database::query($sql);
 
                 return $res;
@@ -2539,7 +2532,7 @@ function store_qualify_historical(
 
         // Insert thread_historical.
         $sql1 = "INSERT INTO $table_threads_qualify_log (c_id, user_id, thread_id,qualify,qualify_user_id,qualify_time,session_id)
- 				 VALUES(".$course_id.", '".$user_id."','".$thread_id."',".(float) $row[0].", '".$qualify_user_id."','".$row[1]."','')";
+                 VALUES(".$course_id.", '".$user_id."','".$thread_id."',".(float) $row[0].", '".$qualify_user_id."','".$row[1]."','')";
         Database::query($sql1);
 
         // Update
@@ -2604,8 +2597,8 @@ function store_reply($current_forum, $values)
         // We first store an entry in the forum_post table.
         $sql = "INSERT INTO $table_posts (c_id, post_title, post_text, thread_id, forum_id, poster_id, post_date, post_notification, post_parent_id, visible)
                 VALUES (
-                		".api_get_course_int_id().",
-                		'".Database::escape_string($values['post_title'])."',
+                        ".api_get_course_int_id().",
+                        '".Database::escape_string($values['post_title'])."',
                         '".Database::escape_string(isset($values['post_text']) ? ($values['post_text']) : null)."',
                         '".Database::escape_string($values['thread_id'])."',
                         '".Database::escape_string($values['forum_id'])."',
@@ -2861,9 +2854,9 @@ function store_edit_post($values)
         $sql = "UPDATE $table_threads SET
                 thread_title            ='".Database::escape_string($values['post_title'])."',
                 thread_sticky           ='".Database::escape_string(isset($values['thread_sticky']) ? $values['thread_sticky'] : null)."',".
-                "thread_title_qualify   ='".Database::escape_string($values['calification_notebook_title'])."',".
-                "thread_qualify_max     ='".Database::escape_string($values['numeric_calification'])."',".
-                "thread_weight          ='".Database::escape_string($values['weight_calification'])."'".
+            "thread_title_qualify   ='".Database::escape_string($values['calification_notebook_title'])."',".
+            "thread_qualify_max     ='".Database::escape_string($values['numeric_calification'])."',".
+            "thread_weight          ='".Database::escape_string($values['weight_calification'])."'".
             " WHERE c_id = $course_id AND thread_id='".intval($values['thread_id'])."'";
 
         Database::query($sql);
@@ -2946,9 +2939,9 @@ function display_user_link($user_id, $name, $origin = '', $in_title = '')
 
 /**
  * This function displays the user image from the profile, with a link to the user's details.
- * @param 	int 	User's database ID
- * @param 	str 	User's name
- * @return 	string 	An HTML with the anchor and the image of the user
+ * @param   int     User's database ID
+ * @param   str     User's name
+ * @return  string  An HTML with the anchor and the image of the user
  * @author Julio Montoya <gugli100@gmail.com>
  */
 function display_user_image($user_id, $name, $origin = '')
@@ -3419,7 +3412,7 @@ function move_thread_form()
         $htmlcontent .= '</optgroup>';
     }
     $htmlcontent .= "</select>";
-    $htmlcontent .= '	</div>
+    $htmlcontent .= '   </div>
                     </div>';
 
     $form->addElement('html', $htmlcontent);
@@ -3504,7 +3497,7 @@ function store_move_post($values)
         // Storing a new thread.
         $sql = "INSERT INTO $table_threads (c_id, thread_title, forum_id, thread_poster_id, thread_poster_name, thread_last_post, thread_date)
             VALUES (
-            	".$course_id.",
+                ".$course_id.",
                 '".Database::escape_string($current_post['post_title'])."',
                 '".Database::escape_string($current_post['forum_id'])."',
                 '".Database::escape_string($current_post['poster_id'])."',
@@ -3857,7 +3850,7 @@ function add_forum_attachment_file($file_comment, $last_id)
             // Storing the attachments if any.
             if ($result) {
                 $sql = "INSERT INTO $agenda_forum_attachment (c_id, filename, comment, path, post_id, size)
-                      	VALUES (".api_get_course_int_id().", '$safe_file_name', '$safe_file_comment', '$safe_new_file_name' , '$last_id', '".intval($_FILES['user_upload']['size'])."' )";
+                        VALUES (".api_get_course_int_id().", '$safe_file_name', '$safe_file_comment', '$safe_new_file_name' , '$last_id', '".intval($_FILES['user_upload']['size'])."' )";
                 Database::query($sql);
                 $message .= ' / '.get_lang('FileUploadSucces').'<br />';
 
@@ -4304,8 +4297,8 @@ function get_notifications_of_user($user_id = 0, $force = false)
 
 /**
  * This function counts the number of post inside a thread
- * @param 	int Thread ID
- * @return	int the number of post inside a thread
+ * @param   int Thread ID
+ * @return  int the number of post inside a thread
  * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  * @version octubre 2008, dokeos 1.8
  */
@@ -4324,9 +4317,9 @@ function count_number_of_post_in_thread($thread_id)
 
 /**
  * This function counts the number of post inside a thread user
- * @param 	int thread ID
- * @param 	int user ID
- * @return	int the number of post inside a thread user
+ * @param   int thread ID
+ * @param   int user ID
+ * @return  int the number of post inside a thread user
  */
 function count_number_of_post_for_user_thread($thread_id, $user_id)
 {
@@ -4348,8 +4341,8 @@ function count_number_of_post_for_user_thread($thread_id, $user_id)
 
 /**
  * This function counts the number of user register in course
- * @param 	int Course ID
- * @return	int the number of user register in course
+ * @param   int Course ID
+ * @return  int the number of user register in course
  * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  * @version octubre 2008, dokeos 1.8
  */
@@ -4365,10 +4358,10 @@ function count_number_of_user_in_course($course_id)
 
 /**
  * This function retrieves information of statistical
- * @param 	int Thread ID
- * @param 	int User ID
- * @param 	int Course ID
- * @return	array the information of statistical
+ * @param   int Thread ID
+ * @param   int User ID
+ * @param   int Course ID
+ * @return  array the information of statistical
  * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  * @version octubre 2008, dokeos 1.8
  */
@@ -4385,10 +4378,10 @@ function get_statistical_information($thread_id, $user_id, $course_id)
 
 /**
  * This function return the posts inside a thread from a given user
- * @param 	course code
- * @param 	int Thread ID
- * @param 	int User ID
- * @return	int the number of post inside a thread
+ * @param   course code
+ * @param   int Thread ID
+ * @param   int User ID
+ * @return  int the number of post inside a thread
  * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  * @version octubre 2008, dokeos 1.8
  */
@@ -4542,8 +4535,8 @@ function get_thread_user_post_limit($course_code, $thread_id, $user_id, $limit =
             LEFT JOIN  $table_users users
                 ON posts.poster_id=users.user_id
             WHERE
-            	posts.c_id = $course_id AND
-            	posts.thread_id='".Database::escape_string($thread_id)."'
+                posts.c_id = $course_id AND
+                posts.thread_id='".Database::escape_string($thread_id)."'
                 AND posts.poster_id='".Database::escape_string($user_id)."'
             ORDER BY posts.post_id DESC LIMIT $limit ";
     $result = Database::query($sql);

BIN
main/img/icons/22/view_remove_na.png


BIN
main/img/icons/22/view_tree_na.png


+ 36 - 14
main/inc/ajax/skill.ajax.php

@@ -131,11 +131,21 @@ switch ($action) {
         break;
     case 'get_skills_tree_json':        
         $user_id    = isset($_REQUEST['load_user']) && $_REQUEST['load_user'] == 1 ? api_get_user_id() : 0;
-        $skill_id   = isset($_REQUEST['skill_id']) ? $_REQUEST['skill_id'] : 0;
-        $depth      = isset($_REQUEST['main_depth']) ? $_REQUEST['main_depth'] : 2;        
+        $skill_id   = isset($_REQUEST['skill_id']) ? intval($_REQUEST['skill_id']) : 0;
+        $depth      = isset($_REQUEST['main_depth']) ? intval($_REQUEST['main_depth']) : 2;        
         $all = $skill->get_skills_tree_json($user_id, $skill_id, false, $depth);
         echo $all;
         break;
+    case 'get_user_skill':
+        $userId = api_get_user_id();
+        $skillId = isset($_REQUEST['profile_id']) ? intval($_REQUEST['profile_id']) : 0;
+        $skill = $skill->user_has_skill($userId, $skillId);
+        if ($skill) {
+            echo 1;
+        } else {
+            echo 0;
+        }
+        break;
     case 'get_user_skills':
         $skills = $skill->get_user_skills($user_id, true);        
         Display::display_no_header();        
@@ -143,12 +153,12 @@ switch ($action) {
         echo Display::$global_template->fetch('default/skill/user_skills.tpl');
         break;
     case 'get_gradebook_info':
-        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
+        $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : null;
         $info = $gradebook->get($id);                    
         echo json_encode($info);
         break;  
     case 'load_children':
-        $id             = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
+        $id             = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : null;
         $load_user_data = isset($_REQUEST['load_user_data']) ? $_REQUEST['load_user_data'] : null;
         $skills = $skill->get_children($id, $load_user_data);
         
@@ -156,9 +166,10 @@ switch ($action) {
         foreach ($skills as $skill) {
             if (isset($skill['data']) && !empty($skill['data'])) {
                 $return[$skill['data']['id']] = array(
-                                                    'id'    => $skill['data']['id'],
-                                                    'name'  => $skill['data']['name'], 
-                                                    'passed'=> $skill['data']['passed']);
+                    'id'    => $skill['data']['id'],
+                    'name'  => $skill['data']['name'], 
+                    'passed'=> $skill['data']['passed']
+                );
             }
         }
         $success = true;
@@ -173,15 +184,15 @@ switch ($action) {
         echo json_encode($result);
         break;
     case 'load_direct_parents':
-        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
+        $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : null;
         $skills = $skill->get_direct_parents($id);        
         $return = array();
         foreach($skills as $skill) {
             $return [$skill['data']['id']] = array (
-                                                'id'        => $skill['data']['id'],
-                                                'parent_id' => $skill['data']['parent_id'],
-                                                'name'      => $skill['data']['name']
-                                                );
+                'id'        => $skill['data']['id'],
+                'parent_id' => $skill['data']['parent_id'],
+                'name'      => $skill['data']['name']
+            );
         }
         echo json_encode($return);        
         break;
@@ -273,13 +284,24 @@ switch ($action) {
             }
         }
         break;             
+    case 'get_profile':
+        $skillRelProfile = new SkillRelProfile();
+        $profileId = isset($_REQUEST['profile_id']) ? intval($_REQUEST['profile_id']) : null;
+        $profile = $skillRelProfile->getProfileInfo($profileId);
+        echo json_encode($profile);
+        break; 
     case 'save_profile':
         if (api_is_platform_admin() || api_is_drh()) {
             $skill_profile = new SkillProfile();
             $params = $_REQUEST;
             //$params['skills'] = isset($_SESSION['skills']) ? $_SESSION['skills'] : null; 
             $params['skills'] = $params['skill_id'];
-            $skill_data = $skill_profile->save($params);        
+            $profileId = isset($_REQUEST['profile']) ? intval($_REQUEST['profile']) : null;
+            if ($profileId > 0) {
+                $skill_data = $skill_profile->UpdateProfileInfo($profileId,$params['name'],$params['description']);
+            } else {
+                $skill_data = $skill_profile->save($params);
+            }         
             if (!empty($skill_data)) {
                 echo 1;
             } else {
@@ -298,4 +320,4 @@ switch ($action) {
     default:
         echo '';
 }
-exit;
+exit;

+ 14 - 7
main/inc/ajax/user_manager.ajax.php

@@ -41,7 +41,7 @@ switch ($action) {
             }
         }
         break;
-	case 'search_tags':
+    case 'search_tags':
         if (api_is_anonymous()) {
             echo '';
         } else {
@@ -50,7 +50,7 @@ switch ($action) {
             }
         }
         break;
-	case 'generate_api_key':
+    case 'generate_api_key':
         if (api_is_anonymous()) {
             echo '';
         } else {
@@ -69,7 +69,7 @@ switch ($action) {
             <?php
         }
         break;
-	case 'active_user':
+    case 'active_user':
         if (api_is_platform_admin() && api_global_admin_can_edit_admin($_GET['user_id'])) {
 
             $user_id = intval($_GET['user_id']);
@@ -82,7 +82,6 @@ switch ($action) {
 
                 //Send and email if account is active
                 if ($status == 1) {
-
                     $user_info = api_get_user_info($user_id);
                     $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
                     $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
@@ -96,13 +95,21 @@ switch ($action) {
                     //$emailbody.=get_lang('Problem'). "\n\n". get_lang('Formula');
                     $emailbody.=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');
 
-                     $additional_parameters = array(
+                     $additionalParameters = array(
                         'smsType' => ACCOUNT_APPROVED_CONNECT,
                         'userId' => $user_id
                     );
 
-                    //$result = api_mail($recipient_name, $user_info['mail'], $emailsubject, $emailbody, $sender_name, $email_admin);
-                    $result = api_mail($recipient_name, $user_info['mail'], $emailsubject, $emailbody, $sender_name, $email_admin, '', $additional_parameters);
+                    $result = api_mail(
+                        $recipient_name,
+                        $user_info['mail'],
+                        $emailsubject,
+                        $emailbody,
+                        $sender_name,
+                        $email_admin,
+                        '',
+                        $additionalParameters
+                    );
                     event_system(LOG_USER_ENABLE, LOG_USER_ID, $user_id);
                 } else {
                     event_system(LOG_USER_DISABLE, LOG_USER_ID, $user_id);

+ 147 - 138
main/inc/lib/add_course.lib.inc.php

@@ -334,12 +334,12 @@ function create_course_tables($course_db_name = null) {
     $use_one_db = true;
 
     if ($use_one_db) {
-    	$course_db_name = DB_COURSE_PREFIX;
+        $course_db_name = DB_COURSE_PREFIX;
     } else {
-	    if (!$_configuration['single_database']) {
-	        Database::query("CREATE DATABASE IF NOT EXISTS " . $course_db_name . "" . $charset_clause);
-	    }
-	    $course_db_name = $_configuration['table_prefix'].$course_db_name.$_configuration['db_glue'];
+        if (!$_configuration['single_database']) {
+            Database::query("CREATE DATABASE IF NOT EXISTS " . $course_db_name . "" . $charset_clause);
+        }
+        $course_db_name = $_configuration['table_prefix'].$course_db_name.$_configuration['db_glue'];
     }
 
     //@todo define the backticks inside those table names directly (instead of adding them afterwards)
@@ -399,8 +399,8 @@ function create_course_tables($course_db_name = null) {
     $TABLEQUIZQUESTIONLIST      = $course_db_name . 'quiz_question';
     $TABLEQUIZANSWERSLIST       = $course_db_name . 'quiz_answer';
     $TABLEQUIZQUESTIONOPTION    = $course_db_name . 'quiz_question_option';
-	$table_quiz_question_category    	 = $course_db_name . 'quiz_question_category';
-	$table_quiz_question_rel_category    = $course_db_name . 'quiz_question_rel_category';
+    $table_quiz_question_category        = $course_db_name . 'quiz_question_category';
+    $table_quiz_question_rel_category    = $course_db_name . 'quiz_question_rel_category';
 
     // Dropbox
     $TABLETOOLDROPBOXPOST       = $course_db_name . 'dropbox_post';
@@ -477,7 +477,7 @@ function create_course_tables($course_db_name = null) {
     $add_to_all_tables = ' c_id INT NOT NULL, ';
 
 
-    /*  Announcement tool	*/
+    /*  Announcement tool  */
 
     $sql = "
         CREATE TABLE `".$TABLETOOLANNOUNCEMENTS . "` (
@@ -498,7 +498,7 @@ function create_course_tables($course_db_name = null) {
 
     // Announcement Attachment
     $sql = "CREATE TABLE  `".$TABLETOOLANNOUNCEMENTSATTACHMENT."` (
-			$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL auto_increment,
             path varchar(255) NOT NULL,
             comment text,
@@ -553,12 +553,12 @@ function create_course_tables($course_db_name = null) {
         )" . $charset_clause;
     Database::query($sql);
 
-    /* Forum tool	*/
+    /* Forum tool  */
 
     // Forum Category
     $sql = "
         CREATE TABLE `".$TABLETOOLFORUMCATEGORY . "` (
-		 $add_to_all_tables
+         $add_to_all_tables
          cat_id int NOT NULL auto_increment,
          cat_title varchar(255) NOT NULL default '',
          cat_comment text,
@@ -669,7 +669,7 @@ function create_course_tables($course_db_name = null) {
 
     // Forum Attachment
     $sql = "CREATE TABLE  `".$TABLETOOLFORUMATTACHMENT."` (
-    		  $add_to_all_tables
+              $add_to_all_tables
               id int NOT NULL auto_increment,
               path varchar(255) NOT NULL,
               comment text,
@@ -682,7 +682,7 @@ function create_course_tables($course_db_name = null) {
 
     // Forum notification
     $sql = "CREATE TABLE  `".$TABLETOOLFORUMNOTIFICATION."` (
-    		  $add_to_all_tables
+              $add_to_all_tables
               id int NOT NULL auto_increment,
               user_id int,
               forum_id int,
@@ -696,7 +696,7 @@ function create_course_tables($course_db_name = null) {
 
     // Forum thread qualify :Add table forum_thread_qualify
     $sql = "CREATE TABLE  `".$TABLETOOLFORUMQUALIFY."` (
-    		$add_to_all_tables
+            $add_to_all_tables
             id int unsigned AUTO_INCREMENT,
             user_id int unsigned NOT NULL,
             thread_id int NOT NULL,
@@ -713,7 +713,7 @@ function create_course_tables($course_db_name = null) {
 
     //Forum thread qualify: Add table forum_thread_qualify_historical
     $sql = "CREATE TABLE  `".$TABLETOOLFORUMQUALIFYLOG."` (
-    		$add_to_all_tables
+            $add_to_all_tables
             id int unsigned AUTO_INCREMENT,
             user_id int unsigned NOT NULL,
             thread_id int NOT NULL,
@@ -832,25 +832,25 @@ function create_course_tables($course_db_name = null) {
 
 
     $sql = "CREATE TABLE `".$table_quiz_question_category . "` (
-	  $add_to_all_tables
-	  id int NOT NULL AUTO_INCREMENT,
-	  title varchar(255) NOT NULL,
-	  description text NOT NULL,
-	  PRIMARY KEY (c_id,id)
-	)" . $charset_clause;
+      $add_to_all_tables
+      id int NOT NULL AUTO_INCREMENT,
+      title varchar(255) NOT NULL,
+      description text NOT NULL,
+      PRIMARY KEY (c_id,id)
+    )" . $charset_clause;
     Database::query($sql);
 
 
-	$sql = "CREATE TABLE `".$table_quiz_question_rel_category . "` (
-	  $add_to_all_tables
-	  question_id int NOT NULL,
-	  category_id int NOT NULL,
-	  PRIMARY KEY (c_id,question_id)
+    $sql = "CREATE TABLE `".$table_quiz_question_rel_category . "` (
+      $add_to_all_tables
+      question_id int NOT NULL,
+      category_id int NOT NULL,
+      PRIMARY KEY (c_id,question_id)
     )" . $charset_clause;
     Database::query($sql);
 
 
-    /*        Course description	*/
+    /*        Course description    */
 
     $sql = "
         CREATE TABLE `".$TABLETOOLCOURSEDESC . "` (
@@ -890,7 +890,7 @@ function create_course_tables($course_db_name = null) {
     $sql = "ALTER TABLE `".$tbl_course_homepage . "` ADD INDEX ( session_id ) ";
     Database::query($sql);
 
-    /*        Agenda tool	   */
+    /*        Agenda tool       */
 
     $sql = "
         CREATE TABLE `".$TABLETOOLAGENDA . "` (
@@ -933,7 +933,7 @@ function create_course_tables($course_db_name = null) {
 
     // Agenda Attachment
     $sql = "CREATE TABLE  `".$TABLETOOLAGENDAATTACHMENT."` (
-    			$add_to_all_tables
+                $add_to_all_tables
               id int NOT NULL auto_increment,
               path varchar(255) NOT NULL,
               comment text,
@@ -950,7 +950,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `".$TABLETOOLDOCUMENT . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int unsigned NOT NULL auto_increment,
             path varchar(255) NOT NULL default '',
             comment text,
@@ -988,8 +988,8 @@ function create_course_tables($course_db_name = null) {
         weight float(6,2) UNSIGNED NOT NULL default 0,
         session_id INT UNSIGNED NOT NULL default 0,
         user_id INTEGER  NOT NULL,
-		allow_text_assignment INTEGER NOT NULL DEFAULT 0,
-		contains_file INTEGER NOT NULL DEFAULT 0,
+        allow_text_assignment INTEGER NOT NULL DEFAULT 0,
+        contains_file INTEGER NOT NULL DEFAULT 0,
         PRIMARY KEY (c_id, id)
         )" . $charset_clause;
     Database::query($sql);
@@ -1051,7 +1051,7 @@ function create_course_tables($course_db_name = null) {
     /* Wiki   */
 
     $sql = "CREATE TABLE `".$TABLETOOLWIKI . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         id int NOT NULL auto_increment,
         page_id int NOT NULL default 0,
         reflink varchar(255) NOT NULL default 'index',
@@ -1087,7 +1087,7 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql = "CREATE TABLE `".$TABLEWIKICONF . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         page_id int NOT NULL default 0,
         task text NOT NULL,
         feedback1 text NOT NULL,
@@ -1108,7 +1108,7 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql = "CREATE TABLE `".$TABLEWIKIDISCUSS . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         id int NOT NULL auto_increment,
         publication_id int NOT NULL default 0,
         userc_id int NOT NULL default 0,
@@ -1120,7 +1120,7 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql = "CREATE TABLE `".$TABLEWIKIMAILCUE . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         id int NOT NULL,
         user_id int NOT NULL,
         type text NOT NULL,
@@ -1137,7 +1137,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `".$TABLETOOLONLINECONNECTED . "` (
-		$add_to_all_tables
+        $add_to_all_tables
         user_id int unsigned NOT NULL,
         last_connection datetime NOT NULL default '0000-00-00 00:00:00',
         PRIMARY KEY (c_id, user_id)
@@ -1174,7 +1174,7 @@ function create_course_tables($course_db_name = null) {
     */
 
     Database::query("CREATE TABLE `".$TABLEGROUPS . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         id int unsigned NOT NULL auto_increment,
         name varchar(100) default NULL,
         category_id int unsigned NOT NULL default 0,
@@ -1197,7 +1197,7 @@ function create_course_tables($course_db_name = null) {
     Database::query("ALTER TABLE `".$TABLEGROUPS . "` ADD INDEX ( session_id )");
 
     Database::query("CREATE TABLE `".$TABLEGROUPCATEGORIES . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         id int unsigned NOT NULL auto_increment,
         title varchar(255) NOT NULL default '',
         description text NOT NULL,
@@ -1217,7 +1217,7 @@ function create_course_tables($course_db_name = null) {
         )" . $charset_clause);
 
     Database::query("CREATE TABLE `".$TABLEGROUPUSER . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         id int unsigned NOT NULL auto_increment,
         user_id int unsigned NOT NULL,
         group_id int unsigned NOT NULL default 0,
@@ -1227,7 +1227,7 @@ function create_course_tables($course_db_name = null) {
         )" . $charset_clause);
 
     Database::query("CREATE TABLE `".$TABLEGROUPTUTOR . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         id int NOT NULL auto_increment,
         user_id int NOT NULL,
         group_id int NOT NULL default 0,
@@ -1235,7 +1235,7 @@ function create_course_tables($course_db_name = null) {
         )" . $charset_clause);
 
     Database::query("CREATE TABLE `".$TABLEITEMPROPERTY . "` (
-    	$add_to_all_tables
+        $add_to_all_tables
         id int NOT NULL auto_increment,
         tool varchar(100) NOT NULL default '',
         insert_user_id int unsigned NOT NULL default '0',
@@ -1310,7 +1310,7 @@ function create_course_tables($course_db_name = null) {
         )" . $charset_clause);
 
     $sql = "CREATE TABLE `".$TABLETOOLDROPBOXCATEGORY."` (
-    		  $add_to_all_tables
+              $add_to_all_tables
               cat_id int NOT NULL auto_increment,
               cat_name text NOT NULL,
               received tinyint unsigned NOT NULL default 0,
@@ -1325,7 +1325,7 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql = "CREATE TABLE `".$TABLETOOLDROPBOXFEEDBACK."` (
-    			$add_to_all_tables
+                $add_to_all_tables
               feedback_id int NOT NULL auto_increment,
               file_id int NOT NULL default 0,
               author_user_id int NOT NULL default 0,
@@ -1342,8 +1342,8 @@ function create_course_tables($course_db_name = null) {
     */
 
     $sql = "CREATE TABLE IF NOT EXISTS `$TABLELP` (
-    	$add_to_all_tables
-    	" .
+        $add_to_all_tables
+        " .
         "id             int unsigned        auto_increment," .  // unique ID, generated by MySQL
         "lp_type        int unsigned   not null," .                    // lp_types can be found in the main database's lp_type table
         "name           varchar(255)        not null," .                    // name is the text name of the learning path (e.g. Word 2000)
@@ -1364,22 +1364,22 @@ function create_course_tables($course_db_name = null) {
         "preview_image  varchar(255)        not null default '', " .        // stores the theme of the LP
         "author         varchar(255)        not null default '', " .        // stores the theme of the LP
         "session_id     int unsigned        not null default 0, " .         // the session_id
-		"prerequisite  	int	unsigned 		not null default 0," .			// pre requisite for next lp
-		"hide_toc_frame tinyint 			NOT NULL DEFAULT 0, ".
-        "seriousgame_mode tinyint 			NOT NULL DEFAULT 0, ".
+        "prerequisite   int unsigned        not null default 0," .          // pre requisite for next lp
+        "hide_toc_frame tinyint             NOT NULL DEFAULT 0, ".
+        "seriousgame_mode tinyint           NOT NULL DEFAULT 0, ".
         "use_max_score  int unsigned        not null default 1, " .
         "autolunch      int unsigned        not null default 0, " .          // auto lunch LP
-        "created_on     DATETIME 			NOT NULL DEFAULT '0000-00-00 00:00:00', " .
-        "modified_on    DATETIME 			NOT NULL DEFAULT '0000-00-00 00:00:00', " .
-        "publicated_on  DATETIME 			NOT NULL DEFAULT '0000-00-00 00:00:00', " .
-        "expired_on     DATETIME 			NOT NULL DEFAULT '0000-00-00 00:00:00',
-    	 PRIMARY KEY  (c_id, id)
+        "created_on     DATETIME            NOT NULL DEFAULT '0000-00-00 00:00:00', " .
+        "modified_on    DATETIME            NOT NULL DEFAULT '0000-00-00 00:00:00', " .
+        "publicated_on  DATETIME            NOT NULL DEFAULT '0000-00-00 00:00:00', " .
+        "expired_on     DATETIME            NOT NULL DEFAULT '0000-00-00 00:00:00',
+         PRIMARY KEY  (c_id, id)
         )" . $charset_clause;
 
     Database::query($sql);
 
     $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPVIEW` (
-    	$add_to_all_tables" .
+        $add_to_all_tables" .
         "id             int unsigned        auto_increment," .  // unique ID from MySQL
         "lp_id          int unsigned        not null," .                    // learnpath ID from 'lp'
         "user_id        int unsigned        not null," .                    // user ID from main.user
@@ -1388,7 +1388,7 @@ function create_course_tables($course_db_name = null) {
         "progress       int unsigned        default 0," .
         "session_id     int                 not null default 0,
          PRIMARY KEY  (c_id, id)
-    	)" . $charset_clause; // lp's progress for this user
+        )" . $charset_clause; // lp's progress for this user
 
     Database::query($sql);
 
@@ -1402,8 +1402,8 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPITEM` (
-    	$add_to_all_tables
-    	" .
+        $add_to_all_tables
+        " .
         "id              int unsigned       auto_increment," .  // unique ID from MySQL
         "lp_id          int unsigned        not null," .                    // lp_id from 'lp'
         "item_type      char(32)            not null default 'dokeos_document'," .  // can be dokeos_document, dokeos_chapter or scorm_asset, scorm_sco, scorm_chapter
@@ -1427,7 +1427,7 @@ function create_course_tables($course_db_name = null) {
         "audio          VARCHAR(250),
         PRIMARY KEY  (c_id, id)
 
-    	)" . $charset_clause;                   // contains the audio file that goes with the learning path step
+        )" . $charset_clause;                   // contains the audio file that goes with the learning path step
 
     Database::query($sql);
 
@@ -1438,8 +1438,8 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPITEMVIEW` (
-    	$add_to_all_tables
-    	" .
+        $add_to_all_tables
+        " .
         "id             bigint unsigned auto_increment," .      // unique ID
         "lp_item_id     int unsigned    not null," .                        // item ID (MySQL id)
         "lp_view_id     int unsigned    not null," .                        // learning path view id (attempt)
@@ -1448,7 +1448,7 @@ function create_course_tables($course_db_name = null) {
         "total_time     int unsigned    not null default 0," .              // after how many seconds did he close it?
         "score          float unsigned  not null default 0," .              // score returned by SCORM or other techs
         "status         char(32)        not null default 'not attempted'," .    // status for this item (SCORM)
-		"suspend_data	longtext null default ''," .
+        "suspend_data   longtext null default ''," .
         "lesson_location    text        null default ''," .
         "core_exit      varchar(32)     not null default 'none'," .
         "max_score      varchar(8)      default '',
@@ -1468,7 +1468,7 @@ function create_course_tables($course_db_name = null) {
 
 
     $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPIVINTERACTION`(
-    	 $add_to_all_tables" .
+         $add_to_all_tables" .
         "id             bigint unsigned     auto_increment," .
         "order_id       int unsigned   not null default 0,".           // internal order (0->...) given by Dokeos
         "lp_iv_id       bigint unsigned     not null," .                    // identifier of the related sco_view
@@ -1480,7 +1480,7 @@ function create_course_tables($course_db_name = null) {
         "student_response   text            not null default ''," .         // student response (format depends on type)
         "result         varchar(255)        not null default ''," .         // textual result
         "latency        varchar(16)         not null default ''," .          // time necessary for completion of the interaction
-    	"PRIMARY KEY  (c_id, id)".
+        "PRIMARY KEY  (c_id, id)".
         ")" . $charset_clause;
 
     Database::query($sql);
@@ -1489,7 +1489,7 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPIVOBJECTIVE`(
-    	$add_to_all_tables" .
+        $add_to_all_tables" .
         "id             bigint unsigned     auto_increment," .
         "lp_iv_id       bigint unsigned     not null," .                    // identifier of the related sco_view
         "order_id       int unsigned   not null default 0,".           // internal order (0->...) given by Dokeos
@@ -1498,7 +1498,7 @@ function create_course_tables($course_db_name = null) {
         "score_max      float unsigned      not null default 0," .          // max score
         "score_min      float unsigned      not null default 0," .          // min score
         "status         char(32)            not null default 'not attempted', " . //status, just as sco status
-    	"PRIMARY KEY  (c_id, id) ".
+        "PRIMARY KEY  (c_id, id) ".
         ")" . $charset_clause;
 
     Database::query($sql);
@@ -1527,7 +1527,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_blogs_comments . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             comment_id int NOT NULL AUTO_INCREMENT ,
             title varchar( 250 ) NOT NULL default '',
             comment longtext NOT NULL ,
@@ -1544,7 +1544,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_blogs_posts . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             post_id int NOT NULL AUTO_INCREMENT ,
             title varchar( 250 ) NOT NULL default '',
             full_text longtext NOT NULL ,
@@ -1558,7 +1558,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_blogs_rating . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             rating_id int NOT NULL AUTO_INCREMENT ,
             blog_id int NOT NULL default 0,
             rating_type enum( 'post', 'comment' ) NOT NULL default 'post',
@@ -1572,7 +1572,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_blogs_rel_user . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             blog_id int NOT NULL default 0,
             user_id int NOT NULL default 0,
             PRIMARY KEY ( c_id, blog_id , user_id )
@@ -1582,7 +1582,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_blogs_tasks . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             task_id int NOT NULL AUTO_INCREMENT ,
             blog_id int NOT NULL default 0,
             title varchar( 250 ) NOT NULL default '',
@@ -1596,7 +1596,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_blogs_tasks_rel_user . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             blog_id int NOT NULL default 0,
             user_id int NOT NULL default 0,
             task_id int NOT NULL default 0,
@@ -1607,7 +1607,7 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql ="CREATE TABLE  `" .$tbl_blogs_attachment."` (
-    	  $add_to_all_tables
+          $add_to_all_tables
           id int unsigned NOT NULL auto_increment,
           path varchar(255) NOT NULL COMMENT 'the real filename',
           comment text,
@@ -1623,7 +1623,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_permission_group . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL AUTO_INCREMENT ,
             group_id int NOT NULL default 0,
             tool varchar( 250 ) NOT NULL default '',
@@ -1635,7 +1635,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_permission_user . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL AUTO_INCREMENT ,
             user_id int NOT NULL default 0,
             tool varchar( 250 ) NOT NULL default '',
@@ -1647,7 +1647,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_permission_task . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL AUTO_INCREMENT,
             task_id int NOT NULL default 0,
             tool varchar( 250 ) NOT NULL default '',
@@ -1659,7 +1659,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_role . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             role_id int NOT NULL AUTO_INCREMENT,
             role_name varchar( 250 ) NOT NULL default '',
             role_comment text,
@@ -1671,7 +1671,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_role_group . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL AUTO_INCREMENT,
             role_id int NOT NULL default 0,
             scope varchar( 20 ) NOT NULL default 'course',
@@ -1683,7 +1683,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_role_permissions . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL AUTO_INCREMENT,
             role_id int NOT NULL default 0,
             tool varchar( 250 ) NOT NULL default '',
@@ -1696,7 +1696,7 @@ function create_course_tables($course_db_name = null) {
 
     $sql = "
         CREATE TABLE `" . $tbl_role_user . "` (
-        	$add_to_all_tables
+            $add_to_all_tables
             role_id int NOT NULL default 0,
             scope varchar( 20 ) NOT NULL default 'course',
             user_id int NOT NULL default 0,
@@ -1730,7 +1730,7 @@ function create_course_tables($course_db_name = null) {
     */
 
     $sql = "CREATE TABLE `".$TABLESURVEY."` (
-    		$add_to_all_tables
+            $add_to_all_tables
               survey_id int unsigned NOT NULL auto_increment,
               code varchar(20) default NULL,
               title text default NULL,
@@ -1767,7 +1767,7 @@ function create_course_tables($course_db_name = null) {
     Database::query($sql);
 
     $sql = "CREATE TABLE `".$TABLESURVEYINVITATION."` (
-    		  $add_to_all_tables
+              $add_to_all_tables
               survey_invitation_id int unsigned NOT NULL auto_increment,
               survey_code varchar(20) NOT NULL,
               user varchar(250) NOT NULL,
@@ -1781,7 +1781,7 @@ function create_course_tables($course_db_name = null) {
     $result = Database::query($sql);
 
     $sql = "CREATE TABLE `".$TABLESURVEYQUESTION."` (
-    		  $add_to_all_tables
+              $add_to_all_tables
               question_id int unsigned NOT NULL auto_increment,
               survey_id int unsigned NOT NULL,
               survey_question text NOT NULL,
@@ -1799,7 +1799,7 @@ function create_course_tables($course_db_name = null) {
     $result = Database::query($sql);
 
     $sql ="CREATE TABLE `".$TABLESURVEYQUESTIONOPTION."` (
-    	$add_to_all_tables
+        $add_to_all_tables
       question_option_id int unsigned NOT NULL auto_increment,
       question_id int unsigned NOT NULL,
       survey_id int unsigned NOT NULL,
@@ -1812,7 +1812,7 @@ function create_course_tables($course_db_name = null) {
     $result = Database::query($sql);
 
     $sql = "CREATE TABLE `".$TABLESURVEYANSWER."` (
-    		  $add_to_all_tables
+              $add_to_all_tables
               answer_id int unsigned NOT NULL auto_increment,
               survey_id int unsigned NOT NULL,
               question_id int unsigned NOT NULL,
@@ -1824,7 +1824,7 @@ function create_course_tables($course_db_name = null) {
     $result = Database::query($sql);
 
     $sql = "CREATE TABLE `".$TABLESURVEYGROUP."` (
-				$add_to_all_tables
+                $add_to_all_tables
               id int unsigned NOT NULL auto_increment,
               name varchar(20) NOT NULL,
               description varchar(255) NOT NULL,
@@ -1835,7 +1835,7 @@ function create_course_tables($course_db_name = null) {
 
     // Table glosary
     $sql = "CREATE TABLE `".$TBL_GLOSSARY."` (
-    		  $add_to_all_tables
+              $add_to_all_tables
               glossary_id int unsigned NOT NULL auto_increment,
               name varchar(255) NOT NULL,
               description text not null,
@@ -1850,7 +1850,7 @@ function create_course_tables($course_db_name = null) {
 
     // Table notebook
     $sql = "CREATE TABLE `".$TBL_NOTEBOOK."` (
-    		  $add_to_all_tables
+              $add_to_all_tables
               notebook_id int unsigned NOT NULL auto_increment,
               user_id int unsigned NOT NULL,
               course varchar(40) not null,
@@ -1869,7 +1869,7 @@ function create_course_tables($course_db_name = null) {
     // Attendance table
     $sql = "
         CREATE TABLE `".$TBL_ATTENDANCE."` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL auto_increment,
             name text NOT NULL,
             description TEXT NULL,
@@ -1892,7 +1892,7 @@ function create_course_tables($course_db_name = null) {
     // Attendance sheet table
     $sql = "
         CREATE TABLE `".$TBL_ATTENDANCE_SHEET."` (
-        	$add_to_all_tables
+            $add_to_all_tables
             user_id int NOT NULL,
             attendance_calendar_id int NOT NULL,
             presence tinyint NOT NULL DEFAULT 0,
@@ -1906,7 +1906,7 @@ function create_course_tables($course_db_name = null) {
     // Attendance calendar table
     $sql = "
         CREATE TABLE `".$TBL_ATTENDANCE_CALENDAR."` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL auto_increment,
             attendance_id int NOT NULL ,
             date_time datetime NOT NULL default '0000-00-00 00:00:00',
@@ -1924,7 +1924,7 @@ function create_course_tables($course_db_name = null) {
     // Attendance result table
     $sql = "
         CREATE TABLE `".$TBL_ATTENDANCE_RESULT."` (
-        	$add_to_all_tables
+            $add_to_all_tables
             id int NOT NULL auto_increment,
             user_id int NOT NULL,
             attendance_id int NOT NULL,
@@ -1941,7 +1941,7 @@ function create_course_tables($course_db_name = null) {
 
     // attendance sheet log table
     $sql = "CREATE TABLE `".$TBL_ATTENDANCE_SHEET_LOG."` (
-    			  $add_to_all_tables
+                  $add_to_all_tables
                   id int  NOT NULL auto_increment,
                   attendance_id int  NOT NULL DEFAULT 0,
                   lastedit_date datetime  NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -1955,7 +1955,7 @@ function create_course_tables($course_db_name = null) {
 
     // Thematic table
     $sql = "CREATE TABLE `".$TBL_THEMATIC."` (
-    			$add_to_all_tables
+                $add_to_all_tables
                 id int NOT NULL auto_increment,
                 title varchar(255) NOT NULL,
                 content text NULL,
@@ -1971,7 +1971,7 @@ function create_course_tables($course_db_name = null) {
 
     // thematic plan table
     $sql = "CREATE TABLE `".$TBL_THEMATIC_PLAN."` (
-            	$add_to_all_tables
+                $add_to_all_tables
                 id int NOT NULL auto_increment,
                 thematic_id int NOT NULL,
                 title varchar(255) NOT NULL,
@@ -1987,7 +1987,7 @@ function create_course_tables($course_db_name = null) {
     // thematic advance table
     $sql = "
             CREATE TABLE `".$TBL_THEMATIC_ADVANCE."` (
-            	$add_to_all_tables
+                $add_to_all_tables
                 id int NOT NULL auto_increment,
                 thematic_id int NOT NULL,
                 attendance_id int NOT NULL DEFAULT 0,
@@ -2078,10 +2078,10 @@ function sort_pictures($files, $type) {
 
 /**
  * Fills the course repository with some example content.
- * @param string Course directory name (without prefix/suffix). eg "ABC"
- * @param bool Whether we want to fill it with example content or not
- * @return array The (structured) list of files created
- * @version	 1.2
+ * @param   string Course directory name (without prefix/suffix). eg "ABC"
+ * @param   bool Whether we want to fill it with example content or not
+ * @return  array The (structured) list of files created
+ * @version 1.2
  * @deprecated this function has been merged into the fill_db_course
  * @assert (null, null) === false
  */
@@ -2290,31 +2290,31 @@ function fill_db_course($course_id, $course_repository, $language, $fill_with_ex
     $course_id = intval($course_id);
 
     if (empty($course_id)) {
-    	return false;
+        return false;
     }
     $now = api_get_utc_datetime(time());
 
-    $tbl_course_homepage 	= Database::get_course_table(TABLE_TOOL_LIST);
-    $TABLEINTROS 			= Database::get_course_table(TABLE_TOOL_INTRO);
-    $TABLEGROUPCATEGORIES 	= Database::get_course_table(TABLE_GROUP_CATEGORY);
-    $TABLEITEMPROPERTY 		= Database::get_course_table(TABLE_ITEM_PROPERTY);
-    $TABLETOOLAGENDA 		= Database::get_course_table(TABLE_AGENDA);
+    $tbl_course_homepage    = Database::get_course_table(TABLE_TOOL_LIST);
+    $TABLEINTROS            = Database::get_course_table(TABLE_TOOL_INTRO);
+    $TABLEGROUPCATEGORIES   = Database::get_course_table(TABLE_GROUP_CATEGORY);
+    $TABLEITEMPROPERTY      = Database::get_course_table(TABLE_ITEM_PROPERTY);
+    $TABLETOOLAGENDA        = Database::get_course_table(TABLE_AGENDA);
     $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
-    $TABLETOOLDOCUMENT 		= Database::get_course_table(TABLE_DOCUMENT);
-    $TABLETOOLLINK 			= Database::get_course_table(TABLE_LINK);
-    $TABLEQUIZ 				= Database::get_course_table(TABLE_QUIZ_TEST);
-    $TABLEQUIZQUESTION 		= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
-    $TABLEQUIZQUESTIONLIST 	= Database::get_course_table(TABLE_QUIZ_QUESTION);
-    $TABLEQUIZANSWERSLIST 	= Database::get_course_table(TABLE_QUIZ_ANSWER);
-    $TABLESETTING 			= Database::get_course_table(TABLE_COURSE_SETTING);
-
-    $TABLEFORUMCATEGORIES 	= Database::get_course_table(TABLE_FORUM_CATEGORY);
-    $TABLEFORUMS 			= Database::get_course_table(TABLE_FORUM);
-    $TABLEFORUMTHREADS 		= Database::get_course_table(TABLE_FORUM_THREAD);
-    $TABLEFORUMPOSTS 		= Database::get_course_table(TABLE_FORUM_POST);
-    $TABLEGRADEBOOK 		= Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
-    $TABLEGRADEBOOKLINK		= Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
-    $TABLEGRADEBOOKCERT		= Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
+    $TABLETOOLDOCUMENT      = Database::get_course_table(TABLE_DOCUMENT);
+    $TABLETOOLLINK          = Database::get_course_table(TABLE_LINK);
+    $TABLEQUIZ              = Database::get_course_table(TABLE_QUIZ_TEST);
+    $TABLEQUIZQUESTION      = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
+    $TABLEQUIZQUESTIONLIST  = Database::get_course_table(TABLE_QUIZ_QUESTION);
+    $TABLEQUIZANSWERSLIST   = Database::get_course_table(TABLE_QUIZ_ANSWER);
+    $TABLESETTING           = Database::get_course_table(TABLE_COURSE_SETTING);
+
+    $TABLEFORUMCATEGORIES   = Database::get_course_table(TABLE_FORUM_CATEGORY);
+    $TABLEFORUMS            = Database::get_course_table(TABLE_FORUM);
+    $TABLEFORUMTHREADS      = Database::get_course_table(TABLE_FORUM_THREAD);
+    $TABLEFORUMPOSTS        = Database::get_course_table(TABLE_FORUM_POST);
+    $TABLEGRADEBOOK         = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
+    $TABLEGRADEBOOKLINK     = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+    $TABLEGRADEBOOKCERT     = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
 
     include api_get_path(SYS_CODE_PATH).'lang/english/create_course.inc.php';
     $file_to_include = api_get_path(SYS_CODE_PATH).'lang/'.$language.'/create_course.inc.php';
@@ -2405,7 +2405,7 @@ function fill_db_course($course_id, $course_repository, $language, $fill_with_ex
     /* Group tool */
 
     Database::query("INSERT INTO $TABLEGROUPCATEGORIES  (c_id,  id , title , description , max_student , self_reg_allowed , self_unreg_allowed , groups_per_user , display_order )
-    		VALUES ($course_id, '2', '".lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
+            VALUES ($course_id, '2', '".lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
 
     /*    Example Material  */
     global $language_interface;
@@ -2600,7 +2600,7 @@ function fill_db_course($course_id, $course_repository, $language, $fill_with_ex
         // We need to add the item properties too!
         $insert_id = Database :: insert_id();
         $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, '" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)";
+                VALUES ($course_id, '" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)";
         Database::query($sql);
 
         $add_wikipedia_link_sql = "INSERT INTO $TABLETOOLLINK  (c_id, url, title, description, category_id, display_order, on_homepage, target)
@@ -2615,13 +2615,13 @@ function fill_db_course($course_id, $course_repository, $language, $fill_with_ex
         /* Annoucement tool */
 
         $sql = "INSERT INTO $TABLETOOLANNOUNCEMENTS  (c_id, title,content,end_date,display_order,email_sent)
-        		VALUES ($course_id, '".lang2db(get_lang('AnnouncementExampleTitle')) . "', '".lang2db(get_lang('AnnouncementEx')) . "', NOW(), '1','0')";
+                VALUES ($course_id, '".lang2db(get_lang('AnnouncementExampleTitle')) . "', '".lang2db(get_lang('AnnouncementEx')) . "', NOW(), '1','0')";
         Database::query($sql);
 
         // We need to add the item properties too!
         $insert_id = Database :: insert_id();
         $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, '" . TOOL_ANNOUNCEMENT . "',1,NOW(),NOW(),$insert_id,'AnnouncementAdded',1,0,NULL,1)";
+                VALUES ($course_id, '" . TOOL_ANNOUNCEMENT . "',1,NOW(),NOW(),$insert_id,'AnnouncementAdded',1,0,NULL,1)";
         Database::query($sql);
 
         /* Introduction text */
@@ -2652,7 +2652,7 @@ function fill_db_course($course_id, $course_repository, $language, $fill_with_ex
           ' "'.$html.'", "1", "0", "0", "1", "0")');
         $exercise_id = Database :: insert_id();
         Database::query("INSERT INTO $TABLEQUIZQUESTIONLIST  (c_id, id, question, description, ponderation, position, type, picture, level)
-        				VALUES ( '.$course_id.', '1', '".lang2db(get_lang('SocraticIrony')) . "', '".lang2db(get_lang('ManyAnswers')) . "', '10', '1', '2','',1)");
+                        VALUES ( '.$course_id.', '1', '".lang2db(get_lang('SocraticIrony')) . "', '".lang2db(get_lang('ManyAnswers')) . "', '10', '1', '2','',1)");
         Database::query("INSERT INTO $TABLEQUIZQUESTION  (c_id, question_id, exercice_id, question_order) VALUES ('.$course_id.', 1,1,1)");
 
         /* Forum tool */
@@ -2660,19 +2660,19 @@ function fill_db_course($course_id, $course_repository, $language, $fill_with_ex
         Database::query("INSERT INTO $TABLEFORUMCATEGORIES VALUES ($course_id, 1,'".lang2db(get_lang('ExampleForumCategory'))."', '', 1, 0, 0)");
         $insert_id = Database :: insert_id();
         Database::query("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, 'forum_category',1,NOW(),NOW(),$insert_id,'ForumCategoryAdded',1,0,NULL,1)");
+                        VALUES ($course_id, 'forum_category',1,NOW(),NOW(),$insert_id,'ForumCategoryAdded',1,0,NULL,1)");
 
         Database::query("INSERT INTO $TABLEFORUMS (c_id, forum_title, forum_comment, forum_threads,forum_posts,forum_last_post,forum_category, allow_anonymous, allow_edit,allow_attachments, allow_new_threads,default_view,forum_of_group,forum_group_public_private, forum_order,locked,session_id )
-        				VALUES ($course_id, '".lang2db(get_lang('ExampleForum'))."', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)");
+                        VALUES ($course_id, '".lang2db(get_lang('ExampleForum'))."', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)");
         $insert_id = Database :: insert_id();
         Database::query("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, '".TOOL_FORUM."', 1,NOW(),NOW(),$insert_id,'ForumAdded',1,0,NULL,1)");
+                         VALUES ($course_id, '".TOOL_FORUM."', 1,NOW(),NOW(),$insert_id,'ForumAdded',1,0,NULL,1)");
 
         Database::query("INSERT INTO $TABLEFORUMTHREADS (c_id, thread_id, thread_title, forum_id, thread_replies, thread_poster_id, thread_poster_name, thread_views, thread_last_post, thread_date, locked, thread_qualify_max, session_id)
-        				VALUES ($course_id, 1, '".lang2db(get_lang('ExampleThread'))."', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)");
+                        VALUES ($course_id, 1, '".lang2db(get_lang('ExampleThread'))."', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)");
         $insert_id = Database :: insert_id();
         Database::query("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, 'forum_thread',1,NOW(),NOW(),$insert_id,'ForumThreadAdded',1,0,NULL,1)");
+                        VALUES ($course_id, 'forum_thread',1,NOW(),NOW(),$insert_id,'ForumThreadAdded',1,0,NULL,1)");
 
         Database::query("INSERT INTO $TABLEFORUMPOSTS VALUES ($course_id, 1, '".lang2db(get_lang('ExampleThread'))."', '".lang2db(get_lang('ExampleThreadContent'))."', 1, 1, 1, '', NOW(), 0, 0, 1)");
 
@@ -2759,8 +2759,8 @@ function register_course($params)
     $teachers           = isset($params['teachers']) ? $params['teachers'] : null;
     $status             = isset($params['status']) ? $params['status'] : null;
 
-    $TABLECOURSE		 	= Database :: get_main_table(TABLE_MAIN_COURSE);
-    $TABLECOURSUSER 		= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+    $TABLECOURSE            = Database :: get_main_table(TABLE_MAIN_COURSE);
+    $TABLECOURSUSER         = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 
     $ok_to_register_course = true;
 
@@ -2833,7 +2833,7 @@ function register_course($params)
                     unsubscribe     = '".intval($unsubscribe) . "',
                     visual_code     = '".Database :: escape_string($visual_code) . "'";
         Database::query($sql);
-		$course_id  = Database::insert_id();
+        $course_id  = Database::insert_id();
 
         if ($course_id) {
             $sort = api_max_sort_value('0', api_get_user_id());
@@ -2915,16 +2915,25 @@ function register_course($params)
                 $message .= get_lang('Language').' '.$course_language;
 
                 $userInfo = api_get_user_info($user_id);
-                $additional_parameters = array(
+                $additionalParameters = array(
                     'smsType' => NEW_COURSE_BEEN_CREATED,
                     'userId' => $user_id,
                     'courseName' => $title,
                     'creatorUsername' => $userInfo['username']
                 );
 
-                //@api_mail($recipient_name, $recipient_email, $subject, $message, $siteName, $recipient_email);
-                api_mail_html($recipient_name, $recipient_email, $subject, $message,
-                    $siteName, $recipient_email, null, null, null, $additional_parameters);
+                api_mail_html(
+                    $recipient_name,
+                    $recipient_email,
+                    $subject,
+                    $message,
+                    $siteName,
+                    $recipient_email,
+                    null,
+                    null,
+                    null,
+                    $additionalParameters
+                );
             }
         }
     }

+ 23 - 7
main/inc/lib/course.lib.php

@@ -2455,16 +2455,25 @@ class CourseManager
             $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');
 
-            $additional_parameters = array(
+            $additionalParameters = array(
                 'smsType' => NEW_USER_SUBSCRIBED_COURSE,
                 'userId' => $tutor['user_id'],
                 'userUsername' => $student['username'],
                 'courseCode' => $course_code
             );
 
-            //@api_mail($recipient_name, $emailto, $emailsubject, $emailbody, $sender_name,$email_admin);
-            api_mail_html($recipient_name, $emailto, $emailsubject, $emailbody,
-                $sender_name, $email_admin, null, null, null, $additional_parameters);
+            api_mail_html(
+                $recipient_name,
+                $emailto,
+                $emailsubject,
+                $emailbody,
+                $sender_name,
+                $email_admin,
+                null,
+                null,
+                null,
+                $additionalParameters
+            );
         }
     }
 
@@ -4474,7 +4483,8 @@ class CourseManager
      * @return int Number of courses
      */
     public static function countAvailableCourses($accessUrlId = null)
-    {
+    {   
+        global $_configuration;
         $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
         $tableCourseRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
         $specialCourseList = self::get_special_course_list();
@@ -4483,9 +4493,15 @@ class CourseManager
         if (!empty($specialCourseList)) {
             $withoutSpecialCourses = ' AND c.code NOT IN ("'.implode('","',$specialCourseList).'")';
         }
-
+        if (isset($_configuration['course_catalog_hide_private'])) {
+            if ($_configuration['course_catalog_hide_private'] == true) {
+                $courseInfo = api_get_course_info();
+                $courseVisibility = $courseInfo['visibility'];
+                $visibilityCondition = ' AND c.visibility <> 1';
+            }
+        }
         if (!empty($accessUrlId) && $accessUrlId == intval($accessUrlId)) {
-            $sql = "SELECT count(id) FROM $tableCourse c, $tableCourseRelAccessUrl u WHERE c.code = u.course_code AND u.access_url_id = $accessUrlId AND c.visibility != 0 AND c.visibility != 4 $withoutSpecialCourses";
+            $sql = "SELECT count(id) FROM $tableCourse c, $tableCourseRelAccessUrl u WHERE c.code = u.course_code AND u.access_url_id = $accessUrlId AND c.visibility != 0 AND c.visibility != 4 $withoutSpecialCourses $visibilityCondition";
         }
         $res = Database::query($sql);
         $row = Database::fetch_row($res);

+ 27 - 11
main/inc/lib/course_category.lib.php

@@ -485,7 +485,8 @@ function browseCourseCategories()
  * @return int
  */
 function countCoursesInCategory($category_code="")
-{
+{   
+    global $_configuration;
     $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $TABLE_COURSE_FIELD = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
     $TABLE_COURSE_FIELD_VALUE = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
@@ -508,9 +509,16 @@ function countCoursesInCategory($category_code="")
     if (!empty($special_course_list)) {
         $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
     }
-
+    
+    if (isset($_configuration['course_catalog_hide_private'])) {
+        if ($_configuration['course_catalog_hide_private'] == true) {
+            $courseInfo = api_get_course_info();
+            $courseVisibility = $courseInfo['visibility'];
+            $visibilityCondition = ' AND course.visibility <> 1';
+        }
+    }
     $sql = "SELECT * FROM $tbl_course
-            WHERE visibility != '0' AND visibility != '4' AND category_code" . "='" . $category_code . "'" . $without_special_courses;
+            WHERE visibility != '0' AND visibility != '4' AND category_code" . "='" . $category_code . "'" . $without_special_courses. $visibilityCondition;
     // Showing only the courses of the current portal access_url_id.
 
     if (api_is_multiple_url_enabled()) {
@@ -520,7 +528,7 @@ function countCoursesInCategory($category_code="")
             $sql = "SELECT * FROM $tbl_course as course
                     INNER JOIN $tbl_url_rel_course as url_rel_course
                     ON (url_rel_course.course_code=course.code)
-                    WHERE access_url_id = $url_access_id AND course.visibility != '0' AND course.visibility != '4' AND category_code" . "='" . $category_code . "'" . $without_special_courses;
+                    WHERE access_url_id = $url_access_id AND course.visibility != '0' AND course.visibility != '4' AND category_code" . "='" . $category_code . "'" . $without_special_courses. $visibilityCondition;
         }
     }
     return Database::num_rows(Database::query($sql));
@@ -532,7 +540,8 @@ function countCoursesInCategory($category_code="")
  * @return array
  */
 function browseCoursesInCategory($category_code, $random_value = null)
-{
+{   
+    global $_configuration;
     $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
     $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
@@ -555,7 +564,14 @@ function browseCoursesInCategory($category_code, $random_value = null)
     if (!empty($special_course_list)) {
         $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
     }
+    if (isset($_configuration['course_catalog_hide_private'])) {
 
+        if ($_configuration['course_catalog_hide_private'] == true) {
+            $courseInfo = api_get_course_info();
+            $courseVisibility = $courseInfo['visibility'];
+            $visibilityCondition = ' AND course.visibility <> 1';
+        }
+    }
     if (!empty($random_value)) {
         $random_value = intval($random_value);
 
@@ -578,11 +594,11 @@ function browseCoursesInCategory($category_code, $random_value = null)
                         ON (url_rel_course.course_code=course.code)
                         WHERE   access_url_id = $url_access_id AND
                                 RAND()*$num_records< $random_value
-                                $without_special_courses
+                                $without_special_courses $visibilityCondition
                      ORDER BY RAND() LIMIT 0, $random_value";
         } else {
             $sql = "SELECT id FROM $tbl_course course
-                    WHERE RAND()*$num_records< $random_value $without_special_courses
+                    WHERE RAND()*$num_records< $random_value $without_special_courses $visibilityCondition
                     ORDER BY RAND() LIMIT 0, $random_value";
         }
 
@@ -599,12 +615,12 @@ function browseCoursesInCategory($category_code, $random_value = null)
     } else {
         $category_code = Database::escape_string($category_code);
         if (empty($category_code) || $category_code == "ALL") {
-            $sql = "SELECT * FROM $tbl_course WHERE 1=1 $without_special_courses ORDER BY title ";
+            $sql = "SELECT * FROM $tbl_course WHERE 1=1 $without_special_courses $visibilityCondition ORDER BY title ";
         } else {
             if ($category_code == 'NONE') {
                 $category_code = '';
             }
-            $sql = "SELECT * FROM $tbl_course WHERE category_code='$category_code' $without_special_courses ORDER BY title ";
+            $sql = "SELECT * FROM $tbl_course WHERE category_code='$category_code' $without_special_courses $visibilityCondition ORDER BY title ";
         }
 
         //showing only the courses of the current Chamilo access_url_id
@@ -614,12 +630,12 @@ function browseCoursesInCategory($category_code, $random_value = null)
             if ($category_code != "ALL") {
                 $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course
                     ON (url_rel_course.course_code=course.code)
-                    WHERE access_url_id = $url_access_id AND category_code='$category_code' $without_special_courses
+                    WHERE access_url_id = $url_access_id AND category_code='$category_code' $without_special_courses $visibilityCondition
                     ORDER BY title";    
             } else{
                 $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course
                     ON (url_rel_course.course_code=course.code)
-                    WHERE access_url_id = $url_access_id $without_special_courses
+                    WHERE access_url_id = $url_access_id $without_special_courses $visibilityCondition
                     ORDER BY title";
             }
             

+ 65 - 15
main/inc/lib/course_request.lib.php

@@ -146,14 +146,24 @@ class CourseRequestManager {
         $recipient_email_admin = get_setting('emailAdministrator');
 
         $userInfo = api_get_user_info($user_id);
-        $additional_parameters = array(
+        $additionalParameters = array(
             'smsType' => NEW_COURSE_SUGGESTED_TEACHER,
             'userId' => $user_id,
             'userUsername' => $userInfo['username']
         );
 
-        api_mail_html($recipient_name_admin, $recipient_email_admin, $email_subject, $email_body_admin, 
-            $sender_name_teacher, $sender_email_teacher, null, null, null, $additional_parameters);
+        api_mail_html(
+            $recipient_name_admin,
+            $recipient_email_admin,
+            $email_subject,
+            $email_body_admin,
+            $sender_name_teacher,
+            $sender_email_teacher,
+            null,
+            null,
+            null,
+            $additionalParameters
+        );
 
         // Sending an e-mail to the requestor.
 
@@ -173,14 +183,24 @@ class CourseRequestManager {
         $recipient_name_teacher = $sender_name_teacher;
         $recipient_email_teacher = $sender_email_teacher;
 
-        $additional_parameters = array(
+        $additionalParameters = array(
             'smsType' => COURSE_OPENING_REQUEST_CODE_REGISTERED,
             'userId' => $user_info['user_id'],
             'courseCode' => $wanted_code
         );
 
-        api_mail_html($recipient_name_teacher, $recipient_email_teacher, $email_subject, $email_body_teacher, 
-            $sender_name_admin, $sender_email_admin, null, null, null, $additional_parameters);
+        api_mail_html(
+            $recipient_name_teacher,
+            $recipient_email_teacher,
+            $email_subject,
+            $email_body_teacher,
+            $sender_name_admin,
+            $sender_email_admin,
+            null,
+            null,
+            null,
+            $additionalParameters
+        );
 
         return $last_insert_id;
 
@@ -431,14 +451,24 @@ class CourseRequestManager {
             $recipient_email = $user_info['mail'];
             $extra_headers = 'Bcc: '.$sender_email;
 
-            $additional_parameters = array(
+            $additionalParameters = array(
                 'smsType' => COURSE_OPENING_REQUEST_CODE_APPROVED,
                 'userId' => $user_id,
                 'courseCode' => $course_info['code']
             );
 
-            api_mail_html($recipient_name, $recipient_email, $email_subject, $email_body, 
-                $sender_name, $sender_email, null, null, null, $additional_parameters);
+            api_mail_html(
+                $recipient_name,
+                $recipient_email,
+                $email_subject,
+                $email_body,
+                $sender_name,
+                $sender_email,
+                null,
+                null,
+                null,
+                $additionalParameters
+            );
 
             return $course_info['code'];
         }
@@ -503,14 +533,24 @@ class CourseRequestManager {
         $recipient_email = $user_info['mail'];
         $extra_headers = 'Bcc: '.$sender_email;
 
-        $additional_parameters = array(
+        $additionalParameters = array(
             'smsType' => COURSE_OPENING_REQUEST_CODE_REJECTED,
             'userId' => $user_id,
             'courseCode' => $code
         );
 
-        api_mail_html($recipient_name, $recipient_email, $email_subject, $email_body, 
-            $sender_name, $sender_email, null, null, null, $additional_parameters);
+        api_mail_html(
+            $recipient_name,
+            $recipient_email,
+            $email_subject,
+            $email_body,
+            $sender_name,
+            $sender_email,
+            null,
+            null,
+            null,
+            $additionalParameters
+        );
 
         return true;
     }
@@ -573,14 +613,24 @@ class CourseRequestManager {
         $recipient_email = $user_info['mail'];
         $extra_headers = 'Bcc: '.$sender_email;
 
-        $additional_parameters = array(
+        $additionalParameters = array(
             'smsType' => COURSE_OPENING_REQUEST_CODE,
             'userId' => $user_id,
             'courseCode' => $code
         );
 
-        $result = api_mail_html($recipient_name, $recipient_email, $email_subject, $email_body, 
-            $sender_name, $sender_email, null, null, null, $additional_parameters);
+        $result = api_mail_html(
+            $recipient_name,
+            $recipient_email,
+            $email_subject,
+            $email_body,
+            $sender_name,
+            $sender_email,
+            null,
+            null,
+            null,
+            $additionalParameters
+        );
 
         if (!$result) {
             return false;

+ 164 - 164
main/inc/lib/database.lib.php

@@ -34,7 +34,7 @@ class Database
     */
 
     /**
-     *	Returns the name of the main database.
+     *  Returns the name of the main database.
      */
     public static function get_main_database()
     {
@@ -43,7 +43,7 @@ class Database
     }
 
     /**
-     *	Returns the name of the statistics database.
+     *  Returns the name of the statistics database.
      *  @todo use main_database
      */
     public static function get_statistic_database()
@@ -52,7 +52,7 @@ class Database
     }
 
     /**
-     *	Returns the name of the database where all the personal stuff of the user is stored
+     *  Returns the name of the database where all the personal stuff of the user is stored
      *  @todo use main_database
      */
     public static function get_user_personal_database()
@@ -61,7 +61,7 @@ class Database
     }
 
     /**
-     *	Returns the name of the current course database.
+     *  Returns the name of the current course database.
      *  @return    mixed   Glued database name of false if undefined
      */
     public static function get_current_course_database()
@@ -75,7 +75,7 @@ class Database
     }
 
     /**
-     *	Returns the glued name of the current course database.
+     *  Returns the glued name of the current course database.
      *  @return    mixed   Glued database name of false if undefined
      */
     public static function get_current_course_glued_database()
@@ -88,11 +88,11 @@ class Database
     }
 
     /**
-     *	The glue is the string needed between database and table.
-     *	The trick is: in multiple databases, this is a period (with backticks).
-     *	In single database, this can be e.g. an underscore so we just fake
-     *	there are multiple databases and the code can be written independent
-     *	of the single / multiple database setting.
+     *  The glue is the string needed between database and table.
+     *  The trick is: in multiple databases, this is a period (with backticks).
+     *  In single database, this can be e.g. an underscore so we just fake
+     *  there are multiple databases and the code can be written independent
+     *  of the single / multiple database setting.
      */
     public static function get_database_glue()
     {
@@ -101,11 +101,11 @@ class Database
     }
 
     /**
-     *	Returns the database prefix.
-     *	All created COURSE databases are prefixed with this string.
+     *  Returns the database prefix.
+     *  All created COURSE databases are prefixed with this string.
      *
-     *	TIP: This can be convenient if you have multiple system installations
-     *	on the same physical server.
+     *  TIP: This can be convenient if you have multiple system installations
+     *  on the same physical server.
      */
     public static function get_database_name_prefix()
     {
@@ -114,10 +114,10 @@ class Database
     }
 
     /**
-     *	Returns the course table prefix for single database.
-     *	Not certain exactly when this is used.
-     *	Do research.
-     *	It's used in local.inc.php.
+     *  Returns the course table prefix for single database.
+     *  Not certain exactly when this is used.
+     *  Do research.
+     *  It's used in local.inc.php.
      */
     public static function get_course_table_prefix()
     {
@@ -177,7 +177,7 @@ class Database
             echo "<h3>Dev Message: get_course_table() doesn't have a 2nd parameter</h3>";
             //exit;
         }
-    	return self::format_table_name(self::get_main_database(), DB_COURSE_PREFIX.$short_table_name);
+        return self::format_table_name(self::get_main_database(), DB_COURSE_PREFIX.$short_table_name);
         //return self::format_glued_course_table_name(self::fix_database_parameter($database_name), $short_table_name);
     }
 
@@ -218,8 +218,8 @@ class Database
     */
 
     /**
-     *	@return a list (array) of all courses.
-     * 	@todo shouldn't this be in the course.lib.php script?
+     *  @return a list (array) of all courses.
+     *  @todo shouldn't this be in the course.lib.php script?
      */
     public static function get_course_list()
     {
@@ -228,10 +228,10 @@ class Database
     }
 
     /**
-     *	Returns an array with all database fields for the specified course.
+     *  Returns an array with all database fields for the specified course.
      *
-     *	@param string The real (system) course code (main course table ID)
-     * 	@todo shouldn't this be in the course.lib.php script?
+     *  @param string The real (system) course code (main course table ID)
+     *  @todo shouldn't this be in the course.lib.php script?
      */
     public static function get_course_info($course_code)
     {
@@ -278,19 +278,19 @@ class Database
     }
 
     /**
-     *	This method creates an abstraction layer between database field names
-     *	and field names expected in code.
+     *  This method creates an abstraction layer between database field names
+     *  and field names expected in code.
      *
-     *	This approach helps when changing database names.
-     *	It's also useful now to get rid of the 'franglais'.
+     *  This approach helps when changing database names.
+     *  It's also useful now to get rid of the 'franglais'.
      *
-     *	@todo	add more array entries to abstract course info from field names
-     *	@author	Roan Embrechts
+     *  @todo   add more array entries to abstract course info from field names
+     *  @author Roan Embrechts
      *
-     * 	@todo What's the use of this method. I think this is better removed.
-     * 		  There should be consistency in the variable names and the
+     *  @todo What's the use of this method. I think this is better removed.
+     *        There should be consistency in the variable names and the
      *            use throughout the scripts
-     * 		  for the database name we should consistently use or db_name
+     *        for the database name we should consistently use or db_name
      *            or database (db_name probably being the better one)
      */
     public static function generate_abstract_course_field_names($result_array)
@@ -332,25 +332,25 @@ class Database
     }
 
     /**
-     *	This method creates an abstraction layer between database field names
-     *	and field names expected in code.
+     *  This method creates an abstraction layer between database field names
+     *  and field names expected in code.
      *
-     *	This helps when changing database names.
-     *	It's also useful now to get rid of the 'franglais'.
+     *  This helps when changing database names.
+     *  It's also useful now to get rid of the 'franglais'.
      *
-     *	@todo add more array entries to abstract user info from field names
-     *	@author Roan Embrechts
-     *	@author Patrick Cool
+     *  @todo add more array entries to abstract user info from field names
+     *  @author Roan Embrechts
+     *  @author Patrick Cool
      *
-     * 	@todo what's the use of this function. I think this is better removed.
-     * 		There should be consistency in the variable names and the use throughout the scripts
+     *  @todo what's the use of this function. I think this is better removed.
+     *      There should be consistency in the variable names and the use throughout the scripts
      */
     public static function generate_abstract_user_field_names($result_array) {
-        $result_array['firstName'] 		= $result_array['firstname'];
-        $result_array['lastName'] 		= $result_array['lastname'];
-        $result_array['mail'] 			= $result_array['email'];
-        #$result_array['picture_uri'] 	= $result_array['picture_uri'];
-        #$result_array ['user_id']		= $result_array['user_id'];
+        $result_array['firstName']      = $result_array['firstname'];
+        $result_array['lastName']       = $result_array['lastname'];
+        $result_array['mail']           = $result_array['email'];
+        #$result_array['picture_uri']   = $result_array['picture_uri'];
+        #$result_array ['user_id']      = $result_array['user_id'];
         return $result_array;
     }
 
@@ -371,8 +371,8 @@ class Database
 
     /**
      * Returns the number of affected rows in the last database operation.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return int								Returns the number of affected rows on success, and -1 if the last query failed.
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return int                              Returns the number of affected rows on success, and -1 if the last query failed.
      */
     public static function affected_rows($connection = null) {
         return self::use_default_connection($connection) ? mysql_affected_rows() : mysql_affected_rows($connection);
@@ -380,8 +380,8 @@ class Database
 
     /**
      * Closes non-persistent database connection.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return bool								Returns TRUE on success or FALSE on failure.
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return bool                             Returns TRUE on success or FALSE on failure.
      */
     public static function close($connection = null) {
         return self::use_default_connection($connection) ? mysql_close() : mysql_close($connection);
@@ -389,8 +389,8 @@ class Database
 
     /**
      * Opens a connection to a database server.
-     * @param array $parameters (optional)		An array that contains the necessary parameters for accessing the server.
-     * @return resource/boolean					Returns a database connection on success or FALSE on failure.
+     * @param array $parameters (optional)      An array that contains the necessary parameters for accessing the server.
+     * @return resource/boolean                 Returns a database connection on success or FALSE on failure.
      * Note: Currently the array could contain MySQL-specific parameters:
      * $parameters['server'], $parameters['username'], $parameters['password'],
      * $parameters['new_link'], $parameters['client_flags'], $parameters['persistent'].
@@ -433,7 +433,7 @@ class Database
 
     /**
      * Returns error number from the last operation done on the database server.
-     * @param resource $connection (optional)	The database server connection,
+     * @param resource $connection (optional)   The database server connection,
      * for detailed description see the method query().
      * @return int Returns the error number from the last database (operation, or 0 (zero) if no error occurred.
      */
@@ -443,7 +443,7 @@ class Database
 
     /**
      * Returns error text from the last operation done on the database server.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
      * @return string Returns the error text from the last database operation, or '' (empty string) if no error occurred.
      */
     public static function error($connection = null) {
@@ -463,9 +463,9 @@ class Database
 
     /**
      * Escapes a string to insert into the database as text
-     * @param string							The string to escape
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return string							The escaped string
+     * @param string                            The string to escape
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return string                           The escaped string
      * @author Yannick Warnier <yannick.warnier@dokeos.com>
      * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
      */
@@ -481,21 +481,21 @@ class Database
 
     /**
      * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
-     * @param resource		The result from a call to sql_query (e.g. Database::query)
-     * @param string		Optional: "ASSOC","NUM" or "BOTH", as the constant used in mysql_fetch_array.
-     * @return array		Array of results as returned by php
+     * @param resource      The result from a call to sql_query (e.g. Database::query)
+     * @param string        Optional: "ASSOC","NUM" or "BOTH", as the constant used in mysql_fetch_array.
+     * @return array        Array of results as returned by php
      * @author Yannick Warnier <yannick.warnier@beeznest.com>
      */
     public static function fetch_array($result, $option = 'BOTH') {
-	if ($result === false) { return array(); }
+    if ($result === false) { return array(); }
         return $option == 'ASSOC' ? mysql_fetch_array($result, MYSQL_ASSOC) : ($option == 'NUM' ? mysql_fetch_array($result, MYSQL_NUM) : mysql_fetch_array($result));
     }
 
     /**
      * Gets an associative array from a SQL result (as returned by Database::query).
      * This method is equivalent to calling Database::fetch_array() with 'ASSOC' value for the optional second parameter.
-     * @param resource $result	The result from a call to sql_query (e.g. Database::query).
-     * @return array			Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
+     * @param resource $result  The result from a call to sql_query (e.g. Database::query).
+     * @return array            Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
      */
     public static function fetch_assoc($result) {
         return mysql_fetch_assoc($result);
@@ -503,11 +503,11 @@ class Database
 
     /**
      * Gets the next row of the result of the SQL query (as returned by Database::query) in an object form
-     * @param	resource	The result from a call to sql_query (e.g. Database::query)
-     * @param	string		Optional class name to instanciate
-     * @param	array		Optional array of parameters
-     * @return	object		Object of class StdClass or the required class, containing the query result row
-     * @author	Yannick Warnier <yannick.warnier@dokeos.com>
+     * @param   resource    The result from a call to sql_query (e.g. Database::query)
+     * @param   string      Optional class name to instanciate
+     * @param   array       Optional array of parameters
+     * @return  object      Object of class StdClass or the required class, containing the query result row
+     * @author  Yannick Warnier <yannick.warnier@dokeos.com>
      */
     public static function fetch_object($result, $class = null, $params = null) {
         return !empty($class) ? (is_array($params) ? mysql_fetch_object($result, $class, $params) : mysql_fetch_object($result, $class)) : mysql_fetch_object($result);
@@ -515,8 +515,8 @@ class Database
 
     /**
      * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
-     * @param resource		The result from a call to sql_query (see Database::query()).
-     * @return array		Array of results as returned by php (mysql_fetch_row)
+     * @param resource      The result from a call to sql_query (see Database::query()).
+     * @return array        Array of results as returned by php (mysql_fetch_row)
      */
     public static function fetch_row($result) {
         return mysql_fetch_row($result);
@@ -524,7 +524,7 @@ class Database
 
     /**
      * Frees all the memory associated with the provided result identifier.
-     * @return bool		Returns TRUE on success or FALSE on failure.
+     * @return bool     Returns TRUE on success or FALSE on failure.
      * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets.
      * Anyway, all associated result memory is automatically freed at the end of the script's execution.
      */
@@ -534,7 +534,7 @@ class Database
 
     /**
      * Returns the database client library version.
-     * @return strung		Returns a string that represents the client library version.
+     * @return strung       Returns a string that represents the client library version.
      */
     public static function get_client_info() {
         return mysql_get_client_info();
@@ -543,9 +543,9 @@ class Database
     /**
      * Returns a list of databases created on the server. The list may contain all of the
      * available database names or filtered database names by using a pattern.
-     * @param string $pattern (optional)		A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return array							Returns in an array the retrieved list of database names.
+     * @param string $pattern (optional)        A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'.
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return array                            Returns in an array the retrieved list of database names.
      */
     public static function get_databases($pattern = '', $connection = null) {
         $result = array();
@@ -559,13 +559,13 @@ class Database
     /**
      * Returns a list of the fields that a given table contains. The list may contain all of the available field names or filtered field names by using a pattern.
      * By using a special option, this method is able to return an indexed list of fields' properties, where field names are keys.
-     * @param string $table						This is the examined table.
-     * @param string $pattern (optional)		A pattern for filtering field names as if it was needed for the SQL's LIKE clause, for example 'column_%'.
-     * @param string $database (optional)		The name of the targeted database. If it is omited, the current database is assumed, see Database::select_db().
-     * @param bool $including_properties (optional)	When this option is true, the returned result has the followong format:
-     * 												array(field_name_1 => array(0 => property_1, 1 => property_2, ...), fieald_name_2 => array(0 => property_1, ...), ...)
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return array							Returns in an array the retrieved list of field names.
+     * @param string $table                     This is the examined table.
+     * @param string $pattern (optional)        A pattern for filtering field names as if it was needed for the SQL's LIKE clause, for example 'column_%'.
+     * @param string $database (optional)       The name of the targeted database. If it is omited, the current database is assumed, see Database::select_db().
+     * @param bool $including_properties (optional) When this option is true, the returned result has the followong format:
+     *                                              array(field_name_1 => array(0 => property_1, 1 => property_2, ...), fieald_name_2 => array(0 => property_1, ...), ...)
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return array                            Returns in an array the retrieved list of field names.
      */
     public static function get_fields($table, $pattern = '', $database = '', $including_properties = false, $connection = null) {
         $result = array();
@@ -593,8 +593,8 @@ class Database
 
     /**
      * Returns information about the type of the current connection and the server host name.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return string/boolean					Returns string data on success or FALSE on failure.
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return string/boolean                   Returns string data on success or FALSE on failure.
      */
     public static function get_host_info($connection = null) {
         return self::use_default_connection($connection) ? mysql_get_host_info() : mysql_get_host_info($connection);
@@ -602,8 +602,8 @@ class Database
 
     /**
      * Retrieves database client/server protocol version.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return int/boolean						Returns the protocol version on success or FALSE on failure.
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return int/boolean                      Returns the protocol version on success or FALSE on failure.
      */
     public static function get_proto_info($connection = null) {
         return self::use_default_connection($connection) ? mysql_get_proto_info() : mysql_get_proto_info($connection);
@@ -611,8 +611,8 @@ class Database
 
     /**
      * Retrieves the database server version.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return string/boolean					Returns the MySQL server version on success or FALSE on failure.
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return string/boolean                   Returns the MySQL server version on success or FALSE on failure.
      */
     public static function get_server_info($connection = null) {
         return self::use_default_connection($connection) ? mysql_get_server_info() : mysql_get_server_info($connection);
@@ -621,10 +621,10 @@ class Database
     /**
      * Returns a list of tables within a database. The list may contain all of the
      * available table names or filtered table names by using a pattern.
-     * @param string $database (optional)		The name of the examined database. If it is omited, the current database is assumed, see Database::select_db().
-     * @param string $pattern (optional)		A pattern for filtering table names as if it was needed for the SQL's LIKE clause, for example 'access_%'.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return array							Returns in an array the retrieved list of table names.
+     * @param string $database (optional)       The name of the examined database. If it is omited, the current database is assumed, see Database::select_db().
+     * @param string $pattern (optional)        A pattern for filtering table names as if it was needed for the SQL's LIKE clause, for example 'access_%'.
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return array                            Returns in an array the retrieved list of table names.
      */
     public static function get_tables($database = '', $pattern = '', $connection = null) {
         $result = array();
@@ -645,8 +645,8 @@ class Database
     /**
      * Gets the ID of the last item inserted into the database
      * This should be updated to use ADODB at some point
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return int								The last ID as returned by the DB function
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return int                              The last ID as returned by the DB function
      */
     public static function insert_id($connection = null) {
         return self::use_default_connection($connection) ? mysql_insert_id() : mysql_insert_id($connection);
@@ -654,8 +654,8 @@ class Database
 
     /**
      * Gets the number of rows from the last query result - help achieving database independence
-     * @param resource		The result
-     * @return integer		The number of rows contained in this result
+     * @param resource      The result
+     * @return integer      The number of rows contained in this result
      * @author Yannick Warnier <yannick.warnier@dokeos.com>
      **/
     public static function num_rows($result) {
@@ -665,10 +665,10 @@ class Database
     /**
      * Acts as the relative *_result() function of most DB drivers and fetches a
      * specific line and a field
-     * @param	resource	The database resource to get data from
-     * @param	integer		The row number
-     * @param	string		Optional field name or number
-     * @return	mixed		One cell of the result, or FALSE on error
+     * @param   resource    The database resource to get data from
+     * @param   integer     The row number
+     * @param   string      Optional field name or number
+     * @return  mixed       One cell of the result, or FALSE on error
      */
     public static function result($resource, $row, $field = '') {
         return self::num_rows($resource) > 0 ? (!empty($field) ? mysql_result($resource, $row, $field) : mysql_result($resource, $row)) : null;
@@ -679,14 +679,14 @@ class Database
      * Documentation has been added by Arthur Portugal
      * Some adaptations have been implemented by Ivan Tcholakov, 2009, 2010
      * @author Olivier Brouckaert
-     * @param string $query						The SQL query
-     * @param resource $connection (optional)	The database server (MySQL) connection.
-     * 											If it is not specified, the connection opened by mysql_connect() is assumed.
-     * 											If no connection is found, the server will try to create one as if mysql_connect() was called with no arguments.
-     * 											If no connection is found or established, an E_WARNING level error is generated.
-     * @param string $file (optional)			On error it shows the file in which the error has been trigerred (use the "magic" constant __FILE__ as input parameter)
-     * @param string $line (optional)			On error it shows the line in which the error has been trigerred (use the "magic" constant __LINE__ as input parameter)
-     * @return resource							The returned result from the query
+     * @param string $query                     The SQL query
+     * @param resource $connection (optional)   The database server (MySQL) connection.
+     *                                          If it is not specified, the connection opened by mysql_connect() is assumed.
+     *                                          If no connection is found, the server will try to create one as if mysql_connect() was called with no arguments.
+     *                                          If no connection is found or established, an E_WARNING level error is generated.
+     * @param string $file (optional)           On error it shows the file in which the error has been trigerred (use the "magic" constant __FILE__ as input parameter)
+     * @param string $line (optional)           On error it shows the line in which the error has been trigerred (use the "magic" constant __LINE__ as input parameter)
+     * @return resource                         The returned result from the query
      * Note: The parameter $connection could be skipped. Here are examples of this method usage:
      * Database::query($query);
      * $result = Database::query($query);
@@ -711,8 +711,8 @@ class Database
 
         //Check if the table contains a c_ (means a course id)
         if (api_get_setting('server_type')==='test' && strpos($query, 'c_')) {
-        	//Check if the table contains inner joins
-        	if (
+            //Check if the table contains inner joins
+            if (
                 strpos($query, 'assoc_handle') === false &&
                 strpos($query, 'olpc_peru_filter') === false &&
                 strpos($query, 'allow_public_certificates') === false &&
@@ -732,20 +732,20 @@ class Database
                 strpos($query, 'chamilo_electric_blue') === false &&
                 strpos($query, 'wcag_anysurfer_public_pages') === false &&
                 strpos($query, 'specific_field') === false &&
-        	    strpos($query, 'down_doc_path') === false &&
-        		strpos($query, 'INNER JOIN') === false &&
-        		strpos($query, 'inner join') === false &&
-        		strpos($query, 'left join') === false &&
-        		strpos($query, 'LEFT JOIN') === false &&
-        		strpos($query, 'insert') 	=== false &&
-        		strpos($query, 'INSERT') === false &&
-        		strpos($query, 'ALTER') === false &&
-        		strpos($query, 'alter') === false &&
-        		strpos($query, 'c_id') === false &&
-        		strpos($query, 'create table') === false &&
-        		strpos($query, 'CREATE TABLE') === false &&
-        		strpos($query, 'AUTO_INCREMENT') === false
-        	) {
+                strpos($query, 'down_doc_path') === false &&
+                strpos($query, 'INNER JOIN') === false &&
+                strpos($query, 'inner join') === false &&
+                strpos($query, 'left join') === false &&
+                strpos($query, 'LEFT JOIN') === false &&
+                strpos($query, 'insert') === false &&
+                strpos($query, 'INSERT') === false &&
+                strpos($query, 'ALTER') === false &&
+                strpos($query, 'alter') === false &&
+                strpos($query, 'c_id') === false &&
+                strpos($query, 'create table') === false &&
+                strpos($query, 'CREATE TABLE') === false &&
+                strpos($query, 'AUTO_INCREMENT') === false
+            ) {
                 //@todo remove this
                 echo '<pre>';
                 $message = '<h4>Dev message: please add the c_id field in this query or report this error in support.chamilo.org </h4>';
@@ -753,7 +753,7 @@ class Database
                 echo $message;
                 echo '</pre>';
                 //error_log($message);
-        	}
+            }
         }
 
         if (!($result = $use_default_connection ? mysql_query($query) : mysql_query($query, $connection))) {
@@ -832,9 +832,9 @@ class Database
 
     /**
      * Selects a database.
-     * @param string $database_name				The name of the database that is to be selected.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return bool								Returns TRUE on success or FALSE on failure.
+     * @param string $database_name             The name of the database that is to be selected.
+     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
+     * @return bool                             Returns TRUE on success or FALSE on failure.
      */
     public static function select_db($database_name, $connection = null) {
         return self::use_default_connection($connection) ? mysql_select_db($database_name) : mysql_select_db($database_name, $connection);
@@ -864,8 +864,8 @@ class Database
 
     /**
      * Checks whether a given encoding is supported by the database server.
-     * @param string $encoding	The encoding (a system conventional id, for example 'UTF-8') to be checked.
-     * @return bool				Returns a boolean value as a check-result.
+     * @param string $encoding  The encoding (a system conventional id, for example 'UTF-8') to be checked.
+     * @return bool             Returns a boolean value as a check-result.
      * @author Ivan Tcholakov
      */
     public static function is_encoding_supported($encoding) {
@@ -885,9 +885,9 @@ class Database
      * Constructs a SQL clause about default character set and default collation for newly created databases and tables.
      * Example: Database::make_charset_clause('UTF-8', 'bulgarian') returns
      *  DEFAULT CHARACTER SET `utf8` DEFAULT COLLATE `utf8_general_ci`
-     * @param string $encoding (optional)	The default database/table encoding (a system conventional id) to be used.
-     * @param string $language (optional)	Language (a system conventional id) used for choosing language sensitive collation (if it is possible).
-     * @return string						Returns the constructed SQL clause or empty string if $encoding is not correct or is not supported.
+     * @param string $encoding (optional)   The default database/table encoding (a system conventional id) to be used.
+     * @param string $language (optional)   Language (a system conventional id) used for choosing language sensitive collation (if it is possible).
+     * @return string                       Returns the constructed SQL clause or empty string if $encoding is not correct or is not supported.
      * @author Ivan Tcholakov
      */
     public static function make_charset_clause($encoding = null, $language = null) {
@@ -912,8 +912,8 @@ class Database
     /**
      * Converts an encoding identificator to MySQL-specific encoding identifictor,
      * i.e. 'UTF-8' --> 'utf8'.
-     * @param string $encoding	The conventional encoding identificator.
-     * @return string			Returns the corresponding MySQL-specific encoding identificator if any, otherwise returns NULL.
+     * @param string $encoding  The conventional encoding identificator.
+     * @return string           Returns the corresponding MySQL-specific encoding identificator if any, otherwise returns NULL.
      * @author Ivan Tcholakov
      */
     public static function to_db_encoding($encoding) {
@@ -934,8 +934,8 @@ class Database
     /**
      * Converts a MySQL-specific encoding identifictor to conventional encoding identificator,
      * i.e. 'utf8' --> 'UTF-8'.
-     * @param string $encoding	The MySQL-specific encoding identificator.
-     * @return string			Returns the corresponding conventional encoding identificator if any, otherwise returns NULL.
+     * @param string $encoding  The MySQL-specific encoding identificator.
+     * @return string           Returns the corresponding conventional encoding identificator if any, otherwise returns NULL.
      * @author Ivan Tcholakov
      */
     public static function from_db_encoding($db_encoding) {
@@ -955,9 +955,9 @@ class Database
 
     /**
      * Chooses the default MySQL-specific collation from given encoding and language.
-     * @param string $encoding				A conventional encoding id, i.e. 'UTF-8'
-     * @param string $language (optional)	A conventional for the system language id, i.e. 'bulgarian'. If it is empty, the chosen collation is the default server value corresponding to the given encoding.
-     * @return string						Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
+     * @param string $encoding              A conventional encoding id, i.e. 'UTF-8'
+     * @param string $language (optional)   A conventional for the system language id, i.e. 'bulgarian'. If it is empty, the chosen collation is the default server value corresponding to the given encoding.
+     * @return string                       Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
      * @author Ivan Tcholakov
      */
     public static function to_db_collation($encoding, $language = null) {
@@ -994,18 +994,18 @@ class Database
     */
 
     /**
-     *	Glues a course database.
-     *	glue format from local.inc.php.
+     *  Glues a course database.
+     *  glue format from local.inc.php.
      */
     private static function glue_course_database_name($database_name) {
         return self::get_course_table_prefix().$database_name.self::get_database_glue();
     }
 
     /**
-     *	@param string $database_name, can be empty to use current course db
+     *  @param string $database_name, can be empty to use current course db
      *
-     *	@return the glued parameter if it is not empty,
-     *	or the current course database (glued) if the parameter is empty.
+     *  @return the glued parameter if it is not empty,
+     *  or the current course database (glued) if the parameter is empty.
      */
     private static function fix_database_parameter($database_name) {
         if (empty($database_name)) {
@@ -1016,18 +1016,18 @@ class Database
     }
 
     /**
-     *	Structures a course database and table name to ready them
-     *	for querying. The course database parameter is considered glued:
-     *	e.g. COURSE001`.`
+     *  Structures a course database and table name to ready them
+     *  for querying. The course database parameter is considered glued:
+     *  e.g. COURSE001`.`
      */
     private static function format_glued_course_table_name($database_name_with_glue, $table) {
         return '`'.$database_name_with_glue.$table.'`';
     }
 
     /**
-     *	Structures a database and table name to ready them
-     *	for querying. The database parameter is considered not glued,
-     *	just plain e.g. COURSE001
+     *  Structures a database and table name to ready them
+     *  for querying. The database parameter is considered not glued,
+     *  just plain e.g. COURSE001
      */
     private static function format_table_name($database, $table) {
         global $_configuration;
@@ -1044,9 +1044,9 @@ class Database
      * checking whether the input parameter $connection actually has been provided.
      * If the input parameter connection is not a resource or if it is not FALSE (in case of error)
      * then the default opened connection should be used by the called method.
-     * @param resource/boolean $connection	The checked parameter $connection.
-     * @return boolean						TRUE means that calling method should use the default connection.
-     * 										FALSE means that (valid) parameter $connection has been provided and it should be used.
+     * @param resource/boolean $connection  The checked parameter $connection.
+     * @return boolean                      TRUE means that calling method should use the default connection.
+     *                                      FALSE means that (valid) parameter $connection has been provided and it should be used.
      */
     private static function use_default_connection($connection) {
         return !is_resource($connection) && $connection !== false;
@@ -1055,8 +1055,8 @@ class Database
     /**
      * This private method tackles the XSS injections. It is similar to Security::remove_XSS() and works always,
      * including the time of initialization when the class Security has not been loaded yet.
-     * @param string	The input variable to be filtered from XSS, in this class it is expected to be a string.
-     * @return string	Returns the filtered string as a result.
+     * @param string    The input variable to be filtered from XSS, in this class it is expected to be a string.
+     * @return string   Returns the filtered string as a result.
      */
     private static function remove_XSS(& $var) {
         return class_exists('Security') ? Security::remove_XSS($var) : @htmlspecialchars($var, ENT_QUOTES, api_get_system_encoding());
@@ -1115,9 +1115,9 @@ class Database
 
     /**
      * Constructs a MySQL-specific collation and checks whether it is supported by the database server.
-     * @param string $db_encoding	A MySQL-specific encoding id, i.e. 'utf8'
-     * @param string $language		A MySQL-compatible language id, i.e. 'bulgarian'
-     * @return string				Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
+     * @param string $db_encoding   A MySQL-specific encoding id, i.e. 'utf8'
+     * @param string $language      A MySQL-compatible language id, i.e. 'bulgarian'
+     * @return string               Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
      * @author Ivan Tcholakov
      */
     private static function check_db_collation($db_encoding, $language) {
@@ -1163,7 +1163,7 @@ class Database
             $sql    = 'INSERT INTO '.$table_name.' ('.implode(',',$params).') VALUES ('.implode(',',$values).')';
             self::query($sql);
             if ($show_query) {
-            	var_dump($sql);
+                var_dump($sql);
             }
             return self::insert_id();
         }
@@ -1336,9 +1336,9 @@ class Database
 
     /**
      * Experimental useful database update
-     * @param	string	table name use Database::get_main_table
-     * @param	array	array with values to updates, keys are the fields in the database: Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya';
-     * @param	array	where conditions i.e array('id = ?' =>'4')
+     * @param   string  table name use Database::get_main_table
+     * @param   array   array with values to updates, keys are the fields in the database: Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya';
+     * @param   array   where conditions i.e array('id = ?' =>'4')
      * @todo lot of stuff to do here
      */
     public static function update($table_name, $attributes, $where_conditions = array(), $show_query = false) {

+ 67 - 69
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_create_folder.php

@@ -28,80 +28,78 @@ 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;
+} elseif (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 {
-    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
+    include_once CLASS_FILE;
+    $file = new file();
+    if ($file->mkdir(addTrailingSlash($_POST['currentFolderPath']) . $_POST['new_folder'], 0775)) {
+        event_system(LOG_MY_FOLDER_CREATE, LOG_MY_FOLDER_PATH, $_POST['currentFolderPath'] . $_POST['new_folder']);
+        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
 
-                $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             = 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;
-                }
-                $info .= sprintf(", %s:'%s'", $k, $v);
+        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;
             }
-        } else {
-            $error = ERR_FOLDER_CREATION_FAILED;
+            $info .= sprintf(", %s:'%s'", $k, $v);
         }
+    } else {
+        $error = ERR_FOLDER_CREATION_FAILED;
     }
 }
 echo "error:'".$error."'";

+ 4 - 0
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_delete_file.php

@@ -63,6 +63,7 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_DELETE) {
                     'document_path',
                     addTrailingSlash(backslashToSlash($_GET['delete']))
                 );
+                event_system(LOG_MY_FOLDER_DELETE, LOG_MY_FOLDER_PATH, $_GET['delete']);
             }
             //////end bridge to Chamilo
             $file->delete(addTrailingSlash(backslashToSlash($_GET['delete'])));
@@ -101,6 +102,7 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_DELETE) {
             } else {
                 $file->delete($_GET['delete']); //deleted by ajaxfilemanager
                 event_system(LOG_USER_PERSONAL_DOC_DELETED, 'document_path', $_GET['delete']);
+                event_system(LOG_MY_FOLDER_DELETE, LOG_MY_FOLDER_PATH, $_GET['delete']);
             }
             //////end bridge to Chamilo
         }
@@ -158,6 +160,7 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_DELETE) {
                             'document_path',
                             addTrailingSlash(backslashToSlash($doc))
                         );
+                        event_system(LOG_MY_FOLDER_DELETE, LOG_MY_FOLDER_PATH, $doc);
                     }
                     //////end bridge to Chamilo
                 } elseif (is_file($doc)
@@ -196,6 +199,7 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_DELETE) {
                     } else {
                         $file->delete($doc); //deleted by ajaxfilemanager
                         event_system(LOG_USER_PERSONAL_DOC_DELETED, 'document_path', $doc);
+                        event_system(LOG_MY_FOLDER_DELETE, LOG_MY_FOLDER_PATH, $doc);
                     }
                     //////end bridge to Chamilo
                 }

+ 4 - 1
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_copy.php

@@ -24,5 +24,8 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_COPY) {
     $sessionAction->setFolder($_POST['currentFolderPath']);
     $sessionAction->set($_POST['selectedDoc']);
     $info = ',num:'.sizeof($_POST['selectedDoc']);
+    foreach ($_POST['selectedDoc'] as $doc) {
+        event_system(LOG_MY_FOLDER_COPY, LOG_MY_FOLDER_PATH, $doc);
+    }
 }
-echo "{error:'".$error."'\n".$info."}";
+echo "{error:'".$error."'\n".$info."}";

+ 3 - 1
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_cut.php

@@ -26,5 +26,7 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_CUT) {
     $sessionAction->setFolder($_POST['currentFolderPath']);
     $sessionAction->set($_POST['selectedDoc']);
     $info = ',num:'.sizeof($_POST['selectedDoc']);
+    foreach ($_POST['selectedDoc'] as $doc) {
+        event_system(LOG_MY_FOLDER_COPY, LOG_MY_FOLDER_PATH, $doc);
+    }
 }
-echo "{error:'".$error."'\n".$info."}";

+ 2 - 0
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_paste.php

@@ -12,6 +12,7 @@ require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanage
 $error                   = '';
 $fileMoved               = array();
 $unmovedDocDueToSamePath = array();
+$finalPath = '';
 if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
     $error = SYS_DISABLED;
 } elseif (empty($_GET['current_folder_path'])) {
@@ -61,6 +62,7 @@ if (CONFIG_SYS_VIEW_ONLY || (!CONFIG_OPTIONS_CUT && !CONFIG_OPTIONS_COPY)) {
                         $obj       = new manager($finalPath, false);
 
                         $fileType = $obj->getFileType($finalPath, (is_dir($finalPath) ? true : false));
+                        event_system(LOG_MY_FOLDER_PASTE, LOG_MY_FOLDER_PATH, $finalPath);
 
                         foreach ($fileType as $k => $v) {
                             $tem[$k] = $v;

+ 4 - 2
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_file_upload.php

@@ -14,7 +14,8 @@ require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanage
 sleep(3);
 echo "{";
 $error = "";
-$info  = "";
+$info = "";
+$fullPath = '';
 
 include_once CLASS_UPLOAD;
 $upload = new Upload();
@@ -115,12 +116,13 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_UPLOAD) {
             }
             $info .= sprintf(", url:'%s'", getFileUrl($path));
             $info .= sprintf(", tipedit:'%s'", TIP_DOC_RENAME);
+            // Log to TRACK_E_DEFAULT
+            event_system(LOG_MY_FOLDER_UPLOAD, LOG_MY_FOLDER_PATH, $fullPath);
         } else {
             $error = ERR_FILE_NOT_AVAILABLE;
         }
     }
 }
-
 echo "error:'".$error."'";
 echo $info;
 echo "}";

+ 2 - 1
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_get_file_listing.php

@@ -10,6 +10,7 @@
 require_once '../../../../../../inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'fckeditor/editor/plugins/ajaxfilemanager/inc/config.php';
 
+$path = isset($_REQUEST['path'])? Security::remove_XSS($_REQUEST['path']) : null ;
 if (!isset($manager)) {
     /**
      *  this is part of  script for processing file paste
@@ -41,7 +42,7 @@ if (!isset($manager)) {
         $sessionAction = new SessionAction();
         include_once(DIR_AJAX_INC."class.manager.php");
 
-        $manager = new manager();
+        $manager = new manager($path);
         $manager->setSessionAction($sessionAction);
 
         $fileList   = $manager->getFileList();

+ 2 - 0
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajax_save_name.php

@@ -70,6 +70,8 @@ if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_RENAME) {
         $fileInfo          = $manager->getFolderInfo();
         $fileInfo['mtime'] = date(DATE_TIME_FORMAT, $fileInfo['mtime']);
     }
+    event_system(LOG_MY_FOLDER_CHANGE, LOG_MY_FOLDER_PATH, $_POST['original_path']);
+    event_system(LOG_MY_FOLDER_CHANGE, LOG_MY_FOLDER_NEW_PATH, $path);
 }
 
 echo "{";

+ 1 - 1
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/class.manager.php

@@ -82,7 +82,7 @@ class manager
             $this->currentFolderPath = CONFIG_SYS_DEFAULT_PATH;
         }
 
-        $this->currentFolderPath = (isUnderRoot($this->getCurrentFolderPath()) ? backslashToSlash((addTrailingSlash($this->getCurrentFolderPath()))) : CONFIG_SYS_DEFAULT_PATH);
+        $this->currentFolderPath = (isUnderRoot($this->getCurrentFolderPath()) ? backslashToSlash((addTrailingSlash($this->getCurrentFolderPath()))) : $this->currentFolderPath);
         $this->currentFolderPath = base64_encode($this->currentFolderPath);
 
         if ($this->calculateSubdir) {

File diff suppressed because it is too large
+ 651 - 459
main/inc/lib/link.lib.php


+ 41 - 23
main/inc/lib/mail.lib.inc.php

@@ -21,18 +21,36 @@ require_once api_get_path(LIBRARY_PATH).'phpmailer/class.phpmailer.php';
  *
  * @author Bert Vanderkimpen ICT&O UGent
  *
- * @param recipient_name   	name of recipient
- * @param recipient_email  	email of recipient
+ * @param recipient_name    name of recipient
+ * @param recipient_email   email of recipient
  * @param message           email body
  * @param subject           email subject
  * @return                  returns true if mail was sent
  * @see                     class.phpmailer.php
  * @deprecated use api_mail_html()
  */
-function api_mail($recipient_name, $recipient_email, $subject, $message, $sender_name = '',
-    $sender_email = '', $extra_headers = '', $additional_parameters = array()) {
-	api_mail_html($recipient_name, $recipient_email, $subject, $message, $sender_name,
-        $sender_email, $extra_headers, null, null, $additional_parameters);
+function api_mail(
+    $recipient_name,
+    $recipient_email,
+    $subject,
+    $message,
+    $sender_name = '',
+    $sender_email = '',
+    $extra_headers = '',
+    $additionalParameters = array()
+) {
+    api_mail_html(
+        $recipient_name,
+        $recipient_email,
+        $subject,
+        $message,
+        $sender_name,
+        $sender_email,
+        $extra_headers,
+        null,
+        null,
+        $additionalParameters
+    );
 }
 
 /**
@@ -66,7 +84,7 @@ function api_mail_html(
     $extra_headers = array(),
     $data_file = array(),
     $embedded_image = false,
-    $additional_parameters = array()
+    $additionalParameters = array()
 ) {
     global $platform_email;
 
@@ -122,14 +140,14 @@ function api_mail_html(
 
     // Send embedded image.
     if ($embedded_image) {
-    	// Get all images html inside content.
+        // Get all images html inside content.
         preg_match_all("/<img\s+.*?src=[\"\']?([^\"\' >]*)[\"\']?[^>]*>/i", $message, $m);
         // Prepare new tag images.
         $new_images_html = array();
         $i = 1;
         if (!empty($m[1])) {
-        	foreach ($m[1] as $image_path) {
-            	$real_path = realpath($image_path);
+            foreach ($m[1] as $image_path) {
+                $real_path = realpath($image_path);
                 $filename  = basename($image_path);
                 $image_cid = $filename.'_'.$i;
                 $encoding = 'base64';
@@ -137,17 +155,17 @@ function api_mail_html(
                 $mail->AddEmbeddedImage($real_path, $image_cid, $filename, $encoding, $image_type);
                 $new_images_html[] = '<img src="cid:'.$image_cid.'" />';
                 $i++;
-			}
-		}
-
-	    // Replace origin image for new embedded image html.
-	    $x = 0;
-	    if (!empty($m[0])) {
-	    	foreach ($m[0] as $orig_img) {
-	        	$message = str_replace($orig_img, $new_images_html[$x], $message);
-	            $x++;
-	         }
-	    }
+            }
+        }
+
+        // Replace origin image for new embedded image html.
+        $x = 0;
+        if (!empty($m[0])) {
+            foreach ($m[0] as $orig_img) {
+                $message = str_replace($orig_img, $new_images_html[$x], $message);
+                $x++;
+             }
+        }
     }
     $message = str_replace(array("\n\r", "\n", "\r"), '<br />', $message);
     $mail->Body = '<html><head></head><body>'.$message.'</body></html>';
@@ -216,9 +234,9 @@ function api_mail_html(
     $plugin = new AppPlugin();
     $installedPluginsList = $plugin->getInstalledPluginListObject();
     foreach ($installedPluginsList as $installedPlugin) {
-        if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additional_parameters)) {
+        if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additionalParameters)) {
             $clockworksmsObject = new Clockworksms();
-            $clockworksmsObject->send($additional_parameters);
+            $clockworksmsObject->send($additionalParameters);
         }
     }
 

+ 252 - 239
main/inc/lib/main_api.lib.php

@@ -83,6 +83,7 @@ define('TOOL_THUMBNAIL', 'thumbnail');
 define('TOOL_HOTPOTATOES', 'hotpotatoes');
 define('TOOL_CALENDAR_EVENT', 'calendar_event');
 define('TOOL_LINK', 'link');
+define('TOOL_LINK_CATEGORY', 'link_category');
 define('TOOL_COURSE_DESCRIPTION', 'course_description');
 define('TOOL_SEARCH', 'search');
 define('TOOL_LEARNPATH', 'learnpath');
@@ -153,24 +154,24 @@ define('LOG_COURSE_DELETE',                     'course_deleted');
 define('LOG_COURSE_CREATE',                     'course_created');
 
 // @todo replace 'soc_gr' with social_group
-define('LOG_GROUP_PORTAL_CREATED',			    'soc_gr_created');
-define('LOG_GROUP_PORTAL_UPDATED',			    'soc_gr_updated');
-define('LOG_GROUP_PORTAL_DELETED',			    'soc_gr_deleted');
-define('LOG_GROUP_PORTAL_USER_DELETE_ALL',		'soc_gr_delete_users');
+define('LOG_GROUP_PORTAL_CREATED',              'soc_gr_created');
+define('LOG_GROUP_PORTAL_UPDATED',              'soc_gr_updated');
+define('LOG_GROUP_PORTAL_DELETED',              'soc_gr_deleted');
+define('LOG_GROUP_PORTAL_USER_DELETE_ALL',      'soc_gr_delete_users');
 
-define('LOG_GROUP_PORTAL_ID',			        'soc_gr_portal_id');
-define('LOG_GROUP_PORTAL_REL_USER_ARRAY',		'soc_gr_user_array');
+define('LOG_GROUP_PORTAL_ID',                   'soc_gr_portal_id');
+define('LOG_GROUP_PORTAL_REL_USER_ARRAY',       'soc_gr_user_array');
 
-define('LOG_GROUP_PORTAL_USER_SUBSCRIBED',  	'soc_gr_u_subs');
-define('LOG_GROUP_PORTAL_USER_UNSUBSCRIBED',	'soc_gr_u_unsubs');
-define('LOG_GROUP_PORTAL_USER_UPDATE_ROLE',		'soc_gr_update_role');
+define('LOG_GROUP_PORTAL_USER_SUBSCRIBED',      'soc_gr_u_subs');
+define('LOG_GROUP_PORTAL_USER_UNSUBSCRIBED',    'soc_gr_u_unsubs');
+define('LOG_GROUP_PORTAL_USER_UPDATE_ROLE',     'soc_gr_update_role');
 
 define('LOG_USER_DELETE',                       'user_deleted');
 define('LOG_USER_CREATE',                       'user_created');
 define('LOG_USER_ENABLE',                       'user_enable');
 define('LOG_USER_DISABLE',                      'user_disable');
-define('LOG_USER_FIELD_CREATE',			        'user_field_created');
-define('LOG_USER_FIELD_DELETE',			        'user_field_deleted');
+define('LOG_USER_FIELD_CREATE',                 'user_field_created');
+define('LOG_USER_FIELD_DELETE',                 'user_field_deleted');
 define('LOG_SESSION_CREATE',                    'session_created');
 define('LOG_SESSION_DELETE',                    'session_deleted');
 define('LOG_SESSION_CATEGORY_CREATE',           'session_cat_created'); //changed in 1.9.8
@@ -195,12 +196,20 @@ define('LOG_EXERCISE_RESULT_DELETE',           'exe_result_deleted');
 define('LOG_LP_ATTEMPT_DELETE',                'lp_attempt_deleted');
 define('LOG_QUESTION_RESULT_DELETE',           'qst_attempt_deleted');
 
-// event logs data types (max 20 chars)
+define('LOG_MY_FOLDER_CREATE',                  'my_folder_created');
+define('LOG_MY_FOLDER_CHANGE',                  'my_folder_changed');
+define('LOG_MY_FOLDER_DELETE',                  'my_folder_deleted');
+define('LOG_MY_FOLDER_COPY',                    'my_folder_copied');
+define('LOG_MY_FOLDER_CUT',                     'my_folder_cut');
+define('LOG_MY_FOLDER_PASTE',                   'my_folder_pasted');
+define('LOG_MY_FOLDER_UPLOAD',                  'my_folder_uploaded');
+
+// Event logs data types (max 20 chars)
 define('LOG_COURSE_CODE',                       'course_code');
 define('LOG_COURSE_ID',                         'course_id');
 define('LOG_USER_ID',                           'user_id');
 define('LOG_USER_OBJECT',                       'user_object');
-define('LOG_USER_FIELD_VARIABLE',		        'user_field_variable');
+define('LOG_USER_FIELD_VARIABLE',               'user_field_variable');
 define('LOG_SESSION_ID',                        'session_id');
 define('LOG_SESSION_CATEGORY_ID',               'session_category_id');
 define('LOG_CONFIGURATION_SETTINGS_CATEGORY',   'settings_category');
@@ -217,6 +226,9 @@ define('LOG_EXERCISE_AND_USER_ID',               'exercise_and_user_id');
 define('LOG_LP_ID',                              'lp_id');
 define('LOG_EXERCISE_ATTEMPT_QUESTION_ID',       'exercise_a_q_id');
 
+define('LOG_MY_FOLDER_PATH',                    'path');
+define('LOG_MY_FOLDER_NEW_PATH',                'new_path');
+
 define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.]/');
 
 //used when login_is_email setting is true
@@ -288,33 +300,33 @@ define('COURSE_RELATION_TYPE_RRHH', 1);
 define('SESSION_RELATION_TYPE_RRHH', 1);
 
 //User image sizes
-define('USER_IMAGE_SIZE_ORIGINAL',	1);
-define('USER_IMAGE_SIZE_BIG', 		2);
-define('USER_IMAGE_SIZE_MEDIUM', 	3);
+define('USER_IMAGE_SIZE_ORIGINAL',  1);
+define('USER_IMAGE_SIZE_BIG',       2);
+define('USER_IMAGE_SIZE_MEDIUM',    3);
 define('USER_IMAGE_SIZE_SMALL',     4);
 
 // Relation type between users
-define('USER_UNKNOW',					0);
-define('USER_RELATION_TYPE_UNKNOW',		1);
-define('USER_RELATION_TYPE_PARENT',		2); // should be deprecated is useless
-define('USER_RELATION_TYPE_FRIEND',		3);
-define('USER_RELATION_TYPE_GOODFRIEND',	4); // should be deprecated is useless
-define('USER_RELATION_TYPE_ENEMY',		5); // should be deprecated is useless
-define('USER_RELATION_TYPE_DELETED',     6);
-define('USER_RELATION_TYPE_RRHH',		7);
+define('USER_UNKNOW',                   0);
+define('USER_RELATION_TYPE_UNKNOW',     1);
+define('USER_RELATION_TYPE_PARENT',     2); // should be deprecated is useless
+define('USER_RELATION_TYPE_FRIEND',     3);
+define('USER_RELATION_TYPE_GOODFRIEND', 4); // should be deprecated is useless
+define('USER_RELATION_TYPE_ENEMY',      5); // should be deprecated is useless
+define('USER_RELATION_TYPE_DELETED',    6);
+define('USER_RELATION_TYPE_RRHH',       7);
 
 //Gradebook link constants
 //Please do not change existing values, they are used in the database !
 
-define('LINK_EXERCISE',				1);
-define('LINK_DROPBOX',				2);
-define('LINK_STUDENTPUBLICATION',	3);
+define('LINK_EXERCISE',             1);
+define('LINK_DROPBOX',              2);
+define('LINK_STUDENTPUBLICATION',   3);
 define('LINK_LEARNPATH',            4);
-define('LINK_FORUM_THREAD',			5);
+define('LINK_FORUM_THREAD',         5);
 //define('LINK_WORK',6);
-define('LINK_ATTENDANCE',			7);
-define('LINK_SURVEY',				8);
-define('LINK_HOTPOTATOES',			9);
+define('LINK_ATTENDANCE',           7);
+define('LINK_SURVEY',               8);
+define('LINK_HOTPOTATOES',          9);
 
 //From display.lib.php
 
@@ -896,37 +908,37 @@ function api_protect_course_script($print_headers = false, $allow_session_admins
         return true;
     }
     if (api_is_platform_admin($allow_session_admins)) {
-    	return true;
+        return true;
     }
     $course_info = api_get_course_info();
 
     if (isset($course_info) && isset($course_info['visibility'])) {
-    	switch ($course_info['visibility']) {
-    		default:
-    		case COURSE_VISIBILITY_CLOSED: //Completely closed: the course is only accessible to the teachers. - 0
-    			if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
-    				$is_visible = true;
-    			}
-    			break;
-    		case COURSE_VISIBILITY_REGISTERED: //Private - access authorized to course members only - 1
-    			if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
-    				$is_visible = true;
-    			}
-    			break;
-    		case COURSE_VISIBILITY_OPEN_PLATFORM: // Open - access allowed for users registered on the platform - 2
-    			if (api_get_user_id() && !api_is_anonymous()) {
-    				$is_visible = true;
-    			}
-    			break;
-    		case COURSE_VISIBILITY_OPEN_WORLD: //Open - access allowed for the whole world - 3
-    			$is_visible = true;
-    			break;
+        switch ($course_info['visibility']) {
+            default:
+            case COURSE_VISIBILITY_CLOSED: //Completely closed: the course is only accessible to the teachers. - 0
+                if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
+                    $is_visible = true;
+                }
+                break;
+            case COURSE_VISIBILITY_REGISTERED: //Private - access authorized to course members only - 1
+                if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
+                    $is_visible = true;
+                }
+                break;
+            case COURSE_VISIBILITY_OPEN_PLATFORM: // Open - access allowed for users registered on the platform - 2
+                if (api_get_user_id() && !api_is_anonymous()) {
+                    $is_visible = true;
+                }
+                break;
+            case COURSE_VISIBILITY_OPEN_WORLD: //Open - access allowed for the whole world - 3
+                $is_visible = true;
+                break;
             case COURSE_VISIBILITY_HIDDEN: //Completely closed: the course is only accessible to the teachers. - 0
                 if (api_is_platform_admin()) {
                     $is_visible = true;
                 }
                 break;
-    	}
+        }
         //If password is set and user is not registered to the course then the course is not visible
         if ($is_allowed_in_course == false & isset($course_info['registration_code']) && !empty($course_info['registration_code'])) {
             $is_visible = false;
@@ -1116,15 +1128,15 @@ function _api_format_user($user, $add_password = false)
     $result['complete_name_with_username'] = $result['complete_name'];
 
     if (!empty($user['username'])) {
-        $result['complete_name_with_username'] 	= $result['complete_name'].' ('.$user['username'].')';
+        $result['complete_name_with_username'] = $result['complete_name'].' ('.$user['username'].')';
     }
 
-    $result['firstname'] 		= $firstname;
-    $result['lastname'] 		= $lastname;
+    $result['firstname']    = $firstname;
+    $result['lastname']     = $lastname;
 
     // Kept for historical reasons
-    $result['firstName'] 		= $firstname;
-    $result['lastName'] 		= $lastname;
+    $result['firstName']    = $firstname;
+    $result['lastName']     = $lastname;
 
     $attributes = array(
         'phone',
@@ -1180,36 +1192,36 @@ function _api_format_user($user, $add_password = false)
 
     // Getting user avatar.
 
-	$picture_filename   = trim($result['picture_uri']);
-	$avatar             = api_get_path(WEB_CODE_PATH).'img/unknown.jpg';
-	$avatar_small       = api_get_path(WEB_CODE_PATH).'img/unknown_22.jpg';
+    $picture_filename   = trim($result['picture_uri']);
+    $avatar             = api_get_path(WEB_CODE_PATH).'img/unknown.jpg';
+    $avatar_small       = api_get_path(WEB_CODE_PATH).'img/unknown_22.jpg';
     $avatar_sys_path    = api_get_path(SYS_CODE_PATH).'img/unknown.jpg';
-	$dir                = 'upload/users/'.$user_id.'/';
+    $dir                = 'upload/users/'.$user_id.'/';
 
-	//if (!empty($picture_filename) && api_is_anonymous() ) {  //Why you have to be anonymous?
+    //if (!empty($picture_filename) && api_is_anonymous() ) {  //Why you have to be anonymous?
     if (!empty($picture_filename)) {
-		if (api_get_setting('split_users_upload_directory') === 'true') {
-			$dir = 'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/';
-		}
-	}
-	$image_sys_path = api_get_path(SYS_CODE_PATH).$dir.$picture_filename;
-
-	if (file_exists($image_sys_path) && !is_dir($image_sys_path)) {
-		$avatar = api_get_path(WEB_CODE_PATH).$dir.$picture_filename;
-		$avatar_small = api_get_path(WEB_CODE_PATH).$dir.'small_'.$picture_filename;
+        if (api_get_setting('split_users_upload_directory') === 'true') {
+            $dir = 'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/';
+        }
+    }
+    $image_sys_path = api_get_path(SYS_CODE_PATH).$dir.$picture_filename;
+
+    if (file_exists($image_sys_path) && !is_dir($image_sys_path)) {
+        $avatar = api_get_path(WEB_CODE_PATH).$dir.$picture_filename;
+        $avatar_small = api_get_path(WEB_CODE_PATH).$dir.'small_'.$picture_filename;
         $avatar_sys_path = api_get_path(SYS_CODE_PATH).$dir.$picture_filename;
-	}
+    }
 
     $result['avatar'] = $avatar;
     $result['avatar_sys_path'] = $avatar_sys_path;
     $result['avatar_small'] = $avatar_small;
 
-	if (isset($user['user_is_online'])) {
-		$result['user_is_online'] = $user['user_is_online'] == true ? 1 : 0;
-	}
+    if (isset($user['user_is_online'])) {
+        $result['user_is_online'] = $user['user_is_online'] == true ? 1 : 0;
+    }
     if (isset($user['user_is_online_in_chat'])) {
-		$result['user_is_online_in_chat'] = intval($user['user_is_online_in_chat']);
-	}
+        $result['user_is_online_in_chat'] = intval($user['user_is_online_in_chat']);
+    }
 
     if ($add_password) {
         $result['password'] = $user['password'];
@@ -1236,10 +1248,10 @@ function api_get_user_info($user_id = '', $check_if_user_is_online = false, $sho
     $result = Database::query($sql);
     if (Database::num_rows($result) > 0) {
         $result_array = Database::fetch_array($result);
-		if ($check_if_user_is_online) {
+        if ($check_if_user_is_online) {
             $use_status_in_platform = user_is_online($user_id);
 
-			$result_array['user_is_online'] = $use_status_in_platform;
+            $result_array['user_is_online'] = $use_status_in_platform;
             $user_online_in_chat = 0;
 
             if ($use_status_in_platform) {
@@ -1249,7 +1261,7 @@ function api_get_user_info($user_id = '', $check_if_user_is_online = false, $sho
                 }
             }
             $result_array['user_is_online_in_chat'] = $user_online_in_chat;
-		}
+        }
         $user = _api_format_user($result_array, $show_password);
         return $user;
     }
@@ -1343,7 +1355,7 @@ function api_get_course_path($course_code = null)
 function api_get_course_setting($setting_name, $course_code = null)
 {
     $course_info = api_get_course_info($course_code);
-	$table 		 = Database::get_course_table(TABLE_COURSE_SETTING);
+    $table       = Database::get_course_table(TABLE_COURSE_SETTING);
     $setting_name = Database::escape_string($setting_name);
     if (!empty($course_info['real_id']) && !empty($setting_name)) {
         $sql = "SELECT value FROM $table
@@ -2451,21 +2463,21 @@ function api_is_course_tutor() {
 }
 
 function api_get_user_platform_status($user_id = false) {
-	$status     = array();
+    $status     = array();
     $user_id    = intval($user_id);
     if (empty($user_id)) {
-    	$user_id    = api_get_user_id();
+        $user_id    = api_get_user_id();
     }
 
-	if (empty($user_id)) {
-		return false;
-	}
-	$group_id   = api_get_group_id();
-	$course_id  = api_get_course_int_id();
-	$course_code= api_get_course_id();
-	$session_id = api_get_session_id();
+    if (empty($user_id)) {
+        return false;
+    }
+    $group_id   = api_get_group_id();
+    $course_id  = api_get_course_int_id();
+    $course_code= api_get_course_id();
+    $session_id = api_get_session_id();
 
-	//Group (in course)
+    //Group (in course)
     if ($group_id && $course_id) {
         $group_status = array();
         $is_subscribed = GroupManager::is_subscribed($user_id, $group_id);
@@ -2481,8 +2493,8 @@ function api_get_user_platform_status($user_id = false) {
         $status['group'] = $group_status;
     }
 
-	//Session
-	if ($session_id && $course_id) {
+    //Session
+    if ($session_id && $course_id) {
         $session_status = array('id' => $session_id, 'course_id' => $course_id);
         $session_user_status = SessionManager::get_user_status_in_course_session($user_id, $course_code, $session_id);
         switch ($session_user_status) {
@@ -2497,12 +2509,12 @@ function api_get_user_platform_status($user_id = false) {
         if ($is_general_coach) {
             $session_status['status'] = 'general_coach';
         }
-    	$status['session'] = $session_status;
+        $status['session'] = $session_status;
 
-	} elseif($course_id) {
-	    //Course
-	    $course_status = array();
-	    if ($course_id) {
+    } elseif($course_id) {
+        //Course
+        $course_status = array();
+        if ($course_id) {
             $user_course_status = CourseManager::get_user_in_course_status($user_id, $course_code);
 
             if ($user_course_status) {
@@ -2521,8 +2533,8 @@ function api_get_user_platform_status($user_id = false) {
                     break;
                 }
             }
-	    }
-	    $status['course'] = $course_status;
+        }
+        $status['course'] = $course_status;
     }
 
     return $status;
@@ -2536,7 +2548,7 @@ function api_get_user_platform_status($user_id = false) {
  */
 function api_is_course_session_coach($user_id, $course_code, $session_id)
 {
-    $session_table 						= Database::get_main_table(TABLE_MAIN_SESSION);
+    $session_table                      = Database::get_main_table(TABLE_MAIN_SESSION);
     $session_rel_course_rel_user_table  = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
     $user_id = intval($user_id);
@@ -2544,9 +2556,9 @@ function api_is_course_session_coach($user_id, $course_code, $session_id)
     $course_code = Database::escape_string($course_code);
 
     $sql = "SELECT DISTINCT id
-				FROM $session_table INNER JOIN $session_rel_course_rel_user_table session_rc_ru
-	            ON session.id = session_rc_ru.id_session
-	            WHERE   session_rc_ru.id_user = '".$user_id."'  AND
+                FROM $session_table INNER JOIN $session_rel_course_rel_user_table session_rc_ru
+                ON session.id = session_rc_ru.id_session
+                WHERE   session_rc_ru.id_user = '".$user_id."'  AND
                         session_rc_ru.course_code = '$course_code' AND
                         session_rc_ru.status = 2 AND
                         session_rc_ru.id_session = '$session_id'";
@@ -2579,34 +2591,34 @@ function api_is_coach($session_id = 0, $course_code = null, $check_student_view
     } else {
         $course_code = api_get_course_id();
     }
-    $session_table 						= Database::get_main_table(TABLE_MAIN_SESSION);
+    $session_table                      = Database::get_main_table(TABLE_MAIN_SESSION);
     $session_rel_course_rel_user_table  = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $sessionIsCoach = null;
 
-	if (!empty($course_code)) {
-	    $sql = "SELECT DISTINCT id, name, date_start, date_end
-				FROM $session_table INNER JOIN $session_rel_course_rel_user_table session_rc_ru
-	            ON session_rc_ru.id_user = '".api_get_user_id()."'
-	            WHERE   session_rc_ru.course_code = '$course_code' AND
+    if (!empty($course_code)) {
+        $sql = "SELECT DISTINCT id, name, date_start, date_end
+                FROM $session_table INNER JOIN $session_rel_course_rel_user_table session_rc_ru
+                ON session_rc_ru.id_user = '".api_get_user_id()."'
+                WHERE   session_rc_ru.course_code = '$course_code' AND
                         session_rc_ru.status = 2 AND
                         session_rc_ru.id_session = '$session_id'";
-	    $result = Database::query($sql);
-	    $sessionIsCoach = Database::store_result($result);
-	}
-
-	if (!empty($session_id)) {
-	    $sql = "SELECT DISTINCT id, name, date_start, date_end
-	         	FROM $session_table
-	         	WHERE session.id_coach =  '".api_get_user_id()."' AND id = '$session_id'
-				ORDER BY date_start, date_end, name";
-	    $result = Database::query($sql);
-	    if (!empty($sessionIsCoach)) {
-	    	$sessionIsCoach = array_merge($sessionIsCoach , Database::store_result($result));
-	    } else {
-	    	$sessionIsCoach = Database::store_result($result);
-	    }
-
-	}
+        $result = Database::query($sql);
+        $sessionIsCoach = Database::store_result($result);
+    }
+
+    if (!empty($session_id)) {
+        $sql = "SELECT DISTINCT id, name, date_start, date_end
+                FROM $session_table
+                WHERE session.id_coach =  '".api_get_user_id()."' AND id = '$session_id'
+                ORDER BY date_start, date_end, name";
+        $result = Database::query($sql);
+        if (!empty($sessionIsCoach)) {
+            $sessionIsCoach = array_merge($sessionIsCoach , Database::store_result($result));
+        } else {
+            $sessionIsCoach = Database::store_result($result);
+        }
+
+    }
     return (count($sessionIsCoach) > 0);
 }
 
@@ -2854,9 +2866,9 @@ function api_display_debug_info($debug_info) {
 
 function api_is_allowed_to_edit($tutor = false, $coach = false, $session_coach = false, $check_student_view = true)
 {
-    $my_session_id 				= api_get_session_id();
-    $is_allowed_coach_to_edit 	= api_is_coach(null, null, $check_student_view);
-    $session_visibility 		= api_get_session_visibility($my_session_id);
+    $my_session_id              = api_get_session_id();
+    $is_allowed_coach_to_edit   = api_is_coach(null, null, $check_student_view);
+    $session_visibility         = api_get_session_visibility($my_session_id);
 
     // Admins can edit anything.
     if (api_is_platform_admin(false)) {
@@ -3309,13 +3321,13 @@ function api_get_item_visibility($_course, $tool, $id, $session = 0)
     $id = intval($id);
     $session = (int) $session;
     $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-    $course_id	 = intval($_course['real_id']);
+    $course_id = intval($_course['real_id']);
     $sql = "SELECT visibility FROM $TABLE_ITEMPROPERTY
-    		WHERE 	c_id = $course_id AND
-    				tool = '$tool' AND
-    				ref = $id AND
-    				(id_session = $session OR id_session = 0)
-    		ORDER BY id_session DESC, lastedit_date DESC
+            WHERE   c_id = $course_id AND
+                    tool = '$tool' AND
+                    ref = $id AND
+                    (id_session = $session OR id_session = 0)
+            ORDER BY id_session DESC, lastedit_date DESC
             LIMIT 1";
 
     $res = Database::query($sql);
@@ -3373,11 +3385,11 @@ function api_item_property_update(
 
     // Definition of variables.
     $tool           = Database::escape_string($tool);
-    $item_id        = Database::escape_string($item_id);
+    $item_id        = intval($item_id);
     $lastedit_type  = Database::escape_string($lastedit_type);
-    $user_id        = Database::escape_string($user_id);
-    $to_group_id    = Database::escape_string($to_group_id);
-    $to_user_id     = Database::escape_string($to_user_id);
+    $user_id        = intval($user_id);
+    $to_group_id    = intval($to_group_id);
+    $to_user_id     = intval($to_user_id);
     $start_visible  = Database::escape_string($start_visible);
     $end_visible    = Database::escape_string($end_visible);
     $start_visible  = ($start_visible == 0) ? '0000-00-00 00:00:00' : $start_visible;
@@ -3449,19 +3461,19 @@ function api_item_property_update(
             if (!empty($session_id)) {
                 // Check whether session id already exist into itemp_properties for updating visibility or add it.
                 $sql = "SELECT id_session FROM $TABLE_ITEMPROPERTY
-                		WHERE
-                		    c_id = $course_id AND
-                		    tool = '$tool' AND
-                		    ref='$item_id' AND
-                		    id_session = '$session_id'";
+                        WHERE
+                            c_id = $course_id AND
+                            tool = '$tool' AND
+                            ref='$item_id' AND
+                            id_session = '$session_id'";
                 $rs = Database::query($sql);
                 if (Database::num_rows($rs) > 0) {
                     $sql = "UPDATE $TABLE_ITEMPROPERTY
-                            SET lastedit_type		= '".str_replace('_', '', ucwords($tool))."Deleted',
-                            	lastedit_date		= '$time',
-                            	lastedit_user_id	= '$user_id',
-                            	visibility			= '$visibility',
-                            	id_session 			= '$session_id' $set_type
+                            SET lastedit_type       = '".str_replace('_', '', ucwords($tool))."Deleted',
+                                lastedit_date       = '$time',
+                                lastedit_user_id    = '$user_id',
+                                visibility          = '$visibility',
+                                id_session          = '$session_id' $set_type
                             WHERE $filter";
                 } else {
                     $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
@@ -3579,7 +3591,7 @@ function api_get_item_property_by_tool($tool, $course_code, $session_id = null)
     $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $session_id = intval($session_id);
     $session_condition = ' AND id_session = '.$session_id;
-    $course_id	 = $course_info['real_id'];
+    $course_id = $course_info['real_id'];
 
     $sql = "SELECT * FROM $item_property_table
             WHERE c_id = $course_id AND tool = '$tool'  $session_condition ";
@@ -3646,7 +3658,7 @@ function api_get_item_property_id($course_code, $tool, $ref) {
 
     // Definition of tables.
     $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-    $course_id	 = $course_info['real_id'];
+    $course_id = $course_info['real_id'];
     $sql = "SELECT id FROM $TABLE_ITEMPROPERTY
             WHERE c_id = $course_id AND tool = '$tool' AND ref = '$ref'";
     $rs  = Database::query($sql);
@@ -3702,7 +3714,7 @@ function api_get_track_item_property_history($tool, $ref)
 
 /**
  * Gets item property data from tool of a course id
- * @param int    	course id
+ * @param int       course id
  * @param string    tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  * @param int       id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  * @param int $session_id
@@ -3717,18 +3729,18 @@ function api_get_item_property_info($course_id, $tool, $ref, $session_id = 0)
 
     $tool = Database::escape_string($tool);
     $ref = intval($ref);
-    $course_id	 = $course_info['real_id'];
+    $course_id = $course_info['real_id'];
     $session_id = intval($session_id);
 
     // Definition of tables.
     $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
 
-   	$sql = "SELECT * FROM $table
-   	        WHERE
-   	            c_id = $course_id AND
-   	            tool = '$tool' AND
-   	            ref = $ref AND
-   	            id_session = $session_id ";
+    $sql = "SELECT * FROM $table
+            WHERE
+                c_id = $course_id AND
+                tool = '$tool' AND
+                ref = $ref AND
+                id_session = $session_id ";
 
     $rs  = Database::query($sql);
     $row = array();
@@ -3765,7 +3777,7 @@ function api_get_languages_combo($name = 'language', $chozen=true) {
     }
 
     $languages  = $language_list['name'];
-    $folder		= $language_list['folder'];
+    $folder     = $language_list['folder'];
 
     $ret .= '<select name="'.$name.'" id="language_chosen" '.($chozen?'class="chzn-select"':'').' >';
     foreach ($languages as $key => $value) {
@@ -3805,7 +3817,7 @@ function api_display_language_form($hide_if_no_choice = false) {
 
     $original_languages = $language_list['name'];
     $folder = $language_list['folder']; // This line is probably no longer needed.
-	$html = '
+    $html = '
     <script type="text/javascript">
     <!--
     function jumpMenu(targ,selObj,restore){ // v3.0
@@ -4285,14 +4297,14 @@ if (!function_exists('sys_get_temp_dir')) {
  * @author      Aidan Lister <aidan@php.net>
  * @version     1.0.3
  * @param       string   $dirname    Directory to delete
- * @param       bool	 Deletes only the content or not
+ * @param       bool     Deletes only the content or not
  * @return      bool     Returns TRUE on success, FALSE on failure
  * @link http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
  * @author      Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
  * @author      Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
  */
 function rmdirr($dirname, $delete_only_content_in_folder = false) {
-	$res = true;
+    $res = true;
 
     // A sanity check.
     if (!file_exists($dirname)) {
@@ -4330,10 +4342,10 @@ function rmdirr($dirname, $delete_only_content_in_folder = false) {
     }
 
     if ($delete_only_content_in_folder == false) {
-	    $res = rmdir($dirname);
-	    if ($res === false) {
-	        error_log(__FILE__.' line '.__LINE__.': '.((bool)ini_get('track_errors') ? $php_errormsg : 'error not recorded because track_errors is off in your php.ini'), 0);
-	    }
+        $res = rmdir($dirname);
+        if ($res === false) {
+            error_log(__FILE__.' line '.__LINE__.': '.((bool)ini_get('track_errors') ? $php_errormsg : 'error not recorded because track_errors is off in your php.ini'), 0);
+        }
     }
     return $res;
 }
@@ -4357,7 +4369,7 @@ function copyr($source, $dest, $exclude = array(), $copied_files = array()) {
         }
         return true;
     } elseif (!is_dir($source)) {
-    	//then source is not a dir nor a file, return
+        //then source is not a dir nor a file, return
         return false;
     }
 
@@ -4402,7 +4414,7 @@ function copy_folder_course_session($pathname, $base_path_document, $session_id,
         return false;
     }
 
-    $course_id	 = $course_info['real_id'];
+    $course_id = $course_info['real_id'];
 
     $folders = explode(DIRECTORY_SEPARATOR,str_replace($base_path_document.DIRECTORY_SEPARATOR,'',$pathname));
 
@@ -4430,13 +4442,13 @@ function copy_folder_course_session($pathname, $base_path_document, $session_id,
 
                 // Insert new folder with destination session_id.
                 $sql = "INSERT INTO ".$table." SET
-                		c_id = $course_id,
-                		path = '$path',
-                		comment = '".Database::escape_string($document->comment)."',
-                		title = '".Database::escape_string(basename($new_pathname))."' ,
-                		filetype='folder',
-                		size= '0',
-                		session_id = '$session_id'";
+                        c_id = $course_id,
+                        path = '$path',
+                        comment = '".Database::escape_string($document->comment)."',
+                        title = '".Database::escape_string(basename($new_pathname))."' ,
+                        filetype='folder',
+                        size= '0',
+                        session_id = '$session_id'";
                 Database::query($sql);
                 $document_id = Database::insert_id();
                 api_item_property_update($course_info,TOOL_DOCUMENT,$document_id,'FolderCreated',api_get_user_id(),0,0,null,null,$session_id);
@@ -4660,44 +4672,44 @@ function api_get_status_langvars() {
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 */
 function api_get_settings_options($var) {
-	$table_settings_options = Database :: get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
+    $table_settings_options = Database :: get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
     $var = Database::escape_string($var);
-	$sql = "SELECT * FROM $table_settings_options WHERE variable = '$var' ORDER BY id";
-	$result = Database::query($sql);
+    $sql = "SELECT * FROM $table_settings_options WHERE variable = '$var' ORDER BY id";
+    $result = Database::query($sql);
     $settings_options_array = array();
-	while ($row = Database::fetch_array($result, 'ASSOC')) {
-		//$temp_array = array ('value' => $row['value'], 'display_text' => $row['display_text']);
-		$settings_options_array[] = $row;
-	}
-	return $settings_options_array;
+    while ($row = Database::fetch_array($result, 'ASSOC')) {
+        //$temp_array = array ('value' => $row['value'], 'display_text' => $row['display_text']);
+        $settings_options_array[] = $row;
+    }
+    return $settings_options_array;
 }
 
 function api_set_setting_option($params) {
-	$table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
-	if (empty($params['id'])) {
-		Database::insert($table, $params);
-	} else {
-		Database::update($table, $params, array('id = ? '=> $params['id']));
-	}
+    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
+    if (empty($params['id'])) {
+        Database::insert($table, $params);
+    } else {
+        Database::update($table, $params, array('id = ? '=> $params['id']));
+    }
 }
 
 function api_set_setting_simple($params) {
-	$table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
+    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
     $url_id = api_get_current_access_url_id();
 
-	if (empty($params['id'])) {
+    if (empty($params['id'])) {
         $params['access_url'] = $url_id;
-		Database::insert($table, $params);
-	} else {
-		Database::update($table, $params, array('id = ? '=> array($params['id'])));
-	}
+        Database::insert($table, $params);
+    } else {
+        Database::update($table, $params, array('id = ? '=> array($params['id'])));
+    }
 }
 
 function api_delete_setting_option($id) {
-	$table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
-	if (!empty($id)) {
-		Database::delete($table, array('id = ? '=> $id));
-	}
+    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
+    if (!empty($id)) {
+        Database::delete($table, array('id = ? '=> $id));
+    }
 }
 
 /**
@@ -5808,11 +5820,11 @@ function api_sql_query($query, $file = '', $line = 0) {
  * @param string $subject
  * @param string $message
  * @param string $additional_headers
- * @param string $additional_parameters
+ * @param string $additionalParameters
  * @author Ivan Tcholakov, 04-OCT-2009, a reworked version of this function.
  * @link http://www.dokeos.com/forum/viewtopic.php?t=15557
  */
-function api_send_mail($to, $subject, $message, $additional_headers = null, $additional_parameters = array()) {
+function api_send_mail($to, $subject, $message, $additional_headers = null, $additionalParameters = array()) {
 
     require_once api_get_path(LIBRARY_PATH).'phpmailer/class.phpmailer.php';
 
@@ -5903,9 +5915,9 @@ function api_send_mail($to, $subject, $message, $additional_headers = null, $add
     $plugin = new AppPlugin();
     $installedPluginsList = $plugin->getInstalledPluginListObject();
     foreach ($installedPluginsList as $installedPlugin) {
-        if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additional_parameters)) {
+        if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additionalParameters)) {
             $clockworksmsObject = new Clockworksms();
-            $clockworksmsObject->send($additional_parameters);
+            $clockworksmsObject->send($additionalParameters);
         }
     }
 
@@ -6197,9 +6209,9 @@ function api_check_browscap() {
     $setting = ini_get('browscap');
     if ($setting) {
         $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
-	    if (strpos($setting, 'browscap.ini') && !empty($browser)) {
-	        return true;
-	    }
+        if (strpos($setting, 'browscap.ini') && !empty($browser)) {
+            return true;
+        }
     }
     return false;
 }
@@ -6234,9 +6246,9 @@ function api_get_jquery_js() {
  */
 function api_get_jquery_ui_js($include_jqgrid = false) {
     $libraries = array('jquery-ui');
-	if ($include_jqgrid) {
-	   $libraries[]='jqgrid';
-	}
+    if ($include_jqgrid) {
+       $libraries[]='jqgrid';
+    }
     return api_get_jquery_libraries_js($libraries);
 }
 
@@ -6309,8 +6321,8 @@ function api_get_jquery_libraries_js($libraries) {
     }
 
     if (in_array('bxslider',$libraries)) {
-    	$js .= api_get_js('bxslider/jquery.bxSlider.min.js');
-    	$js .= api_get_css($js_path.'bxslider/bx_styles/bx_styles.css');
+        $js .= api_get_js('bxslider/jquery.bxSlider.min.js');
+        $js .= api_get_css($js_path.'bxslider/bx_styles/bx_styles.css');
     }
 
     // jquery datepicker
@@ -6343,10 +6355,10 @@ function api_get_jquery_libraries_js($libraries) {
  * Returns the course's URL
  *
  * This function relies on api_get_course_info()
- * @param 	string  The course code - optional (takes it from session if not given)
- * @param 	int		The session id  - optional (takes it from session if not given)
- * @return 	mixed 	The URL of the course or null if something does not work
- * @author 	Julio Montoya <gugli100@gmail.com>
+ * @param   string  The course code - optional (takes it from session if not given)
+ * @param   int     The session id  - optional (takes it from session if not given)
+ * @return  mixed   The URL of the course or null if something does not work
+ * @author  Julio Montoya <gugli100@gmail.com>
  */
 function api_get_course_url($course_code = null, $session_id = null)
 {
@@ -6375,7 +6387,7 @@ function api_get_course_url($course_code = null, $session_id = null)
 /**
  *
  * Check if the current portal has the $_configuration['multiple_access_urls'] parameter on
- * @return bool	true if multi site is enabled
+ * @return bool true if multi site is enabled
  *
  * */
 function api_get_multiple_access_url() {
@@ -6401,29 +6413,29 @@ function api_get_unique_id() {
 }
 
 function api_get_home_path() {
-	$home = 'home/';
-	if (api_get_multiple_access_url()) {
-		$access_url_id = api_get_current_access_url_id();
-		$url_info      = api_get_access_url($access_url_id);
-		$url           = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
-		$clean_url     = replace_dangerous_char($url);
-		$clean_url     = str_replace('/', '-', $clean_url);
-		$clean_url     .= '/';
-		// if $clean_url ==  "localhost/" means that the multiple URL was not well configured we don't rename the $home variable
-		if ($clean_url != 'localhost/')
-			$home          = 'home/'.$clean_url;
-	}
-	return $home;
+    $home = 'home/';
+    if (api_get_multiple_access_url()) {
+        $access_url_id = api_get_current_access_url_id();
+        $url_info      = api_get_access_url($access_url_id);
+        $url           = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
+        $clean_url     = replace_dangerous_char($url);
+        $clean_url     = str_replace('/', '-', $clean_url);
+        $clean_url     .= '/';
+        // if $clean_url ==  "localhost/" means that the multiple URL was not well configured we don't rename the $home variable
+        if ($clean_url != 'localhost/')
+            $home          = 'home/'.$clean_url;
+    }
+    return $home;
 }
 
 function api_get_course_table_condition($and = true) {
-	$course_id = api_get_course_int_id();
-	$condition = '';
-	$condition_add = $and ? " AND " : " WHERE ";
-	if (!empty($course_id)) {
-		$condition = " $condition_add c_id = $course_id";
-	}
-	return $condition;
+    $course_id = api_get_course_int_id();
+    $condition = '';
+    $condition_add = $and ? " AND " : " WHERE ";
+    if (!empty($course_id)) {
+        $condition = " $condition_add c_id = $course_id";
+    }
+    return $condition;
 }
 
 /**
@@ -6641,6 +6653,7 @@ function api_set_default_visibility($item_id, $tool_id, $group_id = null) {
 
     switch ($tool_id) {
         case TOOL_LINK:
+        case TOOL_LINK_CATEGORY:
             $tool_id = 'links';
             break;
         case TOOL_DOCUMENT:

+ 33 - 21
main/inc/lib/notification.lib.php

@@ -154,31 +154,43 @@ class Notification extends Model
                     case self::NOTIFY_MESSAGE_AT_ONCE:
                     case self::NOTIFY_INVITATION_AT_ONCE:
                     case self::NOTIFY_GROUP_AT_ONCE:
-                        if (!empty($user_info['mail'])) {
+                        $mail = api_get_setting('noreply_email_address');
+                        if ($user_setting == self::NOTIFY_INVITATION_AT_ONCE) {
+                            $sender_info['complete_name'] = $this->admin_name;
+                            $extra_headers = array();
+                            $extra_headers['reply_to']['name'] = $this->admin_name;
+                            if (!empty($mail)) {
+                                $sender_info['email'] = $mail;
+                                $extra_headers['reply_to']['mail'] = $mail;
+                                
+                            } else {
+                                $sender_info['email'] = $this->admin_email;
+                                $extra_headers['reply_to']['mail'] = $this->admin_email;
+                            }
+                        }
+                        if (!empty($user_info['mail']) || !empty($mail)) {
                             $name = api_get_person_name($user_info['firstname'], $user_info['lastname']);
                             if (!empty($sender_info['complete_name']) && !empty($sender_info['email'])) {
-                                $extra_headers = array();
-                                $extra_headers['reply_to']['mail'] = $sender_info['email'];
-                                $extra_headers['reply_to']['name'] = $sender_info['complete_name'];
-                                api_mail_html(
-                                    $name,
-                                    $user_info['mail'],
-                                    Security::filter_terms($title),
-                                    Security::filter_terms($content),
-                                    $sender_info['complete_name'],
-                                    $sender_info['email'],
-                                    $extra_headers
-                                );
+                                if ($user_setting != self::NOTIFY_INVITATION_AT_ONCE) {
+                                    $extra_headers = array();
+                                    $extra_headers['reply_to']['mail'] = $sender_info['email'];
+                                    $extra_headers['reply_to']['name'] = $sender_info['complete_name'];
+                                }
                             } else {
-                                api_mail_html(
-                                    $name,
-                                    $user_info['mail'],
-                                    Security::filter_terms($title),
-                                    Security::filter_terms($content),
-                                    $this->admin_name,
-                                    $this->admin_email
-                                );
+                                $extra_headers = array();
+                                $sender_info['complete_name'] = $this->admin_name;
+                                $sender_info['email'] = $this->admin_email;
                             }
+                            api_mail_html(
+                                $name,
+                                $user_info['mail'],
+                                Security::filter_terms($title),
+                                Security::filter_terms($content),
+                                $sender_info['complete_name'],
+                                $sender_info['email'],
+                                $extra_headers
+                            );
+                    
                         }
                         $params['sent_at'] = api_get_utc_datetime();
                         // Saving the notification to be sent some day.

+ 33 - 1
main/inc/lib/skill.lib.php

@@ -28,7 +28,26 @@ class SkillProfile extends Model
         $profiles = Database::store_result($result, 'ASSOC');
         return $profiles;
     }
+    
+    /**
+    * This function is for editing profile info from profile_id.
+    * @param int $profileId
+    * @param string $name
+    * @param string $description
+    */
+    public function UpdateProfileInfo($profileId, $name, $description)
+    {
+        $sql = "UPDATE $this->table SET name = '$name', description = '$description' WHERE id = $profileId ";
+        $result = Database::query($sql);
+        return $result;
+    }
 
+    /**
+     * Call the save method of the parent class and the SkillRelProfile object
+     * @param array Params
+     * @param bool Whether to show the query in parent save() method
+     * @return mixed Profile ID or false if incomplete params
+     */
     public function save($params, $show_query = false)
     {
         if (!empty($params)) {
@@ -55,6 +74,7 @@ class SkillRelProfile extends Model
     public function __construct()
     {
         $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
+        $this->tableProfile = Database::get_main_table(TABLE_MAIN_SKILL_PROFILE);
     }
 
     public function get_skills_by_profile($profile_id)
@@ -68,8 +88,20 @@ class SkillRelProfile extends Model
         }
         return $return_array;
     }
-}
 
+    /**
+    * This function is for getting profile info from profile_id.
+    * @param int $profileId
+    */
+
+    public function getProfileInfo($profileId)
+    { 
+        $sql = "SELECT * FROM $this->table p INNER JOIN $this->tableProfile pr ON(pr.id = p.profile_id) WHERE p.profile_id = ".intval($profileId);
+        $result = Database::query($sql);
+        $profileData = Database::fetch_array($result, 'ASSOC');
+        return $profileData;
+    }
+}
 class SkillRelSkill extends Model
 {
     public $columns = array('skill_id', 'parent_id', 'relation_type', 'level');

+ 17 - 2
main/inc/lib/social.lib.php

@@ -574,7 +574,18 @@ class SocialManager extends UserManager
 
         $show_groups = array('groups', 'group_messages', 'messages_list', 'group_add', 'mygroups', 'group_edit', 'member_list', 'invite_friends', 'waiting_list', 'browse_groups');
 
-        $html = '';
+        // get count unread message and total invitations
+        $count_unread_message = MessageManager::get_number_of_messages(true);
+        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
+
+        $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id(api_get_user_id());
+        $group_pending_invitations = GroupPortalManager::get_groups_by_user(api_get_user_id(), GROUP_USER_PERMISSION_PENDING_INVITATION, false);
+        $group_pending_invitations = count($group_pending_invitations);
+        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
+        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
+        $showUserImage = user_is_online($user_id) || api_is_platform_admin();
+
+        $html = '<div class="social-menu">';
         if (in_array($show, $show_groups) && !empty($group_id)) {
             //--- Group image
             $group_info = GroupPortalManager::get_group_data($group_id);
@@ -591,7 +602,11 @@ class SocialManager extends UserManager
             $html .= '</div>';
             $html .= '</div>';
         } else {
-            $img_array = UserManager::get_user_picture_path_by_id($user_id, 'web', true, true);
+            if ($showUserImage) {
+                $img_array = UserManager::get_user_picture_path_by_id($user_id, 'web', true, true);
+            } else {
+                $img_array = UserManager::get_user_picture_path_by_id(null, 'web', true, true);
+            }
             $big_image = UserManager::get_picture_user($user_id, $img_array['file'], '', USER_IMAGE_SIZE_BIG);
             $big_image = $big_image['file'].'?'.uniqid();
             $normal_image = $img_array['dir'].$img_array['file'].'?'.uniqid();

+ 8 - 7
main/inc/lib/thematic.lib.php

@@ -234,7 +234,9 @@ class Thematic
 	        $condition_session = '';
 	        if (empty($session_id)) {
                 $condition_session = api_get_session_condition(0);
-	        }
+	        } else {
+                $condition_session = api_get_session_condition($session_id, true, true);
+            }
 	    	$condition = " WHERE active = 1 $condition_session ";
 	    }
 		$sql = "SELECT * FROM $tbl_thematic $condition AND c_id = $course_id ORDER BY display_order ";
@@ -910,7 +912,7 @@ class Thematic
         $error = null;
 		$a_thematic_advance_ids = array();
         $course_id = api_get_course_int_id();
-
+        $sessionId = api_get_session_id();
 
 		if (!empty($thematic_data)) {
 			foreach ($thematic_data as $thematic) {
@@ -919,9 +921,9 @@ class Thematic
 				if (!empty($thematic_advance_data[$thematic['id']])) {
 					foreach ($thematic_advance_data[$thematic['id']] as $thematic_advance) {
 
-						$item_info = api_get_item_property_info(api_get_course_int_id(), 'thematic_advance', $thematic_advance['id']);
+						$item_info = api_get_item_property_info(api_get_course_int_id(), 'thematic_advance', $thematic_advance['id'], $sessionId);
 
-						if ($item_info['id_session'] == api_get_session_id()) {
+						if ($item_info['id_session'] == $sessionId) {
 
     						$a_thematic_advance_ids[] = $thematic_advance['id'];
 
@@ -953,17 +955,16 @@ class Thematic
 
             // update item_property
             $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-            $session_id = api_get_session_id();
 
             // get all thematic advance done
             $rs_thematic_done = Database::query("SELECT ref FROM $tbl_item_property
-                                WHERE c_id = $course_id AND tool='thematic_advance' AND lastedit_type='ThematicAdvanceDone' AND id_session = $session_id ");
+                                WHERE c_id = $course_id AND tool='thematic_advance' AND lastedit_type='ThematicAdvanceDone' AND id_session = $sessionId ");
             if (Database::num_rows($rs_thematic_done) > 0) {
                 while ($row_thematic_done = Database::fetch_array($rs_thematic_done)) {
                     $ref = $row_thematic_done['ref'];
                     if (in_array($ref, $a_thematic_advance_ids)) { continue; }
                     // update items
-                    Database::query("UPDATE $tbl_item_property SET lastedit_date='".api_get_utc_datetime()."', lastedit_type='ThematicAdvanceUpdated', lastedit_user_id = $user_id WHERE c_id = $course_id AND tool='thematic_advance' AND ref=$ref AND id_session = $session_id  ");
+                    Database::query("UPDATE $tbl_item_property SET lastedit_date='".api_get_utc_datetime()."', lastedit_type='ThematicAdvanceUpdated', lastedit_user_id = $user_id WHERE c_id = $course_id AND tool='thematic_advance' AND ref=$ref AND id_session = $sessionId  ");
                 }
             }
 		}

+ 14 - 5
main/inc/lib/usermanager.lib.php

@@ -153,8 +153,7 @@ class UserManager
         }
 
 
-        //@todo replace this date with the api_get_utc_date function big problem with users that are already registered
-        $current_date = date('Y-m-d H:i:s', time());
+        $current_date = api_get_utc_datetime();
         $sql = "INSERT INTO $table_user
                 SET lastname =         '".Database::escape_string(trim($lastName))."',
                 firstname =         '".Database::escape_string(trim($firstName))."',
@@ -208,14 +207,24 @@ class UserManager
                     $values["prior_lang"] = null;
                     EventsDispatcher::events('user_registration', $values);
                 } else {
-                    $additional_parameters = array(
+                    $additionalParameters = array(
                         'smsType' => WELCOME_LOGIN_PASSWORD,
                         'userId' => $return,
                         'mobilePhoneNumber' => $extra['mobile_phone_number'],
                         'password' => $original_password
                     );
-                    api_mail_html($recipient_name, $email, $emailsubject, $emailbody,
-                        $sender_name, $email_admin, null, null, null, $additional_parameters);
+                    api_mail_html(
+                        $recipient_name,
+                        $email,
+                        $emailsubject,
+                        $emailbody,
+                        $sender_name,
+                        $email_admin,
+                        null,
+                        null,
+                        null,
+                        $additionalParameters
+                    );
                 }
                 /* ENDS MANAGE EVENT WITH MAIL */
             }

+ 3 - 3
main/inc/lib/userportal.lib.php

@@ -194,14 +194,14 @@ class IndexManager
         if ($show_menu) {
             $html .= '<ul class="nav nav-list">';
             if ($show_create_link) {
-                $html .= '<li><a href="main/create_course/add_course.php" class="add course">'.(api_get_setting('course_validation') == 'true' ? get_lang('CreateCourseRequest') : get_lang('CourseCreate')).'</a></li>';
+                $html .= '<li class="add-course"><a href="' . api_get_path(WEB_CODE_PATH) . 'create_course/add_course.php">'.(api_get_setting('course_validation') == 'true' ? get_lang('CreateCourseRequest') : get_lang('CourseCreate')).'</a></li>';
             }
 
             if ($show_course_link) {
                 if (!api_is_drh() && !api_is_session_admin()) {
-                    $html .=  '<li><a href="main/auth/courses.php" class="list course">'.get_lang('CourseCatalog').'</a></li>';
+                    $html .=  '<li class="list-course"><a href="' . api_get_path(WEB_CODE_PATH) . 'auth/courses.php">'.get_lang('CourseCatalog').'</a></li>';
                 } else {
-                    $html .= '<li><a href="main/dashboard/index.php">'.get_lang('Dashboard').'</a></li>';
+                    $html .= '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'dashboard/index.php">'.get_lang('Dashboard').'</a></li>';
                 }
             }
             $html .= '</ul>';

+ 2 - 0
main/install/configuration.dist.php

@@ -236,3 +236,5 @@ $_configuration['system_stable']     = NEW_VERSION_STABLE;
 //$_configuration['show_official_code_exercise_result_list'] = false;
 // One connection per user
 //$_configuration['prevent_multiple_simultaneous_login'] = false;
+// Hide private courses from course catalog
+//$_configuration['course_catalog_hide_private'] = false;

+ 419 - 374
main/link/link.php

@@ -35,18 +35,18 @@ api_protect_course_script();
 
 $htmlHeadXtra[] = '<script type="text/javascript">
     $(document).ready( function() {
-    	for (i=0;i<$(".actions").length;i++) {
-    		if ($(".actions:eq("+i+")").html()=="<table border=\"0\"></table>" || $(".actions:eq("+i+")").html()=="" || $(".actions:eq("+i+")").html()==null) {
-    			$(".actions:eq("+i+")").hide();
-    		}
-    	}
+        for (i=0;i<$(".actions").length;i++) {
+            if ($(".actions:eq("+i+")").html()=="<table border=\"0\"></table>" || $(".actions:eq("+i+")").html()=="" || $(".actions:eq("+i+")").html()==null) {
+                $(".actions:eq("+i+")").hide();
+            }
+        }
      });
 
      function check_url(id, url) {
-     	var url = "'.api_get_path(WEB_AJAX_PATH).'link.ajax.php?a=check_url&url=" +url;
-     	var loading = " '.addslashes(Display::return_icon('loading1.gif')).'";
-     	$("#url_id_"+id).html(loading);
-    	$("#url_id_"+id).load(url);
+        var url = "'.api_get_path(WEB_AJAX_PATH).'link.ajax.php?a=check_url&url=" +url;
+        var loading = " '.addslashes(Display::return_icon('loading1.gif')).'";
+        $("#url_id_"+id).html(loading);
+        $("#url_id_"+id).load(url);
      }
  </script>';
 
@@ -73,34 +73,33 @@ $target_link = !empty($_REQUEST['target_link']) ? $_REQUEST['target_link'] : '_s
 
 $nameTools = get_lang('Links');
 
+$course_id = api_get_course_int_id();
 // Condition for the session
 $session_id = api_get_session_id();
 $condition_session = api_get_session_condition($session_id, true, true);
 
 if (isset($_GET['action']) && $_GET['action'] == 'addlink') {
-	$nameTools = '';
-	$interbreadcrumb[] = array('url' => 'link.php', 'name' => get_lang('Links'));
-	$interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddLink'));
+    $nameTools = '';
+    $interbreadcrumb[] = array('url' => 'link.php', 'name' => get_lang('Links'));
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddLink'));
 }
 
 if (isset($_GET['action']) && $_GET['action'] == 'addcategory') {
-	$nameTools = '';
-	$interbreadcrumb[] = array('url' => 'link.php', 'name' => get_lang('Links'));
-	$interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddCategory'));
+    $nameTools = '';
+    $interbreadcrumb[] = array('url' => 'link.php', 'name' => get_lang('Links'));
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddCategory'));
 }
 
 if (isset($_GET['action']) && $_GET['action'] == 'editlink') {
-	$nameTools = '';
-	$interbreadcrumb[] = array('url' => 'link.php', 'name' => get_lang('Links'));
-	$interbreadcrumb[] = array('url' => '#', 'name' => get_lang('EditLink'));
+    $nameTools = '';
+    $interbreadcrumb[] = array('url' => 'link.php', 'name' => get_lang('Links'));
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('EditLink'));
 }
 
 // Database Table definitions
 $tbl_link       = Database::get_course_table(TABLE_LINK);
 $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
 
-$course_id = api_get_course_int_id();
-
 // Statistics
 event_access_tool(TOOL_LINK);
 
@@ -122,49 +121,49 @@ function MM_popupMsg(msg) { //v1.0
 $nameTools = get_lang('Links');
 
 if (isset($_GET['action'])) {
-	$check_token = Security::check_token('request');
-	if ($check_token) {
-		switch ($_GET['action']) {
-			case 'addlink':
-				if ($link_submitted) {
-					if (!addlinkcategory("link")) {	// Here we add a link
-						unset($submit_link);
-					}
-				}
-				break;
-			case 'addcategory':
-				if ($category_submitted) {
-					if (!addlinkcategory('category')) {	// Here we add a category
-						unset($submit_category);
-					}
-				}
-				break;
-			case 'importcsv':
-				if ($_POST['submitImport']) {
-					import_csvfile();
-				}
-				break;
-			case 'deletelink':
-				deletelinkcategory('link'); // Here we delete a link
-				break;
-			case 'deletecategory':
-				deletelinkcategory('category'); // Here we delete a category
-				break;
-			case 'editlink':
-				editlinkcategory('link'); // Here we edit a link
-				break;
-			case 'editcategory':
-				editlinkcategory('category'); // Here we edit a category
-				break;
-			case 'visible':
-				change_visibility($_GET['id'], $_GET['scope']); // Here we edit a category
-				break;
-			case 'invisible':
-				change_visibility($_GET['id'], $_GET['scope']); // Here we edit a category
-				break;
-		}
-		Security::clear_token();
-	}
+    $check_token = Security::check_token('request');
+    if ($check_token) {
+        switch ($_GET['action']) {
+            case 'addlink':
+                if ($link_submitted) {
+                    if (!addlinkcategory("link")) {	// Here we add a link
+                        unset($submit_link);
+                    }
+                }
+                break;
+            case 'addcategory':
+                if ($category_submitted) {
+                    if (!addlinkcategory('category')) {	// Here we add a category
+                        unset($submit_category);
+                    }
+                }
+                break;
+            case 'importcsv':
+                if ($_POST['submitImport']) {
+                    import_csvfile();
+                }
+                break;
+            case 'deletelink':
+                deletelinkcategory('link'); // Here we delete a link
+                break;
+            case 'deletecategory':
+                deletelinkcategory('category'); // Here we delete a category
+                break;
+            case 'editlink':
+                editlinkcategory('link'); // Here we edit a link
+                break;
+            case 'editcategory':
+                editlinkcategory('category'); // Here we edit a category
+                break;
+            case 'visible':
+                change_visibility($_GET['id'], $_GET['scope']); // Here we edit a category
+                break;
+            case 'invisible':
+                change_visibility($_GET['id'], $_GET['scope']); // Here we edit a category
+                break;
+        }
+        Security::clear_token();
+    }
 }
 $token = Security::get_token();
 
@@ -173,38 +172,38 @@ $token = Security::get_token();
 Display::display_introduction_section(TOOL_LINK);
 
 if (api_is_allowed_to_edit(null, true) && isset($_GET['action'])) {
-	echo '<div class="actions">';
-	if (!empty($_GET['lp_id']) || !empty($_POST['lp_id'])){
-		if (!empty($_POST['lp_id'])){
-			$lp_id = Security::remove_XSS($_POST['lp_id']);
-		} else {
-			$lp_id = Security::remove_XSS($_GET['lp_id']);
-		}
-		echo "<a href=\"../newscorm/lp_controller.php?".api_get_cidreq()."&gradebook=&action=add_item&type=step&lp_id=".$lp_id."#resource_tab-3\">".Display::return_icon('back.png', get_lang("BackTo").' '.get_lang("LearningPaths"),'',ICON_SIZE_MEDIUM)."</a>";
-	} else {
-		//echo '<a href="link.php?cidReq='.Security::remove_XSS($_GET['cidReq']).'&amp;urlview='.Security::remove_XSS($_GET['urlview']).'">'.Display::return_icon('back.png', get_lang('BackToLinksOverview'),'',ICON_SIZE_MEDIUM).'</a>';
-	}
-	echo '</div>';
-
-	// Displaying the correct title and the form for adding a category or link. This is only shown when nothing
-	// has been submitted yet, hence !isset($submit_link)
-	if (($_GET['action'] == 'addlink' || $_GET['action'] == 'editlink') && empty($_POST['submitLink'])) {
-
-
-
-		if ($category == '') {
-			$category = 0;
-		}
-		echo '<form class="form-horizontal" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&amp;urlview='.Security::remove_XSS($urlview).'">';
+    echo '<div class="actions">';
+    if (!empty($_GET['lp_id']) || !empty($_POST['lp_id'])){
+        if (!empty($_POST['lp_id'])){
+            $lp_id = Security::remove_XSS($_POST['lp_id']);
+        } else {
+            $lp_id = Security::remove_XSS($_GET['lp_id']);
+        }
+        echo "<a href=\"../newscorm/lp_controller.php?".api_get_cidreq()."&gradebook=&action=add_item&type=step&lp_id=".$lp_id."#resource_tab-3\">".Display::return_icon('back.png', get_lang("BackTo").' '.get_lang("LearningPaths"),'',ICON_SIZE_MEDIUM)."</a>";
+    } else {
+        //echo '<a href="link.php?cidReq='.Security::remove_XSS($_GET['cidReq']).'&amp;urlview='.Security::remove_XSS($_GET['urlview']).'">'.Display::return_icon('back.png', get_lang('BackToLinksOverview'),'',ICON_SIZE_MEDIUM).'</a>';
+    }
+    echo '</div>';
+
+    // Displaying the correct title and the form for adding a category or link. This is only shown when nothing
+    // has been submitted yet, hence !isset($submit_link)
+    if (($_GET['action'] == 'addlink' || $_GET['action'] == 'editlink') && empty($_POST['submitLink'])) {
+
+
+
+        if ($category == '') {
+            $category = 0;
+        }
+        echo '<form class="form-horizontal" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&amp;urlview='.Security::remove_XSS($urlview).'">';
         if ($_GET['action'] == 'addlink') {
-			echo '<legend>'.get_lang('LinkAdd').'</legend>';
-		} else {
-			echo '<legend>'.get_lang('LinkMod').'</legend>';
-		}
-		echo '<input type="hidden" name="sec_token" value="'.$token.'" />';
-
-		if ($_GET['action'] == 'editlink') {
-		    $clean_link_id = intval($_GET['id']);
+            echo '<legend>'.get_lang('LinkAdd').'</legend>';
+        } else {
+            echo '<legend>'.get_lang('LinkMod').'</legend>';
+        }
+        echo '<input type="hidden" name="sec_token" value="'.$token.'" />';
+
+        if ($_GET['action'] == 'editlink') {
+            $clean_link_id = intval($_GET['id']);
             $link_info = get_link_info($_GET['id']);
             if ($link_info) {
                 $urllink        = $link_info['url'];
@@ -217,308 +216,354 @@ if (api_is_allowed_to_edit(null, true) && isset($_GET['action'])) {
                 }
                 $target_link = $link_info['target'];
             }
-			echo '<input type="hidden" name="id" value="'.$clean_link_id.'" />';
-		} else {
+            echo '<input type="hidden" name="id" value="'.$clean_link_id.'" />';
+        } else {
             $target_link = "_blank";
         }
         
-		echo '	<div class="control-group url">
-					<label class="control-label">
-						<span class="form_required">*</span> URL
-					</label>
-					<div class="controls">
-						<input type="text" name="urllink" class="span6" value="' . (empty($urllink) ? 'http://' : Security::remove_XSS($urllink)) . '" />
-					</div>
-				</div>';
-		echo '	<div class="control-group title">
-					<label class="control-label">
-						'.get_lang('LinkName').'
-					</label>
-					<div class="controls">
-						<input type="text" name="title" class="span6" value="' . Security::remove_XSS($title) . '" />
-					</div>
-				</div>';
-		echo '	<div class="control-group metadata">
-					<label class="control-label">
-						'.get_lang('Metadata').'
-					</label>
-					<div class="controls">
-						<a href="../metadata/index.php?eid='.urlencode('Link.'.$clean_link_id).'">'.get_lang('AddMetadata').'</a>
-					</div>
-				</div>';
-		echo '	<div class="control-group description">
-					<label class="control-label">
-						'.get_lang('Description').'
-					</label>
-					<div class="controls">
-						<textarea class="span3" cols="50" name="description">' .	Security::remove_XSS($description) . '</textarea>
-					</div>
-				</div>';
-
-		$sqlcategories = "SELECT * FROM ".$tbl_categories." WHERE c_id = $course_id $condition_session ORDER BY display_order DESC";
-		$resultcategories = Database::query($sqlcategories);
-
-		if (Database::num_rows($resultcategories)) {
-			echo '	<div class="control-group category">
-						<label class="control-label">
-							'.get_lang('Category').'
-						</label>
-						<div class="controls">';
-			echo '			<select name="selectcategory">';
-			echo '			<option value="0">--</option>';
-			while ($myrow = Database::fetch_array($resultcategories)) {
-				echo '		<option value="'.$myrow['id'].'"';
-				if ($myrow['id'] == $category) {
-					echo ' selected';
-				}
-				echo '>'.$myrow['category_title'].'</option>';
-			}
-			echo '			</select>';
-			echo '		</div>
-					</div>';
-		}
-		echo '	<div class="control-group onhomepage">
-					<label class="control-label">
-					</label>
-					<div class="controls">
-						<input class="checkbox" type="checkbox" name="onhomepage" id="onhomepage" value="1"'.$onhomepage.'><label for="onhomepage"> '.get_lang('OnHomepage').'?</label>
-					</div>
-				</div>';
-		echo '	<div class="control-group target" id="div_target">
-					<label class="control-label">
-						'.get_lang('LinkTarget').'
-					</label>
-					<div class="controls">
-						<select  name="target_link" id="target_link">';
+        echo '	<div class="control-group url">
+                    <label class="control-label">
+                        <span class="form_required">*</span> URL
+                    </label>
+                    <div class="controls">
+                        <input type="text" name="urllink" class="span6" value="' . (empty($urllink) ? 'http://' : Security::remove_XSS($urllink)) . '" />
+                    </div>
+                </div>';
+        echo '	<div class="control-group title">
+                    <label class="control-label">
+                        '.get_lang('LinkName').'
+                    </label>
+                    <div class="controls">
+                        <input type="text" name="title" class="span6" value="' . Security::remove_XSS($title) . '" />
+                    </div>
+                </div>';
+        echo '	<div class="control-group metadata">
+                    <label class="control-label">
+                        '.get_lang('Metadata').'
+                    </label>
+                    <div class="controls">
+                        <a href="../metadata/index.php?eid='.urlencode('Link.'.$clean_link_id).'">'.get_lang('AddMetadata').'</a>
+                    </div>
+                </div>';
+        echo '	<div class="control-group description">
+                    <label class="control-label">
+                        '.get_lang('Description').'
+                    </label>
+                    <div class="controls">
+                        <textarea class="span3" cols="50" name="description">' .	Security::remove_XSS($description) . '</textarea>
+                    </div>
+                </div>';
+
+        $resultcategories = getLinkCategories($course_id, $session_id);
+
+        if (Database::num_rows($resultcategories)) {
+            echo '	<div class="control-group category">
+                        <label class="control-label">
+                            '.get_lang('Category').'
+                        </label>
+                        <div class="controls">';
+            echo '			<select name="selectcategory">';
+            echo '			<option value="0">--</option>';
+            while ($myrow = Database::fetch_array($resultcategories)) {
+                echo '		<option value="'.$myrow['id'].'"';
+                if ($myrow['id'] == $category) {
+                    echo ' selected';
+                }
+                echo '>'.$myrow['category_title'].'</option>';
+            }
+            echo '			</select>';
+            echo '		</div>
+                    </div>';
+        }
+        echo '	<div class="control-group onhomepage">
+                    <label class="control-label">
+                    </label>
+                    <div class="controls">
+                        <input class="checkbox" type="checkbox" name="onhomepage" id="onhomepage" value="1"'.$onhomepage.'><label for="onhomepage"> '.get_lang('OnHomepage').'?</label>
+                    </div>
+                </div>';
+        echo '	<div class="control-group target" id="div_target">
+                    <label class="control-label">
+                        '.get_lang('LinkTarget').'
+                    </label>
+                    <div class="controls">
+                        <select  name="target_link" id="target_link">';
         $targets = array('_self'=>get_lang('LinkOpenSelf'),'_blank'=>get_lang('LinkOpenBlank'),'_parent'=>get_lang('LinkOpenParent'),'_top'=>get_lang('LinkOpenTop'));
-		foreach ($targets as $target_id => $target) {
-			$selected = '';
-			if ($target_id == $target_link) {
-				$selected = ' selected="selected"';
-			}
-			echo '    	<option value="'.$target_id.'"'.$selected.'>'.$target.'</option> ';
-		}
-		echo '        </select>
-		<span class="help-block">
+        foreach ($targets as $target_id => $target) {
+            $selected = '';
+            if ($target_id == $target_link) {
+                $selected = ' selected="selected"';
+            }
+            echo '    	<option value="'.$target_id.'"'.$selected.'>'.$target.'</option> ';
+        }
+        echo '        </select>
+        <span class="help-block">
             '.get_lang('AddTargetOfLinkOnHomepage').'
             </span>
-					</div>
-				</div>';
-
-		if (api_get_setting('search_enabled') == 'true') {
-			require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
-			$specific_fields = get_specific_field_list();
-
-			echo '	<div class="control-group index">
-						<label class="control-label">
-							'.get_lang('SearchFeatureDoIndexLink').'
-						</label>
-						<div class="controls">
+                    </div>
+                </div>';
+
+        if (api_get_setting('search_enabled') == 'true') {
+            require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
+            $specific_fields = get_specific_field_list();
+
+            echo '	<div class="control-group index">
+                        <label class="control-label">
+                            '.get_lang('SearchFeatureDoIndexLink').'
+                        </label>
+                        <div class="controls">
                             <label for="index_document">
-							<input class="checkbox" type="checkbox" name="index_document" id="index_document" checked="checked">
+                            <input class="checkbox" type="checkbox" name="index_document" id="index_document" checked="checked">
                             '.get_lang('Yes').'
                             </label>
-						</div>
+                        </div>
                     </div>';
 
-			foreach ($specific_fields as $specific_field) {
-				$default_values = '';
-				if ($_GET['action'] == 'editlink') {
-					$filter = array('field_id' => $specific_field['id'], 'ref_id' => intval($_GET['id']), 'tool_id' => '\''. TOOL_LINK .'\'');
-					$values = get_specific_field_values_list($filter, array('value'));
-					if (!empty($values)) {
-						$arr_str_values = array();
-						foreach ($values as $value) {
-							$arr_str_values[] = $value['value'];
-						}
-						$default_values = implode(', ', $arr_str_values);
-					}
-				}
-
-				$sf_textbox = '
-						<div class="control-group">
-							<label class="control-label">%s</label>
-							<div class="controls">
-								<input name="%s" type="text" value="%s"/>
-							</div>
-						</div>';
-
-				echo sprintf($sf_textbox, $specific_field['name'], $specific_field['code'], $default_values);
-			}
-		}
-		//echo '<input type="hidden" name="origin"  value="' . Security::remove_XSS($_GET['origin']) . '" />';
-		echo '<input type="hidden" name="lp_id"  value="' . Security::remove_XSS($_GET['lp_id']) . '" />';
-		echo '<div class="control-group">
-					<label class="control-label">
-					</label>
-					<div class="controls">
-						<button class="btn save" type="submit" name="submitLink" value="OK">'.get_lang('SaveLink').'</button>
-					</div>
-				</div>';
-		echo '</form>';
-	} elseif(($_GET['action'] == 'addcategory' || $_GET['action'] == 'editcategory') && !$submit_category) {
-		echo '<form class="form-horizontal " method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&amp;urlview='.Security::remove_XSS($urlview).'">';
+            foreach ($specific_fields as $specific_field) {
+                $default_values = '';
+                if ($_GET['action'] == 'editlink') {
+                    $filter = array('field_id' => $specific_field['id'], 'ref_id' => intval($_GET['id']), 'tool_id' => '\''. TOOL_LINK .'\'');
+                    $values = get_specific_field_values_list($filter, array('value'));
+                    if (!empty($values)) {
+                        $arr_str_values = array();
+                        foreach ($values as $value) {
+                            $arr_str_values[] = $value['value'];
+                        }
+                        $default_values = implode(', ', $arr_str_values);
+                    }
+                }
+
+                $sf_textbox = '
+                        <div class="control-group">
+                            <label class="control-label">%s</label>
+                            <div class="controls">
+                                <input name="%s" type="text" value="%s"/>
+                            </div>
+                        </div>';
+
+                echo sprintf($sf_textbox, $specific_field['name'], $specific_field['code'], $default_values);
+            }
+        }
+        //echo '<input type="hidden" name="origin"  value="' . Security::remove_XSS($_GET['origin']) . '" />';
+        echo '<input type="hidden" name="lp_id"  value="' . Security::remove_XSS($_GET['lp_id']) . '" />';
+        echo '<div class="control-group">
+                    <label class="control-label">
+                    </label>
+                    <div class="controls">
+                        <button class="btn save" type="submit" name="submitLink" value="OK">'.get_lang('SaveLink').'</button>
+                    </div>
+                </div>';
+        echo '</form>';
+    } elseif(($_GET['action'] == 'addcategory' || $_GET['action'] == 'editcategory') && !$submit_category) {
+        echo '<form class="form-horizontal " method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&amp;urlview='.Security::remove_XSS($urlview).'">';
 
         if ($_GET['action'] == 'addcategory') {
-			echo '<legend>'.get_lang('CategoryAdd').'</legend>';
-			$my_cat_title = get_lang('CategoryAdd');
-		} else {
-			echo '<legend>'.get_lang('CategoryMod').'</legend>';
-			$my_cat_title = get_lang('CategoryMod');
-		}
-
-		echo '<input type="hidden" name="sec_token" value="'.$token.'" />';
-		if ($_GET['action'] == 'editcategory') {
-			echo '<input type="hidden" name="id" value="'.$id.'" />';
-		}
-		echo '	<div class="control-group category">
-					<label class="control-label">
-						<span class="form_required">*</span> '.get_lang('CategoryName').'
-					</label>
-					<div class="controls">
-						<input type="text" name="category_title" size="50" value="'.Security::remove_XSS($category_title).'" />
-					</div>
-				</div>';
-
-		echo '	<div class="control-group description">
-					<label class="control-label">
-						'.get_lang('Description').'
-					</label>
-					<div class="controls">
-						<textarea rows="3" cols="50" name="description">'.Security::remove_XSS($description).'</textarea>
-					</div>
-				</div>';
-
-		echo '	<div class="control-group">
-					<label class="control-label">
-					</label>
-					<div class="controls">
-						<button class="btn save" type="submit" name="submitCategory">'.$my_cat_title.' </button>
-					</div>
-				</div>';
-		echo "</form>";
-	}
+            echo '<legend>'.get_lang('CategoryAdd').'</legend>';
+            $my_cat_title = get_lang('CategoryAdd');
+        } else {
+            echo '<legend>'.get_lang('CategoryMod').'</legend>';
+            $my_cat_title = get_lang('CategoryMod');
+        }
+
+        echo '<input type="hidden" name="sec_token" value="'.$token.'" />';
+        if ($_GET['action'] == 'editcategory') {
+            echo '<input type="hidden" name="id" value="'.$id.'" />';
+        }
+        echo '	<div class="control-group category">
+                    <label class="control-label">
+                        <span class="form_required">*</span> '.get_lang('CategoryName').'
+                    </label>
+                    <div class="controls">
+                        <input type="text" name="category_title" size="50" value="'.Security::remove_XSS($category_title).'" />
+                    </div>
+                </div>';
+
+        echo '	<div class="control-group description">
+                    <label class="control-label">
+                        '.get_lang('Description').'
+                    </label>
+                    <div class="controls">
+                        <textarea rows="3" cols="50" name="description">'.Security::remove_XSS($description).'</textarea>
+                    </div>
+                </div>';
+
+        echo '	<div class="control-group">
+                    <label class="control-label">
+                    </label>
+                    <div class="controls">
+                        <button class="btn save" type="submit" name="submitCategory">'.$my_cat_title.' </button>
+                    </div>
+                </div>';
+        echo "</form>";
+    }
 }
 
 if (!empty($down)) {
-	movecatlink($down);
+    movecatlink($down);
 }
 if (!empty($up)) {
-	movecatlink($up);
+    movecatlink($up);
 }
 
 if (empty($_GET['action']) || ($_GET['action'] != 'editlink' && $_GET['action'] != 'addcategory' && $_GET['action'] != 'addlink') || $link_submitted || $category_submitted) {
 
-	/*	Action Links */
-
-	echo '<div class="actions">';
-	if (api_is_allowed_to_edit(null, true)) {
-		$urlview = Security::remove_XSS($urlview);
-		echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=addlink&amp;category='.(!empty($category) ? $category : '').'&amp;urlview='.$urlview.'">'.Display::return_icon('new_link.png', get_lang('LinkAdd'),'',ICON_SIZE_MEDIUM).'</a>';
-		echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=addcategory&amp;urlview='.$urlview.'">'.Display::return_icon('new_folder.png', get_lang('CategoryAdd'),'',ICON_SIZE_MEDIUM).'</a>';
-
-		   /* "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=importcsv&amp;urlview=".$urlview."\">".get_lang('CsvImport')."</a>\n", // RH*/
-	}
-	// Making the show none / show all links. Show none means urlview=0000 (number of zeros depending on the
-	// number of categories). Show all means urlview=1111 (number of 1 depending on teh number of categories).
-	$sqlcategories = "SELECT * FROM ".$tbl_categories." WHERE c_id = $course_id $condition_session ORDER BY display_order DESC";
-	$resultcategories = Database::query($sqlcategories);
-	$aantalcategories = Database::num_rows($resultcategories);
-	if ($aantalcategories > 0) {
-	    $resultcategories = Database::query($sqlcategories);
-		echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&urlview=';
-		for ($j = 1; $j <= $aantalcategories; $j++) {
-			echo '0';
-		}
-		echo '">'.Display::return_icon('view_remove.png', $shownone,'',ICON_SIZE_MEDIUM).'</a>';
-		echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&urlview=';
-		for ($j = 1; $j <= $aantalcategories; $j++) {
-			echo '1';
-		}
-		echo '">'.Display::return_icon('view_tree.png', $showall,'',ICON_SIZE_MEDIUM).'</a>';
-	}
-	echo '</div>';
-
-	// Displaying the links which have no category (thus category = 0 or NULL), if none present this will not be displayed
-	$sqlLinks = "SELECT * FROM ".$tbl_link." WHERE c_id = $course_id AND category_id=0 OR category_id IS NULL";
-	$result = Database::query($sqlLinks);
-	$numberofzerocategory = Database::num_rows($result);
-
-	if ($numberofzerocategory !== 0) {
-	    echo '<table class="data_table">';
-		echo '<tr><th style="font-weight: bold; text-align:left;padding-left: 10px;">'.get_lang('General').'</th></tr>';
-		echo '</table>';
-		showlinksofcategory(0);
-	}
-
-	$i = 0;
-	$catcounter = 1;
-	$view = '0';
-
-	while ($myrow = Database::fetch_array($resultcategories)) {
-		// Validacion when belongs to a session
-		$session_img = api_get_session_image($myrow['session_id'], $_user['status']);
-
-		//if (!isset($urlview)) {
-		if ($urlview == '') {
-			// No $view set in the url, thus for each category link it should be all zeros except it's own
-			makedefaultviewcode($i);
-		} else {
-			$view = $urlview;
-			$view[$i] = '1';
-		}
-		// If the $urlview has a 1 for this categorie, this means it is expanded and should be desplayed as a
-		// - instead of a +, the category is no longer clickable and all the links of this category are displayed
-		$myrow['description'] = text_filter($myrow['description']);
-
-		if (isset($urlview[$i]) && $urlview[$i] == '1') {
-			$newurlview = $urlview;
-			$newurlview[$i] = '0';
-
-			echo '<tr>';
-				echo '<table class="data_table">';
-				echo '<tr>';
-					echo '<th width="81%" style="font-weight: bold; text-align:left;padding-left: 5px;">';
-					echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;urlview='.Security::remove_XSS($newurlview).'">';
-					echo '<img src="../img/icons/22/view_remove.png" />&nbsp;&nbsp;'.Security::remove_XSS($myrow['category_title']).'</a><br />&nbsp;&nbsp;&nbsp;'.$myrow['description'];
-					echo '</th>';
-					if (api_is_allowed_to_edit(null, true)) {
-						if ($session_id == $myrow['session_id']) {
-							echo '<th>';
-							showcategoryadmintools($myrow['id']);
-							echo '</th>';
-						} else {
-							echo '<th>'.get_lang('EditionNotAvailableFromSession');
-						}
-					}
-				echo '</tr>';
-				echo '</table>';
-				echo showlinksofcategory($myrow['id']);
-			echo '</tr>';
-		} else {
-			echo '<tr>';
-				echo '<table class="data_table">';
-				echo '<tr>';
-					echo '<th width="81%" style="font-weight: bold; text-align:left;padding-left: 5px;"><a href="'.api_get_self().'?'.api_get_cidreq().'&amp;urlview=';
-					echo is_array($view) ? implode('', $view) : $view;
-					echo '"><img src="../img/icons/22/view_tree.png" />&nbsp;&nbsp;'.Security::remove_XSS($myrow['category_title']).$session_img;
-					echo'</a><br />&nbsp;&nbsp;&nbsp;';
-					echo $myrow['description'];
-					if (api_is_allowed_to_edit(null, true)) {
-						echo '<th style="text-align:center;">';
-						showcategoryadmintools($myrow['id']);
-						echo '</th>';
-					}
-					echo '</th>';
-				echo '</tr>';
-
-				echo '</table>';
-			echo '</tr>';
-		}
-		// Displaying the link of the category
-		$i++;
-	}
-	echo '</table>';
+    /*	Action Links */
+
+    echo '<div class="actions">';
+    if (api_is_allowed_to_edit(null, true)) {
+        $urlview = Security::remove_XSS($urlview);
+        echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=addlink&amp;category='.(!empty($category) ? $category : '').'&amp;urlview='.$urlview.'">'.Display::return_icon('new_link.png', get_lang('LinkAdd'),'',ICON_SIZE_MEDIUM).'</a>';
+        echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=addcategory&amp;urlview='.$urlview.'">'.Display::return_icon('new_folder.png', get_lang('CategoryAdd'),'',ICON_SIZE_MEDIUM).'</a>';
+
+           /* "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=importcsv&amp;urlview=".$urlview."\">".get_lang('CsvImport')."</a>\n", // RH*/
+    }
+    // Making the show none / show all links. Show none means urlview=0000 (number of zeros depending on the
+    // number of categories). Show all means urlview=1111 (number of 1 depending on teh number of categories).
+    $resultcategories = getLinkCategories($course_id, $session_id);
+    $aantalcategories = Database::num_rows($resultcategories);
+    if ($aantalcategories > 0) {
+        echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&urlview=';
+        for ($j = 1; $j <= $aantalcategories; $j++) {
+            echo '0';
+        }
+        echo '">'.Display::return_icon('view_remove.png', $shownone,'',ICON_SIZE_MEDIUM).'</a>';
+        echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&urlview=';
+        for ($j = 1; $j <= $aantalcategories; $j++) {
+            echo '1';
+        }
+        echo '">'.Display::return_icon('view_tree.png', $showall,'',ICON_SIZE_MEDIUM).'</a>';
+    }
+    echo '</div>';
+
+    // Displaying the links which have no category (thus category = 0 or NULL), if none present this will not be displayed
+    $sqlLinks = "SELECT * FROM ".$tbl_link." WHERE c_id = $course_id AND category_id=0 OR category_id IS NULL";
+    $result = Database::query($sqlLinks);
+    $numberofzerocategory = Database::num_rows($result);
+
+    if ($numberofzerocategory !== 0) {
+        echo '<table class="data_table">';
+        echo '<tr><th style="font-weight: bold; text-align:left;padding-left: 10px;">'.get_lang('General').'</th></tr>';
+        echo '</table>';
+        showlinksofcategory(0);
+    }
+
+    $i = 0;
+    $catcounter = 1;
+    $view = '0';
+
+    while ($myrow = Database::fetch_array($resultcategories)) {
+        // Validacion when belongs to a session
+        $session_img = api_get_session_image($myrow['session_id'], $_user['status']);
+
+        //if (!isset($urlview)) {
+        if ($urlview == '') {
+            // No $view set in the url, thus for each category link it should be all zeros except it's own
+            makedefaultviewcode($i);
+        } else {
+            $view = $urlview;
+            $view[$i] = '1';
+        }
+        // If the $urlview has a 1 for this categorie, this means it is expanded and should be desplayed as a
+        // - instead of a +, the category is no longer clickable and all the links of this category are displayed
+        $myrow['description'] = text_filter($myrow['description']);
+
+
+        $strVisibility = '';
+        if ($myrow['visibility'] == '1') {
+            $strVisibility =  '<a href="link.php?' . api_get_cidreq() .  '&amp;sec_token='.$token.'&amp;action=invisible&amp;id=' . $myrow['id'] . '&amp;scope=' . TOOL_LINK_CATEGORY . '" title="' . get_lang('Hide') . '">' .
+                Display :: return_icon('visible.png', get_lang('Hide'), array (), ICON_SIZE_SMALL) . '</a>';
+        } elseif ($myrow['visibility'] == '0') {
+            $strVisibility =  ' <a href="link.php?' . api_get_cidreq() .  '&amp;sec_token='.$token.'&amp;action=visible&amp;id=' . $myrow['id'] . '&amp;scope=' . TOOL_LINK_CATEGORY . '" title="' . get_lang('Show') . '">' .
+                Display :: return_icon('invisible.png', get_lang('Show'), array (), ICON_SIZE_SMALL) . '</a>';
+        }
+
+        if ($myrow['visibility'] == '1') {
+
+            if (isset($urlview[$i]) && $urlview[$i] == '1') {
+                $newurlview = $urlview;
+                $newurlview[$i] = '0';
+                echo '<tr>';
+                    echo '<table class="data_table">';
+                    echo '<tr>';
+                        echo '<th width="81%" style="font-weight: bold; text-align:left;padding-left: 5px;">';
+                        echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;urlview='.Security::remove_XSS($newurlview).'">';
+                        echo '<img src="../img/icons/22/view_remove.png" />&nbsp;&nbsp;'.Security::remove_XSS($myrow['category_title']).'</a><br />&nbsp;&nbsp;&nbsp;'.$myrow['description'];
+                        echo '</th>';
+                        if (api_is_allowed_to_edit(null, true)) {
+                            if ($session_id == $myrow['session_id']) {
+                                echo '<th>'; echo $strVisibility; showcategoryadmintools($myrow['id']); echo '</th>';
+                            } else {
+                                echo '<th>'.get_lang('EditionNotAvailableFromSession');
+                            }
+                        }
+                    echo '</tr>';
+                    echo '</table>';
+                    echo showlinksofcategory($myrow['id']);
+                echo '</tr>';
+            } else {
+                echo '<tr>';
+                    echo '<table class="data_table">';
+                    echo '<tr>';
+                        echo '<th width="81%" style="font-weight: bold; text-align:left;padding-left: 5px;"><a href="'.api_get_self().'?'.api_get_cidreq().'&amp;urlview=';
+                        echo is_array($view) ? implode('', $view) : $view;
+                        echo '"><img src="../img/icons/22/view_tree.png" />&nbsp;&nbsp;'.Security::remove_XSS($myrow['category_title']).$session_img;
+                        echo'</a><br />&nbsp;&nbsp;&nbsp;';
+                        echo $myrow['description'];
+                        if (api_is_allowed_to_edit(null, true)) {
+                            echo '<th style="text-align:center;">'; echo $strVisibility; showcategoryadmintools($myrow['id']); echo '</th>';
+                        }
+                        echo '</th>';
+                    echo '</tr>';
+                    echo '</table>';
+                echo '</tr>';
+            }
+
+        } else { // NO VISIBLES
+            if (api_is_allowed_to_edit(null, true)) {
+                if (isset($urlview[$i]) && $urlview[$i] == '1') {
+                    $newurlview = $urlview;
+                    $newurlview[$i] = '0';
+                    echo '<tr>';
+                    echo '<table class="data_table">';
+                    echo '<tr>';
+                    echo '<th width="81%" style="font-weight: bold; text-align:left;padding-left: 5px;">';
+                    echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;urlview='.Security::remove_XSS($newurlview).'">';
+                    echo '<img src="../img/icons/22/view_remove_na.png" />&nbsp;&nbsp;'.Security::remove_XSS($myrow['category_title']).'</a><br />&nbsp;&nbsp;&nbsp;'.$myrow['description'];
+                    echo '</th>';
+                    if (api_is_allowed_to_edit(null, true)) {
+                        if ($session_id == $myrow['session_id']) {
+                            echo '<th>'; echo $strVisibility; showcategoryadmintools($myrow['id']); echo '</th>';
+                        } else {
+                            echo '<th>'.get_lang('EditionNotAvailableFromSession');
+                        }
+                    }
+                    echo '</tr>';
+                    echo '</table>';
+                    echo showlinksofcategory($myrow['id']);
+                    echo '</tr>';
+                } else {
+                    echo '<tr>';
+                    echo '<table class="data_table">';
+                    echo '<tr>';
+                    echo '<th width="81%" style="font-weight: bold; text-align:left;padding-left: 5px;"><a href="'.api_get_self().'?'.api_get_cidreq().'&amp;urlview=';
+                    echo is_array($view) ? implode('', $view) : $view;
+                    echo '"><img src="../img/icons/22/view_tree_na.png" />&nbsp;&nbsp;'.Security::remove_XSS($myrow['category_title']).$session_img;
+                    echo'</a><br />&nbsp;&nbsp;&nbsp;';
+                    echo $myrow['description'];
+                    if (api_is_allowed_to_edit(null, true)) {
+                        echo '<th style="text-align:center;">'; echo $strVisibility; showcategoryadmintools($myrow['id']); echo '</th>';
+                    }
+                    echo '</th>';
+                    echo '</tr>';
+                    echo '</table>';
+                    echo '</tr>';
+                }
+            }
+        }
+        // Displaying the link of the category
+        $i++;
+    }
+    echo '</table>';
 }
 
 Display::display_footer();

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

@@ -10,89 +10,89 @@ require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
  */
 class MySpace
 {
-	/**
-	 * This function serves exporting data in CSV format.
-	 * @param array $header			The header labels.
-	 * @param array $data			The data array.
-	 * @param string $file_name		The name of the file which contains exported data.
-	 * @return string mixed				Returns a message (string) if an error occurred.
-	 */
-	function export_csv($header, $data, $file_name = 'export.csv') {
-
-		$archive_path = api_get_path(SYS_ARCHIVE_PATH);
-		$archive_url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive=';
-
-		if (!$open = fopen($archive_path.$file_name, 'w+')) {
-			$message = get_lang('noOpen');
-		} else {
-			$info = '';
-
-			foreach ($header as $value) {
-				$info .= $value.';';
-			}
-			$info .= "\r\n";
-
-			foreach ($data as $row) {
-				foreach ($row as $value) {
-					$info .= $value.';';
-				}
-				$info .= "\r\n";
-			}
-
-			fwrite($open, $info);
-			fclose($open);
-			@chmod($file_name, api_get_permissions_for_new_files());
-
-			header("Location:".$archive_url.$file_name);
-		}
-		return $message;
-	}
-
-	/**
-	 * Gets the connections to a course as an array of login and logout time
-	 *
-	 * @param 	int 	User ud
-	 * @param 	string 	Course code
-	 * @param	int		Session id (optional, default = 0)
-	 * @return 	array   Conections
-	 */
-	static function get_connections_to_course($user_id, $course_code, $session_id = 0)
+    /**
+     * This function serves exporting data in CSV format.
+     * @param array $header         The header labels.
+     * @param array $data           The data array.
+     * @param string $file_name     The name of the file which contains exported data.
+     * @return string mixed             Returns a message (string) if an error occurred.
+     */
+    function export_csv($header, $data, $file_name = 'export.csv') {
+
+        $archive_path = api_get_path(SYS_ARCHIVE_PATH);
+        $archive_url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive=';
+
+        if (!$open = fopen($archive_path.$file_name, 'w+')) {
+            $message = get_lang('noOpen');
+        } else {
+            $info = '';
+
+            foreach ($header as $value) {
+                $info .= $value.';';
+            }
+            $info .= "\r\n";
+
+            foreach ($data as $row) {
+                foreach ($row as $value) {
+                    $info .= $value.';';
+                }
+                $info .= "\r\n";
+            }
+
+            fwrite($open, $info);
+            fclose($open);
+            @chmod($file_name, api_get_permissions_for_new_files());
+
+            header("Location:".$archive_url.$file_name);
+        }
+        return $message;
+    }
+
+    /**
+     * Gets the connections to a course as an array of login and logout time
+     *
+     * @param   int     User ud
+     * @param   string  Course code
+     * @param   int     Session id (optional, default = 0)
+     * @return  array   Conections
+     */
+    static function get_connections_to_course($user_id, $course_code, $session_id = 0)
     {
-		// Database table definitions
-	    $tbl_track_course 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+        // Database table definitions
+        $tbl_track_course = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
 
-		// protect data
-		$user_id     = intval($user_id);
-		$course_code = Database::escape_string($course_code);
-		$session_id  = intval($session_id);
+        // protect data
+        $user_id     = intval($user_id);
+        $course_code = Database::escape_string($course_code);
+        $session_id  = intval($session_id);
 
-	    $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . '
+        $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . '
                 WHERE   user_id = '.$user_id.' AND
                         course_code="'.$course_code.'" AND
                         session_id = '.$session_id.'
                 ORDER BY login_course_date ASC';
-	    $rs = Database::query($sql);
-	    $connections = array();
+        $rs = Database::query($sql);
+        $connections = array();
 
-	    while ($row = Database::fetch_array($rs)) {
-	        $timestamp_login_date = api_strtotime($row['login_course_date'], 'UTC');
-	        $timestamp_logout_date = api_strtotime($row['logout_course_date'], 'UTC');
-	        $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
-	    }
-	    return $connections;
-	}
+        while ($row = Database::fetch_array($rs)) {
+            $timestamp_login_date = api_strtotime($row['login_course_date'], 'UTC');
+            $timestamp_logout_date = api_strtotime($row['logout_course_date'], 'UTC');
+            $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
+        }
+        return $connections;
+    }
 
     static function get_connections_from_course_list($user_id, $course_list, $session_id = 0) {
-		// Database table definitions
-	    $tbl_track_course 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+        // Database table definitions
+        $tbl_track_course = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
         if (empty($course_list)) {
             return false;
         }
 
-		// protect data
-		$user_id     = intval($user_id);
-		$course_code = Database::escape_string($course_code);
-		$session_id  = intval($session_id);
+        // protect data
+        $user_id     = intval($user_id);
+        $course_code = Database::escape_string($course_code);
+        $session_id  = intval($session_id);
         $new_course_list = array();;
         foreach ($course_list as $course_item) {
             $new_course_list[] =  '"'.Database::escape_string($course_item['code']).'"';
@@ -102,170 +102,170 @@ class MySpace
         if (empty($course_list)) {
             return false;
         }
-	    $sql = 'SELECT login_course_date, logout_course_date, course_code FROM ' . $tbl_track_course . '
+        $sql = 'SELECT login_course_date, logout_course_date, course_code FROM ' . $tbl_track_course . '
                 WHERE   user_id = '.$user_id.' AND
                         course_code IN ('.$course_list.') AND
                         session_id = '.$session_id.'
                 ORDER BY login_course_date ASC';
-	    $rs = Database::query($sql);
-	    $connections = array();
-
-	    while ($row = Database::fetch_array($rs)) {
-	        $timestamp_login_date = api_strtotime($row['login_course_date'], 'UTC');
-	        $timestamp_logout_date = api_strtotime($row['logout_course_date'], 'UTC');
-	        $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date,'course_code' => $row['course_code']);
-	    }
-	    return $connections;
-	}
-
-	/**
-	 * TODO: Not used, to b deleted?
-	 * Enter description here...
-	 * @param int $user_id
-	 * @param string $course_code
-	 * @param date $year
-	 * @param date $month
-	 * @param date $day
-	 * @return unknown
-	 */
-	static function get_connections_to_course_by_time($user_id, $course_code, $year = '', $month = '', $day = '') {
-		// Database table definitions
-	    $tbl_track_course 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
-
-	    $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . '
-	    				WHERE user_id = ' . intval($user_id) . '
-	    				AND course_code="' . Database::escape_string($course_code) . '"
-	    				ORDER BY login_course_date DESC';
-
-	    $rs = Database::query($sql);
-	    $connections = array();
-	    while ($row = Database::fetch_array($rs)) {
-	        $login_date = $row['login_course_date'];
-	        $logout_date = $row['logout_course_date'];
-	        $timestamp_login_date = strtotime($login_date);
-	        $timestamp_logout_date = strtotime($logout_date);
-	        $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
-	    }
-	    return $connections;
-	}
-
-	/**
-	 * Creates a small table in the last column of the table with the user overview
-	 *
-	 * @param integer $user_id the id of the user
-	 * @param array $url_params additonal url parameters
-	 * @param array $row the row information (the other columns)
-	 * @return string html code
-	 */
-	function course_info_tracking_filter($user_id, $url_params, $row) {
-		// the table header
-		$return .= '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
-		/*$return .= '	<tr>';
-		$return .= '		<th>'.get_lang('Course').'</th>';
-		$return .= '		<th>'.get_lang('AvgTimeSpentInTheCourse').'</th>';
-		$return .= '		<th>'.get_lang('AvgStudentsProgress').'</th>';
-		$return .= '		<th>'.get_lang('AvgCourseScore').'</th>';
-		$return .= '		<th>'.get_lang('AvgExercisesScore').'</th>';
-		$return .= '		<th>'.get_lang('AvgMessages').'</th>';
-		$return .= '		<th>'.get_lang('AvgAssignments').'</th>';
-		$return .= '		<th>'.get_lang('TotalExercisesScoreObtained').'</th>';
-		$return .= '		<th>'.get_lang('TotalExercisesScorePossible').'</th>';
-		$return .= '		<th>'.get_lang('TotalExercisesAnswered').'</th>';
-		$return .= '		<th>'.get_lang('TotalExercisesScorePercentage').'</th>';
-		$return .= '		<th>'.get_lang('FirstLogin').'</th>';
-		$return .= '		<th>'.get_lang('LatestLogin').'</th>';
-		$return .= '	</tr>';*/
-
-		// database table definition
-		$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-
-		// getting all the courses of the user
-		$sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".Database::escape_string($user_id)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
-		$result = Database::query($sql);
-		while ($row = Database::fetch_row($result)) {
-			$return .= '<tr>';
-			// course code
-			$return .= '	<td width="157px" >'.cut($row[0], 20, true).'</td>';
-			// time spent in the course
-			$return .= '	<td><div>'.api_time_to_hms(Tracking :: get_time_spent_on_the_course($user_id, $row[0])).'</div></td>';
-			// student progress in course
-			$return .= '	<td><div>'.round(Tracking :: get_avg_student_progress($user_id, $row[0]), 2).'</div></td>';
-			// student score
-			$avg_score = Tracking :: get_avg_student_score($user_id, $row[0]);
-			if (is_numeric($avg_score)) {
-				$avg_score = round($avg_score,2);
-			} else {
-				$$avg_score = '-';
-			}
-
-			$return .= '	<td><div>'.$avg_score.'</div></td>';
-			// student tes score
-			//$return .= '	<td><div style="width:40px">'.round(Tracking :: get_avg_student_exercise_score ($user_id, $row[0]),2).'%</div></td>';
-			// student messages
-			$return .= '	<td><div>'.Tracking :: count_student_messages($user_id, $row[0]).'</div></td>';
-			// student assignments
-			$return .= '	<td><div>'.Tracking :: count_student_assignments($user_id, $row[0]).'</div></td>';
-			// student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
-			$exercises_results = MySpace::exercises_results($user_id, $row[0]);
-			$return .= '	<td width="105px"><div>'.(is_null($exercises_results['percentage']) ? '' : $exercises_results['score_obtained'].'/'.$exercises_results['score_possible'].' ( '.$exercises_results['percentage'].'% )').'</div></td>';
-			//$return .= '	<td><div>'.$exercises_results['score_possible'].'</div></td>';
-			$return .= '	<td><div>'.$exercises_results['questions_answered'].'</div></td>';
-			//$return .= '	<td><div>'.$exercises_results['percentage'].'% </div></td>';
-			// first connection
-			//$return .= '	<td width="60px">'.Tracking :: get_first_connection_date_on_the_course ($user_id, $row[0]).'</td>';
-			// last connection
-			$return .= '	<td><div>'.Tracking :: get_last_connection_date_on_the_course ($user_id, $row[0]).'</div></td>';
-			$return .= '<tr>';
-		}
-		$return .= '</table>';
-		return $return;
-	}
-
-	/**
-	 * Display a sortable table that contains an overview off all the reporting progress of all users and all courses the user is subscribed to
-	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
-	 * @version Dokeos 1.8.6
-	 * @since October 2008
-	 */
-	function display_tracking_user_overview() {
-		MySpace::display_user_overview_export_options();
-
-		$t_head .= '	<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
-		//$t_head .= '	<caption>'.get_lang('CourseInformation').'</caption>';
-		$t_head .=		'<tr>';
-		$t_head .= '		<th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
-		//$t_head .= '		<th><div style="width:40px">'.get_lang('AvgExercisesScore').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
-		$t_head .= '		<th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
-		//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePossible').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
-		//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePercentage').'</div></th>';
-		//$t_head .= '		<th><div style="width:60px">'.get_lang('FirstLogin').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
-		$t_head .= '	</tr></table>';
-
-		$addparams = array('view' => 'admin', 'display' => 'useroverview');
-
-		$table = new SortableTable('tracking_user_overview', array('MySpace','get_number_of_users_tracking_overview'), array('MySpace','get_user_data_tracking_overview'), 0);
-		$table->additional_parameters = $addparams;
-
-		$table->set_header(0, get_lang('OfficialCode'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-		if (api_is_western_name_order()) {
-			$table->set_header(1, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-			$table->set_header(2, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-		} else {
-			$table->set_header(1, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-			$table->set_header(2, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-		}
-		$table->set_header(3, get_lang('LoginName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-		$table->set_header(4, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
-		$table->set_column_filter(4, array('MySpace','course_info_tracking_filter'));
-		$table->display();
-	}
+        $rs = Database::query($sql);
+        $connections = array();
+
+        while ($row = Database::fetch_array($rs)) {
+            $timestamp_login_date = api_strtotime($row['login_course_date'], 'UTC');
+            $timestamp_logout_date = api_strtotime($row['logout_course_date'], 'UTC');
+            $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date,'course_code' => $row['course_code']);
+        }
+        return $connections;
+    }
+
+    /**
+     * TODO: Not used, to b deleted?
+     * Enter description here...
+     * @param int $user_id
+     * @param string $course_code
+     * @param date $year
+     * @param date $month
+     * @param date $day
+     * @return unknown
+     */
+    static function get_connections_to_course_by_time($user_id, $course_code, $year = '', $month = '', $day = '') {
+        // Database table definitions
+        $tbl_track_course = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+
+        $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . '
+                        WHERE user_id = ' . intval($user_id) . '
+                        AND course_code="' . Database::escape_string($course_code) . '"
+                        ORDER BY login_course_date DESC';
+
+        $rs = Database::query($sql);
+        $connections = array();
+        while ($row = Database::fetch_array($rs)) {
+            $login_date = $row['login_course_date'];
+            $logout_date = $row['logout_course_date'];
+            $timestamp_login_date = strtotime($login_date);
+            $timestamp_logout_date = strtotime($logout_date);
+            $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
+        }
+        return $connections;
+    }
+
+    /**
+     * Creates a small table in the last column of the table with the user overview
+     *
+     * @param integer $user_id the id of the user
+     * @param array $url_params additonal url parameters
+     * @param array $row the row information (the other columns)
+     * @return string html code
+     */
+    function course_info_tracking_filter($user_id, $url_params, $row) {
+        // the table header
+        $return .= '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
+        /*$return .= '  <tr>';
+        $return .= '        <th>'.get_lang('Course').'</th>';
+        $return .= '        <th>'.get_lang('AvgTimeSpentInTheCourse').'</th>';
+        $return .= '        <th>'.get_lang('AvgStudentsProgress').'</th>';
+        $return .= '        <th>'.get_lang('AvgCourseScore').'</th>';
+        $return .= '        <th>'.get_lang('AvgExercisesScore').'</th>';
+        $return .= '        <th>'.get_lang('AvgMessages').'</th>';
+        $return .= '        <th>'.get_lang('AvgAssignments').'</th>';
+        $return .= '        <th>'.get_lang('TotalExercisesScoreObtained').'</th>';
+        $return .= '        <th>'.get_lang('TotalExercisesScorePossible').'</th>';
+        $return .= '        <th>'.get_lang('TotalExercisesAnswered').'</th>';
+        $return .= '        <th>'.get_lang('TotalExercisesScorePercentage').'</th>';
+        $return .= '        <th>'.get_lang('FirstLogin').'</th>';
+        $return .= '        <th>'.get_lang('LatestLogin').'</th>';
+        $return .= '    </tr>';*/
+
+        // database table definition
+        $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+
+        // getting all the courses of the user
+        $sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".Database::escape_string($user_id)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
+        $result = Database::query($sql);
+        while ($row = Database::fetch_row($result)) {
+            $return .= '<tr>';
+            // course code
+            $return .= '    <td width="157px" >'.cut($row[0], 20, true).'</td>';
+            // time spent in the course
+            $return .= '    <td><div>'.api_time_to_hms(Tracking :: get_time_spent_on_the_course($user_id, $row[0])).'</div></td>';
+            // student progress in course
+            $return .= '    <td><div>'.round(Tracking :: get_avg_student_progress($user_id, $row[0]), 2).'</div></td>';
+            // student score
+            $avg_score = Tracking :: get_avg_student_score($user_id, $row[0]);
+            if (is_numeric($avg_score)) {
+                $avg_score = round($avg_score,2);
+            } else {
+                $$avg_score = '-';
+            }
+
+            $return .= '    <td><div>'.$avg_score.'</div></td>';
+            // student tes score
+            //$return .= '  <td><div style="width:40px">'.round(Tracking :: get_avg_student_exercise_score ($user_id, $row[0]),2).'%</div></td>';
+            // student messages
+            $return .= '    <td><div>'.Tracking :: count_student_messages($user_id, $row[0]).'</div></td>';
+            // student assignments
+            $return .= '    <td><div>'.Tracking :: count_student_assignments($user_id, $row[0]).'</div></td>';
+            // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
+            $exercises_results = MySpace::exercises_results($user_id, $row[0]);
+            $return .= '    <td width="105px"><div>'.(is_null($exercises_results['percentage']) ? '' : $exercises_results['score_obtained'].'/'.$exercises_results['score_possible'].' ( '.$exercises_results['percentage'].'% )').'</div></td>';
+            //$return .= '  <td><div>'.$exercises_results['score_possible'].'</div></td>';
+            $return .= '    <td><div>'.$exercises_results['questions_answered'].'</div></td>';
+            //$return .= '  <td><div>'.$exercises_results['percentage'].'% </div></td>';
+            // first connection
+            //$return .= '  <td width="60px">'.Tracking :: get_first_connection_date_on_the_course ($user_id, $row[0]).'</td>';
+            // last connection
+            $return .= '    <td><div>'.Tracking :: get_last_connection_date_on_the_course ($user_id, $row[0]).'</div></td>';
+            $return .= '<tr>';
+        }
+        $return .= '</table>';
+        return $return;
+    }
+
+    /**
+     * Display a sortable table that contains an overview off all the reporting progress of all users and all courses the user is subscribed to
+     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+     * @version Dokeos 1.8.6
+     * @since October 2008
+     */
+    function display_tracking_user_overview() {
+        MySpace::display_user_overview_export_options();
+
+        $t_head .= '    <table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
+        //$t_head .= '  <caption>'.get_lang('CourseInformation').'</caption>';
+        $t_head .=      '<tr>';
+        $t_head .= '        <th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
+        //$t_head .= '      <th><div style="width:40px">'.get_lang('AvgExercisesScore').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
+        $t_head .= '        <th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
+        //$t_head .= '      <th><div>'.get_lang('TotalExercisesScorePossible').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
+        //$t_head .= '      <th><div>'.get_lang('TotalExercisesScorePercentage').'</div></th>';
+        //$t_head .= '      <th><div style="width:60px">'.get_lang('FirstLogin').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
+        $t_head .= '    </tr></table>';
+
+        $addparams = array('view' => 'admin', 'display' => 'useroverview');
+
+        $table = new SortableTable('tracking_user_overview', array('MySpace','get_number_of_users_tracking_overview'), array('MySpace','get_user_data_tracking_overview'), 0);
+        $table->additional_parameters = $addparams;
+
+        $table->set_header(0, get_lang('OfficialCode'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+        if (api_is_western_name_order()) {
+            $table->set_header(1, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+            $table->set_header(2, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+        } else {
+            $table->set_header(1, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+            $table->set_header(2, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+        }
+        $table->set_header(3, get_lang('LoginName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+        $table->set_header(4, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
+        $table->set_column_filter(4, array('MySpace','course_info_tracking_filter'));
+        $table->display();
+    }
     /**
      * Display a sortable table that contains an overview off all the progress of the user in a session
      * @author César Perales <cesar.perales@beeznest.com>, Beeznest Team
@@ -842,1556 +842,1556 @@ class MySpace
      */
 
 
-	/**
-	 * Displays a form with all the additionally defined user fields of the profile
-	 * and give you the opportunity to include these in the CSV export
-	 *
-	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
-	 * @version Dokeos 1.8.6
-	 * @since November 2008
-	 */
-	function display_user_overview_export_options() {
-		// include the user manager and formvalidator library
-
-
-		if ($_GET['export'] == 'options') {
-			// get all the defined extra fields
-			$extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC', false, 1);
-
-			// creating the form with all the defined extra fields
-			$form = new FormValidator('exportextrafields', 'post', api_get_self()."?view=".Security::remove_XSS($_GET['view']).'&display='.Security::remove_XSS($_GET['display']).'&export='.Security::remove_XSS($_GET['export']));
-
-			if (is_array($extrafields) && count($extrafields) > 0) {
-				foreach ($extrafields as $key => $extra) {
-					$form->addElement('checkbox', 'extra_export_field'.$extra[0], '', $extra[3]);
-				}
-				$form->addElement('style_submit_button','submit', get_lang('Ok'),'class="save"' );
-
-				// setting the default values for the form that contains all the extra fields
-				if (is_array($_SESSION['additional_export_fields'])) {
-					foreach ($_SESSION['additional_export_fields'] as $key => $value) {
-						$defaults['extra_export_field'.$value] = 1;
-					}
-				}
-				$form->setDefaults($defaults);
-			} else {
-				$form->addElement('html', Display::display_warning_message(get_lang('ThereAreNotExtrafieldsAvailable')));
-			}
-
-			if ($form->validate()) {
-				// exporting the form values
-				$values = $form->exportValues();
-
-				// re-initialising the session that contains the additional fields that need to be exported
-				$_SESSION['additional_export_fields'] = array();
-
-				// adding the fields that are checked to the session
-				$message = '';
-				foreach ($values as $field_ids => $value) {
-					if ($value == 1 && strstr($field_ids,'extra_export_field')) {
-						$_SESSION['additional_export_fields'][] = str_replace('extra_export_field', '', $field_ids);
-					}
-				}
-
-				// adding the fields that will be also exported to a message string
-				if (is_array($_SESSION['additional_export_fields'])) {
-					foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
-						$message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
-					}
-				}
-
-				// Displaying a feedback message
-				if (!empty($_SESSION['additional_export_fields'])) {
-					Display::display_confirmation_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
-				} else  {
-					Display::display_confirmation_message(get_lang('NoAdditionalFieldsWillBeExported'), false);
-				}
-				$message = '';
-			} else {
-				$form->display();
-			}
-
-		} else {
-			if (!empty($_SESSION['additional_export_fields'])) {
-				// get all the defined extra fields
-				$extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
-
-				foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
-					$message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
-				}
-
-				Display::display_normal_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
-				$message = '';
-			}
-		}
-	}
-
-	/**
-	 * Display a sortable table that contains an overview of all the reporting progress of all courses
-	 */
-	function display_tracking_course_overview() {
-		//MySpace::display_user_overview_export_options();
-
-		$t_head .= '	<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
-		//$t_head .= '	<caption>'.get_lang('CourseInformation').'</caption>';
-		$t_head .=		'<tr>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
-		//$t_head .= '		<th><div style="width:40px">'.get_lang('AvgExercisesScore').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
-		$t_head .= '		<th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
-		//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePossible').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
-		//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePercentage').'</div></th>';
-		//$t_head .= '		<th><div style="width:60px">'.get_lang('FirstLogin').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
-		$t_head .= '	</tr></table>';
-
-		$addparams = array('view' => 'admin', 'display' => 'courseoverview');
-
-		$table = new SortableTable('tracking_session_overview', array('MySpace','get_total_number_courses'), array('MySpace','get_course_data_tracking_overview'), 1);
-		$table->additional_parameters = $addparams;
-
-		$table->set_header(0, '', false, null, array('style' => 'display: none'));
-		$table->set_header(1, get_lang('Course'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-		$table->set_header(2, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
-		$table->set_column_filter(2, array('MySpace','course_tracking_filter'));
-		$table->display();
-	}
-
-	/**
-	 * Get the total number of courses
-	 *
-	 * @return integer Total number of courses
-	 */
-	public function get_total_number_courses() {
-		// database table definition
-		$main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-		return Database::count_rows($main_course_table);
-	}
-
-	/**
-	 * Get data for the courses
-	 *
-	 * @param int Inferior limit
-	 * @param int Number of items to select
-	 * @param string Column to order on
-	 * @param string Order direction
-	 * @return array Results
-	 */
-	public function get_course_data_tracking_overview($from, $number_of_items, $column, $direction) {
-		$main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
+    /**
+     * Displays a form with all the additionally defined user fields of the profile
+     * and give you the opportunity to include these in the CSV export
+     *
+     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+     * @version Dokeos 1.8.6
+     * @since November 2008
+     */
+    function display_user_overview_export_options() {
+        // include the user manager and formvalidator library
+
+
+        if ($_GET['export'] == 'options') {
+            // get all the defined extra fields
+            $extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC', false, 1);
+
+            // creating the form with all the defined extra fields
+            $form = new FormValidator('exportextrafields', 'post', api_get_self()."?view=".Security::remove_XSS($_GET['view']).'&display='.Security::remove_XSS($_GET['display']).'&export='.Security::remove_XSS($_GET['export']));
+
+            if (is_array($extrafields) && count($extrafields) > 0) {
+                foreach ($extrafields as $key => $extra) {
+                    $form->addElement('checkbox', 'extra_export_field'.$extra[0], '', $extra[3]);
+                }
+                $form->addElement('style_submit_button','submit', get_lang('Ok'),'class="save"' );
+
+                // setting the default values for the form that contains all the extra fields
+                if (is_array($_SESSION['additional_export_fields'])) {
+                    foreach ($_SESSION['additional_export_fields'] as $key => $value) {
+                        $defaults['extra_export_field'.$value] = 1;
+                    }
+                }
+                $form->setDefaults($defaults);
+            } else {
+                $form->addElement('html', Display::display_warning_message(get_lang('ThereAreNotExtrafieldsAvailable')));
+            }
+
+            if ($form->validate()) {
+                // exporting the form values
+                $values = $form->exportValues();
+
+                // re-initialising the session that contains the additional fields that need to be exported
+                $_SESSION['additional_export_fields'] = array();
+
+                // adding the fields that are checked to the session
+                $message = '';
+                foreach ($values as $field_ids => $value) {
+                    if ($value == 1 && strstr($field_ids,'extra_export_field')) {
+                        $_SESSION['additional_export_fields'][] = str_replace('extra_export_field', '', $field_ids);
+                    }
+                }
+
+                // adding the fields that will be also exported to a message string
+                if (is_array($_SESSION['additional_export_fields'])) {
+                    foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
+                        $message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
+                    }
+                }
+
+                // Displaying a feedback message
+                if (!empty($_SESSION['additional_export_fields'])) {
+                    Display::display_confirmation_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
+                } else  {
+                    Display::display_confirmation_message(get_lang('NoAdditionalFieldsWillBeExported'), false);
+                }
+                $message = '';
+            } else {
+                $form->display();
+            }
+
+        } else {
+            if (!empty($_SESSION['additional_export_fields'])) {
+                // get all the defined extra fields
+                $extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+
+                foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
+                    $message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
+                }
+
+                Display::display_normal_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
+                $message = '';
+            }
+        }
+    }
+
+    /**
+     * Display a sortable table that contains an overview of all the reporting progress of all courses
+     */
+    function display_tracking_course_overview() {
+        //MySpace::display_user_overview_export_options();
+
+        $t_head .= '    <table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
+        //$t_head .= '  <caption>'.get_lang('CourseInformation').'</caption>';
+        $t_head .=      '<tr>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
+        //$t_head .= '      <th><div style="width:40px">'.get_lang('AvgExercisesScore').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
+        $t_head .= '        <th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
+        //$t_head .= '      <th><div>'.get_lang('TotalExercisesScorePossible').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
+        //$t_head .= '      <th><div>'.get_lang('TotalExercisesScorePercentage').'</div></th>';
+        //$t_head .= '      <th><div style="width:60px">'.get_lang('FirstLogin').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
+        $t_head .= '    </tr></table>';
+
+        $addparams = array('view' => 'admin', 'display' => 'courseoverview');
+
+        $table = new SortableTable('tracking_session_overview', array('MySpace','get_total_number_courses'), array('MySpace','get_course_data_tracking_overview'), 1);
+        $table->additional_parameters = $addparams;
+
+        $table->set_header(0, '', false, null, array('style' => 'display: none'));
+        $table->set_header(1, get_lang('Course'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+        $table->set_header(2, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
+        $table->set_column_filter(2, array('MySpace','course_tracking_filter'));
+        $table->display();
+    }
+
+    /**
+     * Get the total number of courses
+     *
+     * @return integer Total number of courses
+     */
+    public function get_total_number_courses() {
+        // database table definition
+        $main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
+        return Database::count_rows($main_course_table);
+    }
+
+    /**
+     * Get data for the courses
+     *
+     * @param int Inferior limit
+     * @param int Number of items to select
+     * @param string Column to order on
+     * @param string Order direction
+     * @return array Results
+     */
+    public function get_course_data_tracking_overview($from, $number_of_items, $column, $direction) {
+        $main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
         $from = intval($from);
         $number_of_items = intval($number_of_items);
 
-		$sql = "SELECT code AS col0, title AS col1 FROM $main_course_table";
-		$sql .= " ORDER BY col$column $direction ";
-		$sql .= " LIMIT $from,$number_of_items";
-		$result = Database::query($sql);
-		$return = array ();
-		while ($course = Database::fetch_row($result)) {
-			$return[] = $course;
-		}
-		return $return;
-	}
-
-	/**
-	 * Fills in course reporting data
-	 *
-	 * @param integer course code
-	 * @param array $url_params additonal url parameters
-	 * @param array $row the row information (the other columns)
-	 * @return string html code
-	 */
-	function course_tracking_filter($course_code, $url_params, $row) {
-		$course_code = $row[0];
-		// the table header
-		$return .= '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
-
-		// database table definition
-		$tbl_course_rel_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-		$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-		$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
-
-		// getting all the courses of the user
-		$sql = "SELECT * FROM $tbl_user AS u INNER JOIN $tbl_course_rel_user AS cu ON cu.user_id = u.user_id WHERE cu.course_code = '".$course_code."' AND ISNULL(cu.role);";
-		$result = Database::query($sql);
-		$time_spent = 0;
-		$progress = 0;
-		$nb_progress_lp = 0;
-		$score = 0;
-		$nb_score_lp = 0;
-		$nb_messages = 0;
-		$nb_assignments = 0;
-		$last_login_date = false;
-		$total_score_obtained = 0;
-		$total_score_possible = 0;
-		$total_questions_answered = 0;
-		while ($row = Database::fetch_object($result)) {
-			// get time spent in the course and session
-			$time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $course_code);
-			$progress_tmp = Tracking::get_avg_student_progress($row->user_id, $course_code, array(), null, true);
-			$progress += $progress_tmp[0];
-			$nb_progress_lp += $progress_tmp[1];
-			$score_tmp = Tracking :: get_avg_student_score($row->user_id, $course_code, array(), null, true);
-			if(is_array($score_tmp)) {
-				$score += $score_tmp[0];
-				$nb_score_lp += $score_tmp[1];
-			}
-			$nb_messages += Tracking::count_student_messages($row->user_id, $course_code);
-			$nb_assignments += Tracking::count_student_assignments($row->user_id, $course_code);
-
-			$last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row->user_id, $course_code, null, false);
-			if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned
-				$last_login_date = $last_login_date_tmp;
-			} else if($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition. To be cleaned.
-				// Find the max and assign it to first_login_date
-				if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
-					$last_login_date = $last_login_date_tmp;
-				}
-			}
-
-			$exercise_results_tmp = MySpace::exercises_results($row->user_id, $course_code);
-			$total_score_obtained += $exercise_results_tmp['score_obtained'];
-			$total_score_possible += $exercise_results_tmp['score_possible'];
-			$total_questions_answered += $exercise_results_tmp['questions_answered'];
-		}
-		if($nb_progress_lp > 0) {
-			$avg_progress = round($progress / $nb_progress_lp, 2);
-		} else {
-			$avg_progress = 0;
-		}
-		if($nb_score_lp > 0) {
-			$avg_score = round($score / $nb_score_lp, 2);
-		} else {
-			$avg_score = '-';
-		}
-		if($last_login_date) {
-			$last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
-		} else {
-			$last_login_date = '-';
-		}
-		if($total_score_possible > 0) {
-			$total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
-		} else {
-			$total_score_percentage = 0;
-		}
-		if($total_score_percentage > 0) {
-			$total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
-		} else {
-			$total_score = '-';
-		}
-		$return .= '<tr>';
-		// time spent in the course
-		$return .= '	<td style="width:164px;">'.api_time_to_hms($time_spent).'</td>';
-		// student progress in course
-		$return .= '	<td>'.$avg_progress.'</td>';
-		// student score
-		$return .= '	<td>'.$avg_score.'</td>';
-		// student messages
-		$return .= '	<td>'.$nb_messages.'</td>';
-		// student assignments
-		$return .= '	<td>'.$nb_assignments.'</td>';
-		// student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
-		$return .= '<td width="105px;">'.$total_score.'</td>';
-		$return .= '<td>'.$total_questions_answered.'</td>';
-		// last connection
-		$return .= '	<td>'.$last_login_date.'</td>';
-		$return .= '</tr>';
-		$return .= '</table>';
-		return $return;
-	}
-
-	/**
-	 * This function exports the table that we see in display_tracking_course_overview()
-	 *
-	 */
-	function export_tracking_course_overview() {
-		// database table definition
-		$tbl_course_rel_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-		$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-		$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
-
-		// the values of the sortable table
-		if ($_GET['tracking_course_overview_page_nr']) {
-			$from = $_GET['tracking_course_overview_page_nr'];
-		} else {
-			$from = 0;
-		}
-		if ($_GET['tracking_course_overview_column']) {
-			$orderby = $_GET['tracking_course_overview_column'];
-		} else {
-			$orderby = 0;
-		}
-
-		if ($_GET['tracking_course_overview_direction']) {
-			$direction = $_GET['tracking_course_overview_direction'];
-		} else {
-			$direction = 'ASC';
-		}
-
-		$course_data = MySpace::get_course_data_tracking_overview($from, 1000, $orderby, $direction);
-
-		$csv_content = array();
-
-		// the first line of the csv file with the column headers
-		$csv_row = array();
-		$csv_row[] = get_lang('Course', '');
-		$csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
-		$csv_row[] = get_lang('AvgStudentsProgress', '');
-		$csv_row[] = get_lang('AvgCourseScore', '');
-		$csv_row[] = get_lang('TotalNumberOfMessages', '');
-		$csv_row[] = get_lang('TotalNumberOfAssignments', '');
-		$csv_row[] = get_lang('TotalExercisesScoreObtained', '');
-		$csv_row[] = get_lang('TotalExercisesScorePossible', '');
-		$csv_row[] = get_lang('TotalExercisesAnswered', '');
-		$csv_row[] = get_lang('TotalExercisesScorePercentage', '');
-		$csv_row[] = get_lang('LatestLogin', '');
-		$csv_content[] = $csv_row;
-
-		// the other lines (the data)
-		foreach ($course_data as $key => $course) {
-			$course_code = $course[0];
-			$course_title = $course[1];
-
-			$csv_row = array();
-			$csv_row[] = $course_title;
-
-			// getting all the courses of the session
-			$sql = "SELECT * FROM $tbl_user AS u INNER JOIN $tbl_course_rel_user AS cu ON cu.user_id = u.user_id WHERE cu.course_code = '".$course_code."' AND ISNULL(cu.role);";
-			$result = Database::query($sql);
-			$time_spent = 0;
-			$progress = 0;
-			$nb_progress_lp = 0;
-			$score = 0;
-			$nb_score_lp = 0;
-			$nb_messages = 0;
-			$nb_assignments = 0;
-			$last_login_date = false;
-			$total_score_obtained = 0;
-			$total_score_possible = 0;
-			$total_questions_answered = 0;
-			while ($row = Database::fetch_object($result)) {
-				// get time spent in the course and session
-				$time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $course_code);
-				$progress_tmp = Tracking::get_avg_student_progress($row->user_id, $course_code, array(), null, true);
-				$progress += $progress_tmp[0];
-				$nb_progress_lp += $progress_tmp[1];
-				$score_tmp = Tracking :: get_avg_student_score($row->user_id, $course_code, array(), null, true);
-				if(is_array($score_tmp)) {
-					$score += $score_tmp[0];
-					$nb_score_lp += $score_tmp[1];
-				}
-				$nb_messages += Tracking::count_student_messages($row->user_id, $course_code);
-				$nb_assignments += Tracking::count_student_assignments($row->user_id, $course_code);
-
-				$last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row->user_id, $course_code, null, false);
-				if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned.
-					$last_login_date = $last_login_date_tmp;
-				} else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned.
-					// Find the max and assign it to first_login_date
-					if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
-						$last_login_date = $last_login_date_tmp;
-					}
-				}
-
-				$exercise_results_tmp = MySpace::exercises_results($row->user_id, $course_code);
-				$total_score_obtained += $exercise_results_tmp['score_obtained'];
-				$total_score_possible += $exercise_results_tmp['score_possible'];
-				$total_questions_answered += $exercise_results_tmp['questions_answered'];
-			}
-			if($nb_progress_lp > 0) {
-				$avg_progress = round($progress / $nb_progress_lp, 2);
-			} else {
-				$avg_progress = 0;
-			}
-			if($nb_score_lp > 0) {
-				$avg_score = round($score / $nb_score_lp, 2);
-			} else {
-				$avg_score = '-';
-			}
-			if($last_login_date) {
-				$last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
-			} else {
-				$last_login_date = '-';
-			}
-			if($total_score_possible > 0) {
-				$total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
-			} else {
-				$total_score_percentage = 0;
-			}
-			// time spent in the course
-			$csv_row[] = api_time_to_hms($time_spent);
-			// student progress in course
-			$csv_row[] = $avg_progress;
-			// student score
-			$csv_row[] = $avg_score;
-			// student messages
-			$csv_row[] = $nb_messages;
-			// student assignments
-			$csv_row[] = $nb_assignments;
-			// student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
-			$csv_row[] = $total_score_obtained;
-			$csv_row[] = $total_score_possible;
-			$csv_row[] = $total_questions_answered;
-			$csv_row[] = $total_score_percentage;
-			// last connection
-			$csv_row[] = $last_login_date;
-			$csv_content[] = $csv_row;
-		}
-		Export :: export_table_csv($csv_content, 'reporting_course_overview');
-		exit;
-	}
-
-	/**
-	 * Display a sortable table that contains an overview of all the reporting progress of all sessions and all courses the user is subscribed to
-	 * @author Guillaume Viguier <guillaume@viguierjust.com>
-	 */
-	function display_tracking_session_overview() {
-		//MySpace::display_user_overview_export_options();
-
-		$t_head .= '	<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
-		//$t_head .= '	<caption>'.get_lang('CourseInformation').'</caption>';
-		$t_head .=		'<tr>';
-		$t_head .= '		<th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
-		//$t_head .= '		<th><div style="width:40px">'.get_lang('AvgExercisesScore').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
-		$t_head .= '		<th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
-		//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePossible').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
-		//$t_head .= '		<th><div>'.get_lang('TotalExercisesScorePercentage').'</div></th>';
-		//$t_head .= '		<th><div style="width:60px">'.get_lang('FirstLogin').'</div></th>';
-		$t_head .= '		<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
-		$t_head .= '	</tr></table>';
-
-		$addparams = array('view' => 'admin', 'display' => 'sessionoverview');
-
-		$table = new SortableTable('tracking_session_overview', array('MySpace','get_total_number_sessions'), array('MySpace','get_session_data_tracking_overview'), 1);
-		$table->additional_parameters = $addparams;
-
-		$table->set_header(0, '', false, null, array('style' => 'display: none'));
-		$table->set_header(1, get_lang('Session'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
-		$table->set_header(2, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
-		$table->set_column_filter(2, array('MySpace','session_tracking_filter'));
-		$table->display();
-	}
-
-	/**
-	 * Get the total number of sessions
-	 *
-	 * @return integer Total number of sessions
-	 */
-	public function get_total_number_sessions() {
-		// database table definition
-		$main_session_table = Database :: get_main_table(TABLE_MAIN_SESSION);
-		return Database::count_rows($main_session_table);
-	}
-
-	/**
-	 * Get data for the sessions
-	 *
-	 * @param int Inferior limit
-	 * @param int Number of items to select
-	 * @param string Column to order on
-	 * @param string Order direction
-	 * @return array Results
-	 */
-	public function get_session_data_tracking_overview($from, $number_of_items, $column, $direction) {
-		//global $_configuration;
-		// database table definition
-		//$access_url_id = api_get_current_access_url_id();
-	 	//$tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-		$main_session_table = Database :: get_main_table(TABLE_MAIN_SESSION);
-
-		/*if ($_configuration['multiple_access_urls']) {
-			$condition_multi_url = ", $tbl_url_rel_user as url_user WHERE user.user_id=url_user.user_id AND access_url_id='$access_url_id'";
-		}
-
-		global $export_csv;
-		if ($export_csv) {
-			$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-		} else {
-			$is_western_name_order = api_is_western_name_order();
-		}*/
-		$sql = "SELECT id AS col0, name AS col1 FROM $main_session_table";
-		$sql .= " ORDER BY col$column $direction ";
-		$sql .= " LIMIT $from,$number_of_items";
-		$result = Database::query($sql);
-		$return = array ();
-		while ($session = Database::fetch_row($result)) {
-			$return[] = $session;
-		}
-		return $return;
-	}
-
-	/**
-	 * Fills in session reporting data
-	 *
-	 * @param integer $user_id the id of the user
-	 * @param array $url_params additonal url parameters
-	 * @param array $row the row information (the other columns)
-	 * @return string html code
-	 */
-	function session_tracking_filter($session_id, $url_params, $row) {
-		$session_id = $row[0];
-		// the table header
-		$return .= '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
-		/*$return .= '	<tr>';
-		$return .= '		<th>'.get_lang('Course').'</th>';
-		$return .= '		<th>'.get_lang('AvgTimeSpentInTheCourse').'</th>';
-		$return .= '		<th>'.get_lang('AvgStudentsProgress').'</th>';
-		$return .= '		<th>'.get_lang('AvgCourseScore').'</th>';
-		$return .= '		<th>'.get_lang('AvgExercisesScore').'</th>';
-		$return .= '		<th>'.get_lang('AvgMessages').'</th>';
-		$return .= '		<th>'.get_lang('AvgAssignments').'</th>';
-		$return .= '		<th>'.get_lang('TotalExercisesScoreObtained').'</th>';
-		$return .= '		<th>'.get_lang('TotalExercisesScorePossible').'</th>';
-		$return .= '		<th>'.get_lang('TotalExercisesAnswered').'</th>';
-		$return .= '		<th>'.get_lang('TotalExercisesScorePercentage').'</th>';
-		$return .= '		<th>'.get_lang('FirstLogin').'</th>';
-		$return .= '		<th>'.get_lang('LatestLogin').'</th>';
-		$return .= '	</tr>';*/
-
-		// database table definition
-		$tbl_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_user = Database :: get_main_table(TABLE_MAIN_USER);
-
-		// getting all the courses of the user
-		$sql = "SELECT * FROM $tbl_course AS c INNER JOIN $tbl_session_rel_course AS sc ON sc.course_code = c.code WHERE sc.id_session = '".$session_id."';";
-		$result = Database::query($sql);
-		while ($row = Database::fetch_object($result)) {
-			$return .= '<tr>';
-			// course code
-			$return .= '	<td width="157px" >'.$row->title.'</td>';
-			// get the users in the course
-			$sql = "SELECT user_id FROM $tbl_user AS u INNER JOIN $tbl_session_rel_course_rel_user AS scu ON u.user_id = scu.id_user WHERE scu.id_session = '".$session_id."' AND scu.course_code = '".$row->code."';";
-			$result_users = Database::query($sql);
-			$time_spent = 0;
-			$progress = 0;
-			$nb_progress_lp = 0;
-			$score = 0;
-			$nb_score_lp = 0;
-			$nb_messages = 0;
-			$nb_assignments = 0;
-			$last_login_date = false;
-			$total_score_obtained = 0;
-			$total_score_possible = 0;
-			$total_questions_answered = 0;
-			while($row_user = Database::fetch_object($result_users)) {
-				// get time spent in the course and session
-				$time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $row->code, $session_id);
-				$progress_tmp = Tracking::get_avg_student_progress($row_user->user_id, $row->code, array(), $session_id, true);
-				$progress += $progress_tmp[0];
-				$nb_progress_lp += $progress_tmp[1];
-				$score_tmp = Tracking :: get_avg_student_score($row_user->user_id, $row->code, array(), $session_id, true);
-				if(is_array($score_tmp)) {
-					$score += $score_tmp[0];
-					$nb_score_lp += $score_tmp[1];
-				}
-				$nb_messages += Tracking::count_student_messages($row_user->user_id, $row->code, $session_id);
-				$nb_assignments += Tracking::count_student_assignments($row_user->user_id, $row->code, $session_id);
-
-				$last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $row->code, $session_id, false);
-				if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned.
-					$last_login_date = $last_login_date_tmp;
-				} else if($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition! To be cleaned.
-					// Find the max and assign it to first_login_date
-					if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
-						$last_login_date = $last_login_date_tmp;
-					}
-				}
-
-				$exercise_results_tmp = MySpace::exercises_results($row_user->user_id, $row->code, $session_id);
-				$total_score_obtained += $exercise_results_tmp['score_obtained'];
-				$total_score_possible += $exercise_results_tmp['score_possible'];
-				$total_questions_answered += $exercise_results_tmp['questions_answered'];
-			}
-			if($nb_progress_lp > 0) {
-				$avg_progress = round($progress / $nb_progress_lp, 2);
-			} else {
-				$avg_progress = 0;
-			}
-			if($nb_score_lp > 0) {
-				$avg_score = round($score / $nb_score_lp, 2);
-			} else {
-				$avg_score = '-';
-			}
-			if($last_login_date) {
-				$last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
-			} else {
-				$last_login_date = '-';
-			}
-			if($total_score_possible > 0) {
-				$total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
-			} else {
-				$total_score_percentage = 0;
-			}
-			if($total_score_percentage > 0) {
-				$total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
-			} else {
-				$total_score = '-';
-			}
-			// time spent in the course
-			$return .= '	<td><div>'.api_time_to_hms($time_spent).'</div></td>';
-			// student progress in course
-			$return .= '	<td><div>'.$avg_progress.'</div></td>';
-			// student score
-			$return .= '	<td><div>'.$avg_score.'</div></td>';
-			// student messages
-			$return .= '	<td><div>'.$nb_messages.'</div></td>';
-			// student assignments
-			$return .= '	<td><div>'.$nb_assignments.'</div></td>';
-			// student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
-			$return .= '<td width="105px;">'.$total_score.'</td>';
-			$return .= '<td>'.$total_questions_answered.'</td>';
-			// last connection
-			$return .= '	<td><div>'.$last_login_date.'</div></td>';
-			$return .= '<tr>';
-		}
-		$return .= '</table>';
-		return $return;
-	}
-
-	/**
-	 * This function exports the table that we see in display_tracking_session_overview()
-	 *
-	 */
-	function export_tracking_session_overview() {
-		// database table definition
-		$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_user = Database :: get_main_table(TABLE_MAIN_USER);
-
-		// the values of the sortable table
-		if ($_GET['tracking_session_overview_page_nr']) {
-			$from = $_GET['tracking_session_overview_page_nr'];
-		} else {
-			$from = 0;
-		}
-		if ($_GET['tracking_session_overview_column']) {
-			$orderby = $_GET['tracking_session_overview_column'];
-		} else {
-			$orderby = 0;
-		}
-
-		if ($_GET['tracking_session_overview_direction']) {
-			$direction = $_GET['tracking_session_overview_direction'];
-		} else {
-			$direction = 'ASC';
-		}
-
-		$session_data = MySpace::get_session_data_tracking_overview($from, 1000, $orderby, $direction);
-
-		$csv_content = array();
-
-		// the first line of the csv file with the column headers
-		$csv_row = array();
-		$csv_row[] = get_lang('Session');
-		$csv_row[] = get_lang('Course', '');
-		$csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
-		$csv_row[] = get_lang('AvgStudentsProgress', '');
-		$csv_row[] = get_lang('AvgCourseScore', '');
-		$csv_row[] = get_lang('TotalNumberOfMessages', '');
-		$csv_row[] = get_lang('TotalNumberOfAssignments', '');
-		$csv_row[] = get_lang('TotalExercisesScoreObtained', '');
-		$csv_row[] = get_lang('TotalExercisesScorePossible', '');
-		$csv_row[] = get_lang('TotalExercisesAnswered', '');
-		$csv_row[] = get_lang('TotalExercisesScorePercentage', '');
-		$csv_row[] = get_lang('LatestLogin', '');
-		$csv_content[] = $csv_row;
-
-		// the other lines (the data)
-		foreach ($session_data as $key => $session) {
-			$session_id = $session[0];
-			$session_title = $session[1];
-
-			// getting all the courses of the session
-			$sql = "SELECT * FROM $tbl_course AS c INNER JOIN $tbl_session_rel_course AS sc ON sc.course_code = c.code WHERE sc.id_session = '".$session_id."';";
-			$result = Database::query($sql);
-			while ($row = Database::fetch_object($result)) {
-				$csv_row = array();
-				$csv_row[] = $session_title;
-				$csv_row[] = $row->title;
-				// get the users in the course
-				$sql = "SELECT user_id FROM $tbl_user AS u INNER JOIN $tbl_session_rel_course_rel_user AS scu ON u.user_id = scu.id_user WHERE scu.id_session = '".$session_id."' AND scu.course_code = '".$row->code."';";
-				$result_users = Database::query($sql);
-				$time_spent = 0;
-				$progress = 0;
-				$nb_progress_lp = 0;
-				$score = 0;
-				$nb_score_lp = 0;
-				$nb_messages = 0;
-				$nb_assignments = 0;
-				$last_login_date = false;
-				$total_score_obtained = 0;
-				$total_score_possible = 0;
-				$total_questions_answered = 0;
-				while($row_user = Database::fetch_object($result_users)) {
-					// get time spent in the course and session
-					$time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $row->code, $session_id);
-					$progress_tmp = Tracking::get_avg_student_progress($row_user->user_id, $row->code, array(), $session_id, true);
-					$progress += $progress_tmp[0];
-					$nb_progress_lp += $progress_tmp[1];
-					$score_tmp = Tracking :: get_avg_student_score($row_user->user_id, $row->code, array(), $session_id, true);
-					if(is_array($score_tmp)) {
-						$score += $score_tmp[0];
-						$nb_score_lp += $score_tmp[1];
-					}
-					$nb_messages += Tracking::count_student_messages($row_user->user_id, $row->code, $session_id);
-					$nb_assignments += Tracking::count_student_assignments($row_user->user_id, $row->code, $session_id);
-
-					$last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $row->code, $session_id, false);
-					if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned.
-						$last_login_date = $last_login_date_tmp;
-					} else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned.
-						// Find the max and assign it to first_login_date
-						if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
-							$last_login_date = $last_login_date_tmp;
-						}
-					}
-
-					$exercise_results_tmp = MySpace::exercises_results($row_user->user_id, $row->code, $session_id);
-					$total_score_obtained += $exercise_results_tmp['score_obtained'];
-					$total_score_possible += $exercise_results_tmp['score_possible'];
-					$total_questions_answered += $exercise_results_tmp['questions_answered'];
-				}
-				if($nb_progress_lp > 0) {
-					$avg_progress = round($progress / $nb_progress_lp, 2);
-				} else {
-					$avg_progress = 0;
-				}
-				if($nb_score_lp > 0) {
-					$avg_score = round($score / $nb_score_lp, 2);
-				} else {
-					$avg_score = '-';
-				}
-				if($last_login_date) {
-					$last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
-				} else {
-					$last_login_date = '-';
-				}
-				if($total_score_possible > 0) {
-					$total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
-				} else {
-					$total_score_percentage = 0;
-				}
-				if($total_score_percentage > 0) {
-					$total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
-				} else {
-					$total_score = '-';
-				}
-				// time spent in the course
-				$csv_row[] = api_time_to_hms($time_spent);
-				// student progress in course
-				$csv_row[] = $avg_progress;
-				// student score
-				$csv_row[] = $avg_score;
-				// student messages
-				$csv_row[] = $nb_messages;
-				// student assignments
-				$csv_row[] = $nb_assignments;
-				// student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
-				$csv_row[] = $total_score_obtained;
-				$csv_row[] = $total_score_possible;
-				$csv_row[] = $total_questions_answered;
-				$csv_row[] = $total_score_percentage;
-				// last connection
-				$csv_row[] = $last_login_date;
-				$csv_content[] = $csv_row;
-			}
-		}
-		Export :: export_table_csv($csv_content, 'reporting_session_overview');
-		exit;
-	}
-
-
-	/**
-	 * Get general information about the exercise performance of the user
-	 * the total obtained score (all the score on all the questions)
-	 * the maximum score that could be obtained
-	 * the number of questions answered
-	 * the success percentage
-	 * @param integer $user_id the id of the user
-	 * @param string $course_code the course code
-	 * @return array
-	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
-	 * @version Dokeos 1.8.6
-	 * @since November 2008
-	 */
-	function exercises_results($user_id, $course_code, $session_id = false) {
-		$questions_answered = 0;
-		$sql = 'SELECT exe_result , exe_weighting
-			FROM '.Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES)."
-			WHERE exe_cours_id = '".Database::escape_string($course_code)."'
-			AND exe_user_id = '".Database::escape_string($user_id)."'";
-		if($session_id !== false) {
-			$sql .= " AND session_id = '".$session_id."' ";
-		}
-		$result = Database::query($sql);
-		$score_obtained = 0;
-		$score_possible = 0;
-		$questions_answered = 0;
-		while ($row = Database::fetch_array($result)) {
-			$score_obtained += $row['exe_result'];
-			$score_possible += $row['exe_weighting'];
-			$questions_answered ++;
-		}
-
-		if ($score_possible != 0) {
-			$percentage = round(($score_obtained / $score_possible * 100), 2);
-		} else {
-			$percentage = null;
-		}
-
-		return array('score_obtained' => $score_obtained, 'score_possible' => $score_possible, 'questions_answered' => $questions_answered, 'percentage' => $percentage);
-	}
-
-	/**
-	 * This function exports the table that we see in display_tracking_user_overview()
-	 *
-	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
-	 * @version Dokeos 1.8.6
-	 * @since October 2008
-	 */
-	function export_tracking_user_overview() {
-
-
-		// database table definitions
-		$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-
-		$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-		$sort_by_first_name = api_sort_by_first_name();
-
-		// the values of the sortable table
-		if ($_GET['tracking_user_overview_page_nr']) {
-			$from = $_GET['tracking_user_overview_page_nr'];
-		} else {
-			$from = 0;
-		}
-		if ($_GET['tracking_user_overview_column']) {
-			$orderby = $_GET['tracking_user_overview_column'];
-		} else {
-			$orderby = 0;
-		}
-		if ($is_western_name_order != api_is_western_name_order() && ($orderby == 1 || $orderby == 2)) {
-			// Swapping the sorting column if name order for export is different than the common name order.
-			$orderby = 3 - $orderby;
-		}
-		if ($_GET['tracking_user_overview_direction']) {
-			$direction = $_GET['tracking_user_overview_direction'];
-		} else {
-			$direction = 'ASC';
-		}
-
-		$user_data = MySpace::get_user_data_tracking_overview($from, 1000, $orderby, $direction);
-
-		// the first line of the csv file with the column headers
-		$csv_row = array();
-		$csv_row[] = get_lang('OfficialCode');
-		if ($is_western_name_order) {
-			$csv_row[] = get_lang('FirstName', '');
-			$csv_row[] = get_lang('LastName', '');
-		} else {
-			$csv_row[] = get_lang('LastName', '');
-			$csv_row[] = get_lang('FirstName', '');
-		}
-		$csv_row[] = get_lang('LoginName');
-		$csv_row[] = get_lang('CourseCode');
-		// the additional user defined fields (only those that were selected to be exported)
-
-		$fields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
-
-		if (is_array($_SESSION['additional_export_fields'])) {
-			foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
-				$csv_row[] = $fields[$extra_field_export][3];
-				$field_names_to_be_exported[] = 'extra_'.$fields[$extra_field_export][1];
-			}
-		}
-		$csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
-		$csv_row[] = get_lang('AvgStudentsProgress', '');
-		$csv_row[] = get_lang('AvgCourseScore', '');
-		$csv_row[] = get_lang('AvgExercisesScore', '');
-		$csv_row[] = get_lang('AvgMessages', '');
-		$csv_row[] = get_lang('AvgAssignments', '');
-		$csv_row[] = get_lang('TotalExercisesScoreObtained', '');
-		$csv_row[] = get_lang('TotalExercisesScorePossible', '');
-		$csv_row[] = get_lang('TotalExercisesAnswered', '');
-		$csv_row[] = get_lang('TotalExercisesScorePercentage', '');
-		$csv_row[] = get_lang('FirstLogin', '');
-		$csv_row[] = get_lang('LatestLogin', '');
-		$csv_content[] = $csv_row;
-
-		// the other lines (the data)
-		foreach ($user_data as $key => $user) {
-			// getting all the courses of the user
-			$sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".Database::escape_string($user[4])."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
-			$result = Database::query($sql);
-			while ($row = Database::fetch_row($result)) {
-				$csv_row = array();
-				// user official code
-				$csv_row[] = $user[0];
-				// user first|last name
-				$csv_row[] = $user[1];
-				// user last|first name
-				$csv_row[] = $user[2];
-				// user login name
-				$csv_row[] = $user[3];
-				// course code
-				$csv_row[] = $row[0];
-				// the additional defined user fields
-				$extra_fields = MySpace::get_user_overview_export_extra_fields($user[4]);
-
-				if (is_array($field_names_to_be_exported)) {
-					foreach ($field_names_to_be_exported as $key => $extra_field_export) {
-						$csv_row[] = $extra_fields[$extra_field_export];
-					}
-				}
-				// time spent in the course
-				$csv_row[] = api_time_to_hms(Tracking :: get_time_spent_on_the_course ($user[4], $row[0]));
-				// student progress in course
-				$csv_row[] = round(Tracking :: get_avg_student_progress ($user[4], $row[0]), 2);
-				// student score
-				$csv_row[] = round(Tracking :: get_avg_student_score ($user[4], $row[0]), 2);
-				// student tes score
-				$csv_row[] = round(Tracking :: get_avg_student_exercise_score ($user[4], $row[0]), 2);
-				// student messages
-				$csv_row[] = Tracking :: count_student_messages ($user[4], $row[0]);
-				// student assignments
-				$csv_row[] = Tracking :: count_student_assignments ($user[4], $row[0]);
-				// student exercises results
-				$exercises_results = MySpace::exercises_results($user[4], $row[0]);
-				$csv_row[] = $exercises_results['score_obtained'];
-				$csv_row[] = $exercises_results['score_possible'];
-				$csv_row[] = $exercises_results['questions_answered'];
-				$csv_row[] = $exercises_results['percentage'];
-				// first connection
-				$csv_row[] = Tracking :: get_first_connection_date_on_the_course ($user[4], $row[0]);
-				// last connection
-				$csv_row[] = strip_tags(Tracking :: get_last_connection_date_on_the_course ($user[4], $row[0]));
-
-				$csv_content[] = $csv_row;
-			}
-		}
-		Export :: export_table_csv($csv_content, 'reporting_user_overview');
-		exit;
-	}
-
-	/**
-	 * Get data for courses list in sortable with pagination
-	 * @return array
-	 */
-	static function get_course_data($from, $number_of_items, $column, $direction) {
-		global $courses, $csv_content, $charset, $session_id;
-
-		// definition database tables
-		$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
-		$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-		$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-		$course_data = array();
-		$courses_code = array_keys($courses);
-
-		foreach ($courses_code as &$code) {
-			$code = "'$code'";
-		}
-
-		// get all courses with limit
-		$sql = "SELECT course.code as col1, course.title as col2
-				FROM $tbl_course course
-				WHERE course.code IN (".implode(',',$courses_code).")";
-
-		if (!in_array($direction, array('ASC','DESC'))) $direction = 'ASC';
-
-	    $column = intval($column);
-	    $from = intval($from);
-	    $number_of_items = intval($number_of_items);
-		$sql .= " ORDER BY col$column $direction ";
-		$sql .= " LIMIT $from,$number_of_items";
-
-		$res = Database::query($sql);
-		while ($row_course = Database::fetch_row($res)) {
-
-			$course_code = $row_course[0];
-			$course_info = api_get_course_info($course_code);
-			$avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0;
-
-			// students directly subscribed to the course
-			if (empty($session_id)) {
-				$sql = "SELECT user_id FROM $tbl_course_user as course_rel_user WHERE course_rel_user.status='5' AND course_rel_user.course_code='$course_code'";
-			} else {
-				$sql = "SELECT id_user as user_id FROM $tbl_session_course_user srcu WHERE  srcu. course_code='$course_code' AND id_session = '$session_id' AND srcu.status<>2";
-			}
-			$rs = Database::query($sql);
-			$users = array();
-			while ($row = Database::fetch_array($rs)) { $users[] = $row['user_id']; }
-
-			if (count($users) > 0) {
-				$nb_students_in_course = count($users);
-				$avg_assignments_in_course  = Tracking::count_student_assignments($users, $course_code, $session_id);
-				$avg_messages_in_course     = Tracking::count_student_messages($users, $course_code, $session_id);
-				$avg_progress_in_course     = Tracking::get_avg_student_progress($users, $course_code, array(), $session_id);
-				$avg_score_in_course        = Tracking::get_avg_student_score($users, $course_code, array(), $session_id);
-				$avg_score_in_exercise      = Tracking::get_avg_student_exercise_score($users, $course_code, 0, $session_id);
-				$avg_time_spent_in_course   = Tracking::get_time_spent_on_the_course($users, $course_code, $session_id);
-
-				$avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
-				if (is_numeric($avg_score_in_course)) {
-					$avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2);
-				}
-				$avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
-
-			} else {
-				$avg_time_spent_in_course = null;
-				$avg_progress_in_course = null;
-				$avg_score_in_course = null;
-				$avg_score_in_exercise = null;
-				$avg_messages_in_course = null;
-				$avg_assignments_in_course = null;
-			}
-			$table_row = array();
-			$table_row[] = $row_course[1];
-			$table_row[] = $nb_students_in_course;
-			$table_row[] = $avg_time_spent_in_course;
-			$table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course.'%';
-			$table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course.'%';
-			$table_row[] = is_null($avg_score_in_exercise) ? '' : $avg_score_in_exercise.'%';
-			$table_row[] = $avg_messages_in_course;
-			$table_row[] = $avg_assignments_in_course;
-
-			//set the "from" value to know if I access the Reporting by the chamilo tab or the course link
-			$table_row[] = '<center><a href="../tracking/courseLog.php?cidReq='.$course_code.'&from=myspace&id_session='.$session_id.'">
-			                 <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>
-			                </center>';
-			$csv_content[] = array(
-				api_html_entity_decode($row_course[1], ENT_QUOTES, $charset),
-				$nb_students_in_course,
-				$avg_time_spent_in_course,
-				is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
-				is_null($avg_score_in_course) ? null : is_numeric($avg_score_in_course) ? $avg_score_in_course.'%' : $avg_score_in_course ,
-				is_null($avg_score_in_exercise) ? null : $avg_score_in_exercise.'%',
-				$avg_messages_in_course,
-				$avg_assignments_in_course,
-			);
-			$course_data[] = $table_row;
-		}
-		return $course_data;
-	}
-
-	/**
-	 * get the numer of users of the platform
-	 *
-	 * @return integer
-	 *
-	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
-	 * @version Dokeos 1.8.6
-	 * @since October 2008
-	 */
-	function get_number_of_users_tracking_overview() {
-		// database table definition
-		$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
-		return Database::count_rows($main_user_table);
-	}
-
-	/**
-	 * get all the data for the sortable table of the reporting progress of all users and all the courses the user is subscribed to.
-	 *
-	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
-	 * @version Dokeos 1.8.6
-	 * @since October 2008
-	 */
-	function get_user_data_tracking_overview($from, $number_of_items, $column, $direction) {
-		global $_configuration;
-		// database table definition
-		$access_url_id = api_get_current_access_url_id();
-	 	$tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-		$main_user_table = Database::get_main_table(TABLE_MAIN_USER);
-
-		if ($_configuration['multiple_access_urls']) {
-			$condition_multi_url = ", $tbl_url_rel_user as url_user WHERE user.user_id=url_user.user_id AND access_url_id='$access_url_id'";
-		}
-
-		global $export_csv;
-		if ($export_csv) {
-			$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-		} else {
-			$is_western_name_order = api_is_western_name_order();
-		}
-		$sql = "SELECT
-					official_code 	AS col0,
-					".($is_western_name_order ? "
-					firstname 		AS col1,
-					lastname 		AS col2,
-					" : "
-					lastname 		AS col1,
-					firstname 		AS col2,
-					").
-					"username		AS col3,
-					user.user_id 		AS col4
-				FROM
-					$main_user_table as user $condition_multi_url
-				";
-		$sql .= " ORDER BY col$column $direction ";
-		$sql .= " LIMIT $from,$number_of_items";
-		$result = Database::query($sql);
-		$return = array ();
-		while ($user = Database::fetch_row($result)) {
-			$return[] = $user;
-		}
-		return $return;
-	}
-
-	/**
-	 * Get all information that the user with user_id = $user_data has
-	 * entered in the additionally defined profile fields
-	 * @param integer $user_id the id of the user
-	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
-	 * @version Dokeos 1.8.6
-	 * @since November 2008
-	 */
-	function get_user_overview_export_extra_fields($user_id) {
-		// include the user manager
-
-		$extra_data = UserManager::get_extra_user_data($user_id, true);
-		return $extra_data;
-	}
-	/**
-	 * Checks if a username exist in the DB otherwise it create a "double"
-	 * i.e. if we look into for jmontoya but the user's name already exist we create the user jmontoya2
-	 * the return array will be array(username=>'jmontoya', sufix='2')
-	 * @param string firstname
-	 * @param string lastname
-	 * @param string username
-	 * @return array with the username, the sufix
-	 * @author Julio Montoya Armas
-	 */
-	function make_username($firstname, $lastname, $username, $language = null, $encoding = null) {
-		$table_user = Database::get_main_table(TABLE_MAIN_USER);
-		$tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-		// if username exist
-		if (!UserManager::is_username_available($username) || empty($username)) {
-			$i = 0;
-			while (1) {
-				if ($i == 0) {
-					$sufix = '';
-				} else {
-					$sufix = $i;
-				}
-				$desired_username = UserManager::create_username($firstname, $lastname, $language, $encoding);
-				if (UserManager::is_username_available($desired_username.$sufix)) {
-					break;
-				} else {
-					$i++;
-				}
-			}
-			$username_array = array('username' => $desired_username , 'sufix' => $sufix);
-			return $username_array;
-		} else {
-			$username_array = array('username' => $username, 'sufix' => '');
-			return $username_array;
-		}
-	}
-
-	/**
-	 * Checks if there are repeted users in a given array
-	 * @param  array $usernames list of the usernames in the uploaded file
-	 * @param  array $user_array['username'] and $user_array['sufix'] where sufix is the number part in a login i.e -> jmontoya2
-	 * @return array with the $usernames array and the $user_array array
-	 * @author Julio Montoya Armas
-	 */
-	function check_user_in_array($usernames, $user_array) {
-		$user_list = array_keys($usernames);
-		$username = $user_array['username'].$user_array['sufix'];
-
-		if (in_array($username, $user_list)) {
-			$user_array['sufix'] += $usernames[$username];
-			$usernames[$username]++;
-		} else {
-			$usernames[$username] = 1;
-		}
-		$result_array = array($usernames, $user_array);
-		return $result_array;
-	}
-
-	/**
-	 * Checks whether a username has been already subscribed in a session.
-	 * @param string a given username
-	 * @param array  the array with the course list codes
-	 * @param the session id
-	 * @return 0 if the user is not subscribed  otherwise it returns the user_id of the given username
-	 * @author Julio Montoya Armas
-	 */
-	function user_available_in_session($username, $course_list, $id_session) {
-		$table_user = Database::get_main_table(TABLE_MAIN_USER);
-		$tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-		$id_session = intval($id_session);
-		$username = Database::escape_string($username);
-		foreach($course_list as $enreg_course) {
-			$sql_select = "	SELECT u.user_id FROM $tbl_session_rel_course_rel_user rel INNER JOIN $table_user u
-						   	ON (rel.id_user=u.user_id)
-							WHERE rel.id_session='$id_session' AND u.status='5' AND u.username ='$username' AND rel.course_code='$enreg_course'";
-			$rs = Database::query($sql_select);
-			if (Database::num_rows($rs) > 0) {
-				return Database::result($rs, 0, 0);
-			} else {
-				return 0;
-			}
-		}
-	}
-
-	/**
-	This function checks whether some users in the uploaded file repeated and creates unique usernames if necesary.
-	A case: Within the file there is an user repeted twice (Julio Montoya / Julio Montoya) and the username fields are empty.
-	Then, this function would create unique usernames based on the first and the last name. Two users wiould be created - jmontoya and jmontoya2.
-	Of course, if in the database there is a user with the name jmontoya, the newly created two users registered would be jmontoya2 and jmontoya3.
-	@param $users list of users
-	@author Julio Montoya Armas
-	*/
-	function check_all_usernames($users, $course_list, $id_session) {
-		$table_user = Database::get_main_table(TABLE_MAIN_USER);
-		$usernames = array();
-		$new_users = array();
-		foreach ($users as $index => $user) {
-			$desired_username = array();
-			if (empty($user['UserName'])) {
-				$desired_username = MySpace::make_username($user['FirstName'], $user['LastName'], '');
-				$pre_username = $desired_username['username'].$desired_username['sufix'];
-				$user['UserName'] = $pre_username;
-				$user['create'] = '1';
-			} else {
-				if (UserManager::is_username_available($user['UserName'])) {
-					$desired_username = MySpace::make_username($user['FirstName'], $user['LastName'], $user['UserName']);
-					$user['UserName'] = $desired_username['username'].$desired_username['sufix'];
-					$user['create'] = '1';
-				} else {
-					$is_session_avail = MySpace::user_available_in_session($user['UserName'], $course_list, $id_session);
-					if ($is_session_avail == 0) {
-						$user_name = $user['UserName'];
-						$sql_select = "SELECT user_id FROM $table_user WHERE username ='$user_name' ";
-						$rs = Database::query($sql_select);
-						$user['create'] = Database::result($rs, 0, 0); // This should be the ID because the user exists.
-					} else {
-						$user['create'] = $is_session_avail;
-					}
-				}
-			}
-			// Usernames is the current list of users in the file.
-			$result_array = MySpace::check_user_in_array($usernames, $desired_username);
-			$usernames = $result_array[0];
-			$desired_username = $result_array[1];
-			$user['UserName'] = $desired_username['username'].$desired_username['sufix'];
-			$new_users[] = $user;
-		}
-		return $new_users;
-	}
-
-	/**
-	 * This functions checks whether there are users that are already registered in the DB by different creator than the current coach.
-	 * @param string a given username
-	 * @param array  the array with the course list codes
-	 * @param the session id
-	 * @author Julio Montoya Armas
-	 */
-	function get_user_creator($users, $course_list, $id_session) {
-		$errors = array();
-		foreach ($users as $index => $user) {
-			// database table definition
-			$table_user = Database::get_main_table(TABLE_MAIN_USER);
-			$tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-			$username = Database::escape_string($user['UserName']);
-			//echo "<br>";
-			$sql = "SELECT creator_id FROM $table_user WHERE username='$username' ";
-
-			$rs = Database::query($sql);
-			$creator_id = Database::result($rs, 0, 0);
-			// check if we are the creators or not
-			if ($creator_id != '') {
-				if ($creator_id != api_get_user_id()) {
-					$user['error'] = get_lang('UserAlreadyRegisteredByOtherCreator');
-					$errors[] = $user;
-				}
-			}
-		}
-		return $errors;
-	}
-
-	/**
-	 * Validates imported data.
-	 * @param list of users
-	 */
-	function validate_data($users, $id_session = null) {
-		$errors = array();
-		$usernames = array();
-		$new_users = array();
-		foreach ($users as $index => $user) {
-			// 1. Check whether mandatory fields are set.
-			$mandatory_fields = array('LastName', 'FirstName');
-			if (api_get_setting('registration', 'email') == 'true') {
-				$mandatory_fields[] = 'Email';
-			}
-
-			foreach ($mandatory_fields as $key => $field) {
-				if (!isset ($user[$field]) || strlen($user[$field]) == 0) {
-					$user['error'] = get_lang($field.'Mandatory');
-					$errors[] = $user;
-				}
-			}
-			// 2. Check whether the username is too long.
-			if (UserManager::is_username_too_long($user['UserName'])) {
-				$user['error'] = get_lang('UserNameTooLong');
-				$errors[] = $user;
-			}
-
-			$user['UserName'] = trim($user['UserName']);
-
-			if (empty($user['UserName'])) {
-				 $user['UserName'] = UserManager::create_username($user['FirstName'], $user['LastName']);
-			}
-			$new_users[] = $user;
-		}
-		$results = array('errors' => $errors, 'users' => $new_users);
-		return $results;
-	}
-
-	/**
-	 * Adds missing user-information (which isn't required, like password, etc).
-	 */
-	function complete_missing_data($user) {
-		// 1. Generate a password if it is necessary.
-		if (!isset ($user['Password']) || strlen($user['Password']) == 0) {
-			$user['Password'] = api_generate_password();
-		}
-		return $user;
-	}
-
-	/**
-	 * Saves imported data.
-	 */
-	function save_data($users, $course_list, $id_session) {
-		$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
-		$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-		$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-		$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-
-		$id_session = intval($id_session);
-		$sendMail = $_POST['sendMail'] ? 1 : 0;
-
-		// Adding users to the platform.
-		$new_users = array();
-		foreach ($users as $index => $user) {
-			$user = MySpace::complete_missing_data($user);
-			// coach only will registered users
-			$default_status = '5';
-			if ($user['create'] == '1') {
-				$user['id'] = UserManager :: create_user($user['FirstName'], $user['LastName'], $default_status, $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], api_get_setting('PlatformLanguage'), $user['PhoneNumber'], '');
-				$user['added_at_platform'] = 1;
-			} else {
-				$user['id'] = $user['create'];
-				$user['added_at_platform'] = 0;
-			}
-			$new_users[] = $user;
-		}
-		// Update user list.
-		$users = $new_users;
-
-		// Inserting users.
-		$super_list = array();
-		foreach ($course_list as $enreg_course) {
-			$nbr_users = 0;
-			$new_users = array();
-			$enreg_course = Database::escape_string($enreg_course);
-			foreach ($users as $index => $user) {
-				$userid = intval($user['id']);
-				$sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$userid')";
-				$course_session = array('course' => $enreg_course, 'added' => 1);
-				//$user['added_at_session'] = $course_session;
-				Database::query($sql);
-				if (Database::affected_rows()) {
-					$nbr_users++;
-				}
-				$new_users[] = $user;
-			}
-			$super_list[] = $new_users;
-
-			//update the nbr_users field
-			$sql_select = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course'";
-			$rs = Database::query($sql_select);
-			list($nbr_users) = Database::fetch_array($rs);
-			$sql_update = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'";
-			Database::query($sql_update);
-
-			$sql_update = "UPDATE $tbl_session SET nbr_users= '$nbr_users' WHERE id='$id_session'";
-			Database::query($sql_update);
-		}
-		// We don't delete the users (thoughts while dreaming)
-		//$sql_delete = "DELETE FROM $tbl_session_rel_user WHERE id_session = '$id_session'";
-		//Database::query($sql_delete);
-
-		$new_users = array();
-		foreach ($users as $index => $user) {
-			$userid = $user['id'];
-			$sql_insert = "INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user) VALUES('$id_session','$userid')";
-			Database::query($sql_insert);
-			$user['added_at_session'] = 1;
-			$new_users[] = $user;
-		}
-
-		$users = $new_users;
-		$registered_users = get_lang('FileImported').'<br /> Import file results : <br />';
-		// Sending emails.
-		$addedto = '';
-		if ($sendMail) {
-			$i = 0; 
-			foreach ($users as $index => $user) {
-				$emailto = api_get_person_name($user['FirstName'], $user['LastName'], null, PERSON_NAME_EMAIL_ADDRESS).' <'.$user['Email'].'>';
-				$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
-				$emailbody = get_lang('Dear').' '.api_get_person_name($user['FirstName'], $user['LastName']).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : $user[UserName]\n".get_lang('Pass')." : $user[Password]\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path(WEB_PATH)." \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')."";
-				$emailheaders = 'From: '.api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS).' <'.api_get_setting('emailAdministrator').">\n";
-				$emailheaders .= 'Reply-To: '.api_get_setting('emailAdministrator');
-
-				/*$extra = get_user_overview_export_extra_fields($user['user_id']);
-				$additional_parameters = array(
+        $sql = "SELECT code AS col0, title AS col1 FROM $main_course_table";
+        $sql .= " ORDER BY col$column $direction ";
+        $sql .= " LIMIT $from,$number_of_items";
+        $result = Database::query($sql);
+        $return = array ();
+        while ($course = Database::fetch_row($result)) {
+            $return[] = $course;
+        }
+        return $return;
+    }
+
+    /**
+     * Fills in course reporting data
+     *
+     * @param integer course code
+     * @param array $url_params additonal url parameters
+     * @param array $row the row information (the other columns)
+     * @return string html code
+     */
+    function course_tracking_filter($course_code, $url_params, $row) {
+        $course_code = $row[0];
+        // the table header
+        $return .= '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
+
+        // database table definition
+        $tbl_course_rel_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+        $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
+
+        // getting all the courses of the user
+        $sql = "SELECT * FROM $tbl_user AS u INNER JOIN $tbl_course_rel_user AS cu ON cu.user_id = u.user_id WHERE cu.course_code = '".$course_code."' AND ISNULL(cu.role);";
+        $result = Database::query($sql);
+        $time_spent = 0;
+        $progress = 0;
+        $nb_progress_lp = 0;
+        $score = 0;
+        $nb_score_lp = 0;
+        $nb_messages = 0;
+        $nb_assignments = 0;
+        $last_login_date = false;
+        $total_score_obtained = 0;
+        $total_score_possible = 0;
+        $total_questions_answered = 0;
+        while ($row = Database::fetch_object($result)) {
+            // get time spent in the course and session
+            $time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $course_code);
+            $progress_tmp = Tracking::get_avg_student_progress($row->user_id, $course_code, array(), null, true);
+            $progress += $progress_tmp[0];
+            $nb_progress_lp += $progress_tmp[1];
+            $score_tmp = Tracking :: get_avg_student_score($row->user_id, $course_code, array(), null, true);
+            if(is_array($score_tmp)) {
+                $score += $score_tmp[0];
+                $nb_score_lp += $score_tmp[1];
+            }
+            $nb_messages += Tracking::count_student_messages($row->user_id, $course_code);
+            $nb_assignments += Tracking::count_student_assignments($row->user_id, $course_code);
+
+            $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row->user_id, $course_code, null, false);
+            if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned
+                $last_login_date = $last_login_date_tmp;
+            } else if($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition. To be cleaned.
+                // Find the max and assign it to first_login_date
+                if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
+                    $last_login_date = $last_login_date_tmp;
+                }
+            }
+
+            $exercise_results_tmp = MySpace::exercises_results($row->user_id, $course_code);
+            $total_score_obtained += $exercise_results_tmp['score_obtained'];
+            $total_score_possible += $exercise_results_tmp['score_possible'];
+            $total_questions_answered += $exercise_results_tmp['questions_answered'];
+        }
+        if($nb_progress_lp > 0) {
+            $avg_progress = round($progress / $nb_progress_lp, 2);
+        } else {
+            $avg_progress = 0;
+        }
+        if($nb_score_lp > 0) {
+            $avg_score = round($score / $nb_score_lp, 2);
+        } else {
+            $avg_score = '-';
+        }
+        if($last_login_date) {
+            $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
+        } else {
+            $last_login_date = '-';
+        }
+        if($total_score_possible > 0) {
+            $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
+        } else {
+            $total_score_percentage = 0;
+        }
+        if($total_score_percentage > 0) {
+            $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
+        } else {
+            $total_score = '-';
+        }
+        $return .= '<tr>';
+        // time spent in the course
+        $return .= '    <td style="width:164px;">'.api_time_to_hms($time_spent).'</td>';
+        // student progress in course
+        $return .= '    <td>'.$avg_progress.'</td>';
+        // student score
+        $return .= '    <td>'.$avg_score.'</td>';
+        // student messages
+        $return .= '    <td>'.$nb_messages.'</td>';
+        // student assignments
+        $return .= '    <td>'.$nb_assignments.'</td>';
+        // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
+        $return .= '<td width="105px;">'.$total_score.'</td>';
+        $return .= '<td>'.$total_questions_answered.'</td>';
+        // last connection
+        $return .= '    <td>'.$last_login_date.'</td>';
+        $return .= '</tr>';
+        $return .= '</table>';
+        return $return;
+    }
+
+    /**
+     * This function exports the table that we see in display_tracking_course_overview()
+     *
+     */
+    function export_tracking_course_overview() {
+        // database table definition
+        $tbl_course_rel_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+        $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
+
+        // the values of the sortable table
+        if ($_GET['tracking_course_overview_page_nr']) {
+            $from = $_GET['tracking_course_overview_page_nr'];
+        } else {
+            $from = 0;
+        }
+        if ($_GET['tracking_course_overview_column']) {
+            $orderby = $_GET['tracking_course_overview_column'];
+        } else {
+            $orderby = 0;
+        }
+
+        if ($_GET['tracking_course_overview_direction']) {
+            $direction = $_GET['tracking_course_overview_direction'];
+        } else {
+            $direction = 'ASC';
+        }
+
+        $course_data = MySpace::get_course_data_tracking_overview($from, 1000, $orderby, $direction);
+
+        $csv_content = array();
+
+        // the first line of the csv file with the column headers
+        $csv_row = array();
+        $csv_row[] = get_lang('Course', '');
+        $csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
+        $csv_row[] = get_lang('AvgStudentsProgress', '');
+        $csv_row[] = get_lang('AvgCourseScore', '');
+        $csv_row[] = get_lang('TotalNumberOfMessages', '');
+        $csv_row[] = get_lang('TotalNumberOfAssignments', '');
+        $csv_row[] = get_lang('TotalExercisesScoreObtained', '');
+        $csv_row[] = get_lang('TotalExercisesScorePossible', '');
+        $csv_row[] = get_lang('TotalExercisesAnswered', '');
+        $csv_row[] = get_lang('TotalExercisesScorePercentage', '');
+        $csv_row[] = get_lang('LatestLogin', '');
+        $csv_content[] = $csv_row;
+
+        // the other lines (the data)
+        foreach ($course_data as $key => $course) {
+            $course_code = $course[0];
+            $course_title = $course[1];
+
+            $csv_row = array();
+            $csv_row[] = $course_title;
+
+            // getting all the courses of the session
+            $sql = "SELECT * FROM $tbl_user AS u INNER JOIN $tbl_course_rel_user AS cu ON cu.user_id = u.user_id WHERE cu.course_code = '".$course_code."' AND ISNULL(cu.role);";
+            $result = Database::query($sql);
+            $time_spent = 0;
+            $progress = 0;
+            $nb_progress_lp = 0;
+            $score = 0;
+            $nb_score_lp = 0;
+            $nb_messages = 0;
+            $nb_assignments = 0;
+            $last_login_date = false;
+            $total_score_obtained = 0;
+            $total_score_possible = 0;
+            $total_questions_answered = 0;
+            while ($row = Database::fetch_object($result)) {
+                // get time spent in the course and session
+                $time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $course_code);
+                $progress_tmp = Tracking::get_avg_student_progress($row->user_id, $course_code, array(), null, true);
+                $progress += $progress_tmp[0];
+                $nb_progress_lp += $progress_tmp[1];
+                $score_tmp = Tracking :: get_avg_student_score($row->user_id, $course_code, array(), null, true);
+                if(is_array($score_tmp)) {
+                    $score += $score_tmp[0];
+                    $nb_score_lp += $score_tmp[1];
+                }
+                $nb_messages += Tracking::count_student_messages($row->user_id, $course_code);
+                $nb_assignments += Tracking::count_student_assignments($row->user_id, $course_code);
+
+                $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row->user_id, $course_code, null, false);
+                if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned.
+                    $last_login_date = $last_login_date_tmp;
+                } else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned.
+                    // Find the max and assign it to first_login_date
+                    if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
+                        $last_login_date = $last_login_date_tmp;
+                    }
+                }
+
+                $exercise_results_tmp = MySpace::exercises_results($row->user_id, $course_code);
+                $total_score_obtained += $exercise_results_tmp['score_obtained'];
+                $total_score_possible += $exercise_results_tmp['score_possible'];
+                $total_questions_answered += $exercise_results_tmp['questions_answered'];
+            }
+            if($nb_progress_lp > 0) {
+                $avg_progress = round($progress / $nb_progress_lp, 2);
+            } else {
+                $avg_progress = 0;
+            }
+            if($nb_score_lp > 0) {
+                $avg_score = round($score / $nb_score_lp, 2);
+            } else {
+                $avg_score = '-';
+            }
+            if($last_login_date) {
+                $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
+            } else {
+                $last_login_date = '-';
+            }
+            if($total_score_possible > 0) {
+                $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
+            } else {
+                $total_score_percentage = 0;
+            }
+            // time spent in the course
+            $csv_row[] = api_time_to_hms($time_spent);
+            // student progress in course
+            $csv_row[] = $avg_progress;
+            // student score
+            $csv_row[] = $avg_score;
+            // student messages
+            $csv_row[] = $nb_messages;
+            // student assignments
+            $csv_row[] = $nb_assignments;
+            // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
+            $csv_row[] = $total_score_obtained;
+            $csv_row[] = $total_score_possible;
+            $csv_row[] = $total_questions_answered;
+            $csv_row[] = $total_score_percentage;
+            // last connection
+            $csv_row[] = $last_login_date;
+            $csv_content[] = $csv_row;
+        }
+        Export :: export_table_csv($csv_content, 'reporting_course_overview');
+        exit;
+    }
+
+    /**
+     * Display a sortable table that contains an overview of all the reporting progress of all sessions and all courses the user is subscribed to
+     * @author Guillaume Viguier <guillaume@viguierjust.com>
+     */
+    function display_tracking_session_overview() {
+        //MySpace::display_user_overview_export_options();
+
+        $t_head .= '    <table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
+        //$t_head .= '  <caption>'.get_lang('CourseInformation').'</caption>';
+        $t_head .=      '<tr>';
+        $t_head .= '        <th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
+        //$t_head .= '      <th><div style="width:40px">'.get_lang('AvgExercisesScore').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
+        $t_head .= '        <th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
+        //$t_head .= '      <th><div>'.get_lang('TotalExercisesScorePossible').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
+        //$t_head .= '      <th><div>'.get_lang('TotalExercisesScorePercentage').'</div></th>';
+        //$t_head .= '      <th><div style="width:60px">'.get_lang('FirstLogin').'</div></th>';
+        $t_head .= '        <th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
+        $t_head .= '    </tr></table>';
+
+        $addparams = array('view' => 'admin', 'display' => 'sessionoverview');
+
+        $table = new SortableTable('tracking_session_overview', array('MySpace','get_total_number_sessions'), array('MySpace','get_session_data_tracking_overview'), 1);
+        $table->additional_parameters = $addparams;
+
+        $table->set_header(0, '', false, null, array('style' => 'display: none'));
+        $table->set_header(1, get_lang('Session'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
+        $table->set_header(2, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
+        $table->set_column_filter(2, array('MySpace','session_tracking_filter'));
+        $table->display();
+    }
+
+    /**
+     * Get the total number of sessions
+     *
+     * @return integer Total number of sessions
+     */
+    public function get_total_number_sessions() {
+        // database table definition
+        $main_session_table = Database :: get_main_table(TABLE_MAIN_SESSION);
+        return Database::count_rows($main_session_table);
+    }
+
+    /**
+     * Get data for the sessions
+     *
+     * @param int Inferior limit
+     * @param int Number of items to select
+     * @param string Column to order on
+     * @param string Order direction
+     * @return array Results
+     */
+    public function get_session_data_tracking_overview($from, $number_of_items, $column, $direction) {
+        //global $_configuration;
+        // database table definition
+        //$access_url_id = api_get_current_access_url_id();
+        //$tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+        $main_session_table = Database :: get_main_table(TABLE_MAIN_SESSION);
+
+        /*if ($_configuration['multiple_access_urls']) {
+            $condition_multi_url = ", $tbl_url_rel_user as url_user WHERE user.user_id=url_user.user_id AND access_url_id='$access_url_id'";
+        }
+
+        global $export_csv;
+        if ($export_csv) {
+            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+        } else {
+            $is_western_name_order = api_is_western_name_order();
+        }*/
+        $sql = "SELECT id AS col0, name AS col1 FROM $main_session_table";
+        $sql .= " ORDER BY col$column $direction ";
+        $sql .= " LIMIT $from,$number_of_items";
+        $result = Database::query($sql);
+        $return = array ();
+        while ($session = Database::fetch_row($result)) {
+            $return[] = $session;
+        }
+        return $return;
+    }
+
+    /**
+     * Fills in session reporting data
+     *
+     * @param integer $user_id the id of the user
+     * @param array $url_params additonal url parameters
+     * @param array $row the row information (the other columns)
+     * @return string html code
+     */
+    function session_tracking_filter($session_id, $url_params, $row) {
+        $session_id = $row[0];
+        // the table header
+        $return .= '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
+        /*$return .= '  <tr>';
+        $return .= '        <th>'.get_lang('Course').'</th>';
+        $return .= '        <th>'.get_lang('AvgTimeSpentInTheCourse').'</th>';
+        $return .= '        <th>'.get_lang('AvgStudentsProgress').'</th>';
+        $return .= '        <th>'.get_lang('AvgCourseScore').'</th>';
+        $return .= '        <th>'.get_lang('AvgExercisesScore').'</th>';
+        $return .= '        <th>'.get_lang('AvgMessages').'</th>';
+        $return .= '        <th>'.get_lang('AvgAssignments').'</th>';
+        $return .= '        <th>'.get_lang('TotalExercisesScoreObtained').'</th>';
+        $return .= '        <th>'.get_lang('TotalExercisesScorePossible').'</th>';
+        $return .= '        <th>'.get_lang('TotalExercisesAnswered').'</th>';
+        $return .= '        <th>'.get_lang('TotalExercisesScorePercentage').'</th>';
+        $return .= '        <th>'.get_lang('FirstLogin').'</th>';
+        $return .= '        <th>'.get_lang('LatestLogin').'</th>';
+        $return .= '    </tr>';*/
+
+        // database table definition
+        $tbl_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_user = Database :: get_main_table(TABLE_MAIN_USER);
+
+        // getting all the courses of the user
+        $sql = "SELECT * FROM $tbl_course AS c INNER JOIN $tbl_session_rel_course AS sc ON sc.course_code = c.code WHERE sc.id_session = '".$session_id."';";
+        $result = Database::query($sql);
+        while ($row = Database::fetch_object($result)) {
+            $return .= '<tr>';
+            // course code
+            $return .= '    <td width="157px" >'.$row->title.'</td>';
+            // get the users in the course
+            $sql = "SELECT user_id FROM $tbl_user AS u INNER JOIN $tbl_session_rel_course_rel_user AS scu ON u.user_id = scu.id_user WHERE scu.id_session = '".$session_id."' AND scu.course_code = '".$row->code."';";
+            $result_users = Database::query($sql);
+            $time_spent = 0;
+            $progress = 0;
+            $nb_progress_lp = 0;
+            $score = 0;
+            $nb_score_lp = 0;
+            $nb_messages = 0;
+            $nb_assignments = 0;
+            $last_login_date = false;
+            $total_score_obtained = 0;
+            $total_score_possible = 0;
+            $total_questions_answered = 0;
+            while($row_user = Database::fetch_object($result_users)) {
+                // get time spent in the course and session
+                $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $row->code, $session_id);
+                $progress_tmp = Tracking::get_avg_student_progress($row_user->user_id, $row->code, array(), $session_id, true);
+                $progress += $progress_tmp[0];
+                $nb_progress_lp += $progress_tmp[1];
+                $score_tmp = Tracking :: get_avg_student_score($row_user->user_id, $row->code, array(), $session_id, true);
+                if(is_array($score_tmp)) {
+                    $score += $score_tmp[0];
+                    $nb_score_lp += $score_tmp[1];
+                }
+                $nb_messages += Tracking::count_student_messages($row_user->user_id, $row->code, $session_id);
+                $nb_assignments += Tracking::count_student_assignments($row_user->user_id, $row->code, $session_id);
+
+                $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $row->code, $session_id, false);
+                if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned.
+                    $last_login_date = $last_login_date_tmp;
+                } else if($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition! To be cleaned.
+                    // Find the max and assign it to first_login_date
+                    if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
+                        $last_login_date = $last_login_date_tmp;
+                    }
+                }
+
+                $exercise_results_tmp = MySpace::exercises_results($row_user->user_id, $row->code, $session_id);
+                $total_score_obtained += $exercise_results_tmp['score_obtained'];
+                $total_score_possible += $exercise_results_tmp['score_possible'];
+                $total_questions_answered += $exercise_results_tmp['questions_answered'];
+            }
+            if($nb_progress_lp > 0) {
+                $avg_progress = round($progress / $nb_progress_lp, 2);
+            } else {
+                $avg_progress = 0;
+            }
+            if($nb_score_lp > 0) {
+                $avg_score = round($score / $nb_score_lp, 2);
+            } else {
+                $avg_score = '-';
+            }
+            if($last_login_date) {
+                $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
+            } else {
+                $last_login_date = '-';
+            }
+            if($total_score_possible > 0) {
+                $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
+            } else {
+                $total_score_percentage = 0;
+            }
+            if($total_score_percentage > 0) {
+                $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
+            } else {
+                $total_score = '-';
+            }
+            // time spent in the course
+            $return .= '    <td><div>'.api_time_to_hms($time_spent).'</div></td>';
+            // student progress in course
+            $return .= '    <td><div>'.$avg_progress.'</div></td>';
+            // student score
+            $return .= '    <td><div>'.$avg_score.'</div></td>';
+            // student messages
+            $return .= '    <td><div>'.$nb_messages.'</div></td>';
+            // student assignments
+            $return .= '    <td><div>'.$nb_assignments.'</div></td>';
+            // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
+            $return .= '<td width="105px;">'.$total_score.'</td>';
+            $return .= '<td>'.$total_questions_answered.'</td>';
+            // last connection
+            $return .= '    <td><div>'.$last_login_date.'</div></td>';
+            $return .= '<tr>';
+        }
+        $return .= '</table>';
+        return $return;
+    }
+
+    /**
+     * This function exports the table that we see in display_tracking_session_overview()
+     *
+     */
+    function export_tracking_session_overview() {
+        // database table definition
+        $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_user = Database :: get_main_table(TABLE_MAIN_USER);
+
+        // the values of the sortable table
+        if ($_GET['tracking_session_overview_page_nr']) {
+            $from = $_GET['tracking_session_overview_page_nr'];
+        } else {
+            $from = 0;
+        }
+        if ($_GET['tracking_session_overview_column']) {
+            $orderby = $_GET['tracking_session_overview_column'];
+        } else {
+            $orderby = 0;
+        }
+
+        if ($_GET['tracking_session_overview_direction']) {
+            $direction = $_GET['tracking_session_overview_direction'];
+        } else {
+            $direction = 'ASC';
+        }
+
+        $session_data = MySpace::get_session_data_tracking_overview($from, 1000, $orderby, $direction);
+
+        $csv_content = array();
+
+        // the first line of the csv file with the column headers
+        $csv_row = array();
+        $csv_row[] = get_lang('Session');
+        $csv_row[] = get_lang('Course', '');
+        $csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
+        $csv_row[] = get_lang('AvgStudentsProgress', '');
+        $csv_row[] = get_lang('AvgCourseScore', '');
+        $csv_row[] = get_lang('TotalNumberOfMessages', '');
+        $csv_row[] = get_lang('TotalNumberOfAssignments', '');
+        $csv_row[] = get_lang('TotalExercisesScoreObtained', '');
+        $csv_row[] = get_lang('TotalExercisesScorePossible', '');
+        $csv_row[] = get_lang('TotalExercisesAnswered', '');
+        $csv_row[] = get_lang('TotalExercisesScorePercentage', '');
+        $csv_row[] = get_lang('LatestLogin', '');
+        $csv_content[] = $csv_row;
+
+        // the other lines (the data)
+        foreach ($session_data as $key => $session) {
+            $session_id = $session[0];
+            $session_title = $session[1];
+
+            // getting all the courses of the session
+            $sql = "SELECT * FROM $tbl_course AS c INNER JOIN $tbl_session_rel_course AS sc ON sc.course_code = c.code WHERE sc.id_session = '".$session_id."';";
+            $result = Database::query($sql);
+            while ($row = Database::fetch_object($result)) {
+                $csv_row = array();
+                $csv_row[] = $session_title;
+                $csv_row[] = $row->title;
+                // get the users in the course
+                $sql = "SELECT user_id FROM $tbl_user AS u INNER JOIN $tbl_session_rel_course_rel_user AS scu ON u.user_id = scu.id_user WHERE scu.id_session = '".$session_id."' AND scu.course_code = '".$row->code."';";
+                $result_users = Database::query($sql);
+                $time_spent = 0;
+                $progress = 0;
+                $nb_progress_lp = 0;
+                $score = 0;
+                $nb_score_lp = 0;
+                $nb_messages = 0;
+                $nb_assignments = 0;
+                $last_login_date = false;
+                $total_score_obtained = 0;
+                $total_score_possible = 0;
+                $total_questions_answered = 0;
+                while($row_user = Database::fetch_object($result_users)) {
+                    // get time spent in the course and session
+                    $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $row->code, $session_id);
+                    $progress_tmp = Tracking::get_avg_student_progress($row_user->user_id, $row->code, array(), $session_id, true);
+                    $progress += $progress_tmp[0];
+                    $nb_progress_lp += $progress_tmp[1];
+                    $score_tmp = Tracking :: get_avg_student_score($row_user->user_id, $row->code, array(), $session_id, true);
+                    if(is_array($score_tmp)) {
+                        $score += $score_tmp[0];
+                        $nb_score_lp += $score_tmp[1];
+                    }
+                    $nb_messages += Tracking::count_student_messages($row_user->user_id, $row->code, $session_id);
+                    $nb_assignments += Tracking::count_student_assignments($row_user->user_id, $row->code, $session_id);
+
+                    $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $row->code, $session_id, false);
+                    if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned.
+                        $last_login_date = $last_login_date_tmp;
+                    } else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned.
+                        // Find the max and assign it to first_login_date
+                        if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
+                            $last_login_date = $last_login_date_tmp;
+                        }
+                    }
+
+                    $exercise_results_tmp = MySpace::exercises_results($row_user->user_id, $row->code, $session_id);
+                    $total_score_obtained += $exercise_results_tmp['score_obtained'];
+                    $total_score_possible += $exercise_results_tmp['score_possible'];
+                    $total_questions_answered += $exercise_results_tmp['questions_answered'];
+                }
+                if($nb_progress_lp > 0) {
+                    $avg_progress = round($progress / $nb_progress_lp, 2);
+                } else {
+                    $avg_progress = 0;
+                }
+                if($nb_score_lp > 0) {
+                    $avg_score = round($score / $nb_score_lp, 2);
+                } else {
+                    $avg_score = '-';
+                }
+                if($last_login_date) {
+                    $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
+                } else {
+                    $last_login_date = '-';
+                }
+                if($total_score_possible > 0) {
+                    $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
+                } else {
+                    $total_score_percentage = 0;
+                }
+                if($total_score_percentage > 0) {
+                    $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
+                } else {
+                    $total_score = '-';
+                }
+                // time spent in the course
+                $csv_row[] = api_time_to_hms($time_spent);
+                // student progress in course
+                $csv_row[] = $avg_progress;
+                // student score
+                $csv_row[] = $avg_score;
+                // student messages
+                $csv_row[] = $nb_messages;
+                // student assignments
+                $csv_row[] = $nb_assignments;
+                // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
+                $csv_row[] = $total_score_obtained;
+                $csv_row[] = $total_score_possible;
+                $csv_row[] = $total_questions_answered;
+                $csv_row[] = $total_score_percentage;
+                // last connection
+                $csv_row[] = $last_login_date;
+                $csv_content[] = $csv_row;
+            }
+        }
+        Export :: export_table_csv($csv_content, 'reporting_session_overview');
+        exit;
+    }
+
+
+    /**
+     * Get general information about the exercise performance of the user
+     * the total obtained score (all the score on all the questions)
+     * the maximum score that could be obtained
+     * the number of questions answered
+     * the success percentage
+     * @param integer $user_id the id of the user
+     * @param string $course_code the course code
+     * @return array
+     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+     * @version Dokeos 1.8.6
+     * @since November 2008
+     */
+    function exercises_results($user_id, $course_code, $session_id = false) {
+        $questions_answered = 0;
+        $sql = 'SELECT exe_result , exe_weighting
+            FROM '.Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES)."
+            WHERE exe_cours_id = '".Database::escape_string($course_code)."'
+            AND exe_user_id = '".Database::escape_string($user_id)."'";
+        if($session_id !== false) {
+            $sql .= " AND session_id = '".$session_id."' ";
+        }
+        $result = Database::query($sql);
+        $score_obtained = 0;
+        $score_possible = 0;
+        $questions_answered = 0;
+        while ($row = Database::fetch_array($result)) {
+            $score_obtained += $row['exe_result'];
+            $score_possible += $row['exe_weighting'];
+            $questions_answered ++;
+        }
+
+        if ($score_possible != 0) {
+            $percentage = round(($score_obtained / $score_possible * 100), 2);
+        } else {
+            $percentage = null;
+        }
+
+        return array('score_obtained' => $score_obtained, 'score_possible' => $score_possible, 'questions_answered' => $questions_answered, 'percentage' => $percentage);
+    }
+
+    /**
+     * This function exports the table that we see in display_tracking_user_overview()
+     *
+     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+     * @version Dokeos 1.8.6
+     * @since October 2008
+     */
+    function export_tracking_user_overview() {
+
+
+        // database table definitions
+        $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+
+        $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+        $sort_by_first_name = api_sort_by_first_name();
+
+        // the values of the sortable table
+        if ($_GET['tracking_user_overview_page_nr']) {
+            $from = $_GET['tracking_user_overview_page_nr'];
+        } else {
+            $from = 0;
+        }
+        if ($_GET['tracking_user_overview_column']) {
+            $orderby = $_GET['tracking_user_overview_column'];
+        } else {
+            $orderby = 0;
+        }
+        if ($is_western_name_order != api_is_western_name_order() && ($orderby == 1 || $orderby == 2)) {
+            // Swapping the sorting column if name order for export is different than the common name order.
+            $orderby = 3 - $orderby;
+        }
+        if ($_GET['tracking_user_overview_direction']) {
+            $direction = $_GET['tracking_user_overview_direction'];
+        } else {
+            $direction = 'ASC';
+        }
+
+        $user_data = MySpace::get_user_data_tracking_overview($from, 1000, $orderby, $direction);
+
+        // the first line of the csv file with the column headers
+        $csv_row = array();
+        $csv_row[] = get_lang('OfficialCode');
+        if ($is_western_name_order) {
+            $csv_row[] = get_lang('FirstName', '');
+            $csv_row[] = get_lang('LastName', '');
+        } else {
+            $csv_row[] = get_lang('LastName', '');
+            $csv_row[] = get_lang('FirstName', '');
+        }
+        $csv_row[] = get_lang('LoginName');
+        $csv_row[] = get_lang('CourseCode');
+        // the additional user defined fields (only those that were selected to be exported)
+
+        $fields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+
+        if (is_array($_SESSION['additional_export_fields'])) {
+            foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
+                $csv_row[] = $fields[$extra_field_export][3];
+                $field_names_to_be_exported[] = 'extra_'.$fields[$extra_field_export][1];
+            }
+        }
+        $csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
+        $csv_row[] = get_lang('AvgStudentsProgress', '');
+        $csv_row[] = get_lang('AvgCourseScore', '');
+        $csv_row[] = get_lang('AvgExercisesScore', '');
+        $csv_row[] = get_lang('AvgMessages', '');
+        $csv_row[] = get_lang('AvgAssignments', '');
+        $csv_row[] = get_lang('TotalExercisesScoreObtained', '');
+        $csv_row[] = get_lang('TotalExercisesScorePossible', '');
+        $csv_row[] = get_lang('TotalExercisesAnswered', '');
+        $csv_row[] = get_lang('TotalExercisesScorePercentage', '');
+        $csv_row[] = get_lang('FirstLogin', '');
+        $csv_row[] = get_lang('LatestLogin', '');
+        $csv_content[] = $csv_row;
+
+        // the other lines (the data)
+        foreach ($user_data as $key => $user) {
+            // getting all the courses of the user
+            $sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".Database::escape_string($user[4])."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
+            $result = Database::query($sql);
+            while ($row = Database::fetch_row($result)) {
+                $csv_row = array();
+                // user official code
+                $csv_row[] = $user[0];
+                // user first|last name
+                $csv_row[] = $user[1];
+                // user last|first name
+                $csv_row[] = $user[2];
+                // user login name
+                $csv_row[] = $user[3];
+                // course code
+                $csv_row[] = $row[0];
+                // the additional defined user fields
+                $extra_fields = MySpace::get_user_overview_export_extra_fields($user[4]);
+
+                if (is_array($field_names_to_be_exported)) {
+                    foreach ($field_names_to_be_exported as $key => $extra_field_export) {
+                        $csv_row[] = $extra_fields[$extra_field_export];
+                    }
+                }
+                // time spent in the course
+                $csv_row[] = api_time_to_hms(Tracking :: get_time_spent_on_the_course ($user[4], $row[0]));
+                // student progress in course
+                $csv_row[] = round(Tracking :: get_avg_student_progress ($user[4], $row[0]), 2);
+                // student score
+                $csv_row[] = round(Tracking :: get_avg_student_score ($user[4], $row[0]), 2);
+                // student tes score
+                $csv_row[] = round(Tracking :: get_avg_student_exercise_score ($user[4], $row[0]), 2);
+                // student messages
+                $csv_row[] = Tracking :: count_student_messages ($user[4], $row[0]);
+                // student assignments
+                $csv_row[] = Tracking :: count_student_assignments ($user[4], $row[0]);
+                // student exercises results
+                $exercises_results = MySpace::exercises_results($user[4], $row[0]);
+                $csv_row[] = $exercises_results['score_obtained'];
+                $csv_row[] = $exercises_results['score_possible'];
+                $csv_row[] = $exercises_results['questions_answered'];
+                $csv_row[] = $exercises_results['percentage'];
+                // first connection
+                $csv_row[] = Tracking :: get_first_connection_date_on_the_course ($user[4], $row[0]);
+                // last connection
+                $csv_row[] = strip_tags(Tracking :: get_last_connection_date_on_the_course ($user[4], $row[0]));
+
+                $csv_content[] = $csv_row;
+            }
+        }
+        Export :: export_table_csv($csv_content, 'reporting_user_overview');
+        exit;
+    }
+
+    /**
+     * Get data for courses list in sortable with pagination
+     * @return array
+     */
+    static function get_course_data($from, $number_of_items, $column, $direction) {
+        global $courses, $csv_content, $charset, $session_id;
+
+        // definition database tables
+        $tbl_course                 = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $tbl_course_user            = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+        $tbl_session_course_user    = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+        $course_data = array();
+        $courses_code = array_keys($courses);
+
+        foreach ($courses_code as &$code) {
+            $code = "'$code'";
+        }
+
+        // get all courses with limit
+        $sql = "SELECT course.code as col1, course.title as col2
+                FROM $tbl_course course
+                WHERE course.code IN (".implode(',',$courses_code).")";
+
+        if (!in_array($direction, array('ASC','DESC'))) $direction = 'ASC';
+
+        $column = intval($column);
+        $from = intval($from);
+        $number_of_items = intval($number_of_items);
+        $sql .= " ORDER BY col$column $direction ";
+        $sql .= " LIMIT $from,$number_of_items";
+
+        $res = Database::query($sql);
+        while ($row_course = Database::fetch_row($res)) {
+
+            $course_code = $row_course[0];
+            $course_info = api_get_course_info($course_code);
+            $avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0;
+
+            // students directly subscribed to the course
+            if (empty($session_id)) {
+                $sql = "SELECT user_id FROM $tbl_course_user as course_rel_user WHERE course_rel_user.status='5' AND course_rel_user.course_code='$course_code'";
+            } else {
+                $sql = "SELECT id_user as user_id FROM $tbl_session_course_user srcu WHERE  srcu. course_code='$course_code' AND id_session = '$session_id' AND srcu.status<>2";
+            }
+            $rs = Database::query($sql);
+            $users = array();
+            while ($row = Database::fetch_array($rs)) { $users[] = $row['user_id']; }
+
+            if (count($users) > 0) {
+                $nb_students_in_course = count($users);
+                $avg_assignments_in_course  = Tracking::count_student_assignments($users, $course_code, $session_id);
+                $avg_messages_in_course     = Tracking::count_student_messages($users, $course_code, $session_id);
+                $avg_progress_in_course     = Tracking::get_avg_student_progress($users, $course_code, array(), $session_id);
+                $avg_score_in_course        = Tracking::get_avg_student_score($users, $course_code, array(), $session_id);
+                $avg_score_in_exercise      = Tracking::get_avg_student_exercise_score($users, $course_code, 0, $session_id);
+                $avg_time_spent_in_course   = Tracking::get_time_spent_on_the_course($users, $course_code, $session_id);
+
+                $avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
+                if (is_numeric($avg_score_in_course)) {
+                    $avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2);
+                }
+                $avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
+
+            } else {
+                $avg_time_spent_in_course = null;
+                $avg_progress_in_course = null;
+                $avg_score_in_course = null;
+                $avg_score_in_exercise = null;
+                $avg_messages_in_course = null;
+                $avg_assignments_in_course = null;
+            }
+            $table_row = array();
+            $table_row[] = $row_course[1];
+            $table_row[] = $nb_students_in_course;
+            $table_row[] = $avg_time_spent_in_course;
+            $table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course.'%';
+            $table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course.'%';
+            $table_row[] = is_null($avg_score_in_exercise) ? '' : $avg_score_in_exercise.'%';
+            $table_row[] = $avg_messages_in_course;
+            $table_row[] = $avg_assignments_in_course;
+
+            //set the "from" value to know if I access the Reporting by the chamilo tab or the course link
+            $table_row[] = '<center><a href="../tracking/courseLog.php?cidReq='.$course_code.'&from=myspace&id_session='.$session_id.'">
+                             <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>
+                            </center>';
+            $csv_content[] = array(
+                api_html_entity_decode($row_course[1], ENT_QUOTES, $charset),
+                $nb_students_in_course,
+                $avg_time_spent_in_course,
+                is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
+                is_null($avg_score_in_course) ? null : is_numeric($avg_score_in_course) ? $avg_score_in_course.'%' : $avg_score_in_course ,
+                is_null($avg_score_in_exercise) ? null : $avg_score_in_exercise.'%',
+                $avg_messages_in_course,
+                $avg_assignments_in_course,
+            );
+            $course_data[] = $table_row;
+        }
+        return $course_data;
+    }
+
+    /**
+     * get the numer of users of the platform
+     *
+     * @return integer
+     *
+     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+     * @version Dokeos 1.8.6
+     * @since October 2008
+     */
+    function get_number_of_users_tracking_overview() {
+        // database table definition
+        $main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
+        return Database::count_rows($main_user_table);
+    }
+
+    /**
+     * get all the data for the sortable table of the reporting progress of all users and all the courses the user is subscribed to.
+     *
+     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+     * @version Dokeos 1.8.6
+     * @since October 2008
+     */
+    function get_user_data_tracking_overview($from, $number_of_items, $column, $direction) {
+        global $_configuration;
+        // database table definition
+        $access_url_id = api_get_current_access_url_id();
+        $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+        $main_user_table = Database::get_main_table(TABLE_MAIN_USER);
+
+        if ($_configuration['multiple_access_urls']) {
+            $condition_multi_url = ", $tbl_url_rel_user as url_user WHERE user.user_id=url_user.user_id AND access_url_id='$access_url_id'";
+        }
+
+        global $export_csv;
+        if ($export_csv) {
+            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+        } else {
+            $is_western_name_order = api_is_western_name_order();
+        }
+        $sql = "SELECT
+                    official_code AS col0,
+                    ".($is_western_name_order ? "
+                    firstname       AS col1,
+                    lastname        AS col2,
+                    " : "
+                    lastname        AS col1,
+                    firstname       AS col2,
+                    ").
+                    "username       AS col3,
+                    user.user_id        AS col4
+                FROM
+                    $main_user_table as user $condition_multi_url
+                ";
+        $sql .= " ORDER BY col$column $direction ";
+        $sql .= " LIMIT $from,$number_of_items";
+        $result = Database::query($sql);
+        $return = array ();
+        while ($user = Database::fetch_row($result)) {
+            $return[] = $user;
+        }
+        return $return;
+    }
+
+    /**
+     * Get all information that the user with user_id = $user_data has
+     * entered in the additionally defined profile fields
+     * @param integer $user_id the id of the user
+     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+     * @version Dokeos 1.8.6
+     * @since November 2008
+     */
+    function get_user_overview_export_extra_fields($user_id) {
+        // include the user manager
+
+        $extra_data = UserManager::get_extra_user_data($user_id, true);
+        return $extra_data;
+    }
+    /**
+     * Checks if a username exist in the DB otherwise it create a "double"
+     * i.e. if we look into for jmontoya but the user's name already exist we create the user jmontoya2
+     * the return array will be array(username=>'jmontoya', sufix='2')
+     * @param string firstname
+     * @param string lastname
+     * @param string username
+     * @return array with the username, the sufix
+     * @author Julio Montoya Armas
+     */
+    function make_username($firstname, $lastname, $username, $language = null, $encoding = null) {
+        $table_user = Database::get_main_table(TABLE_MAIN_USER);
+        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        // if username exist
+        if (!UserManager::is_username_available($username) || empty($username)) {
+            $i = 0;
+            while (1) {
+                if ($i == 0) {
+                    $sufix = '';
+                } else {
+                    $sufix = $i;
+                }
+                $desired_username = UserManager::create_username($firstname, $lastname, $language, $encoding);
+                if (UserManager::is_username_available($desired_username.$sufix)) {
+                    break;
+                } else {
+                    $i++;
+                }
+            }
+            $username_array = array('username' => $desired_username , 'sufix' => $sufix);
+            return $username_array;
+        } else {
+            $username_array = array('username' => $username, 'sufix' => '');
+            return $username_array;
+        }
+    }
+
+    /**
+     * Checks if there are repeted users in a given array
+     * @param  array $usernames list of the usernames in the uploaded file
+     * @param  array $user_array['username'] and $user_array['sufix'] where sufix is the number part in a login i.e -> jmontoya2
+     * @return array with the $usernames array and the $user_array array
+     * @author Julio Montoya Armas
+     */
+    function check_user_in_array($usernames, $user_array) {
+        $user_list = array_keys($usernames);
+        $username = $user_array['username'].$user_array['sufix'];
+
+        if (in_array($username, $user_list)) {
+            $user_array['sufix'] += $usernames[$username];
+            $usernames[$username]++;
+        } else {
+            $usernames[$username] = 1;
+        }
+        $result_array = array($usernames, $user_array);
+        return $result_array;
+    }
+
+    /**
+     * Checks whether a username has been already subscribed in a session.
+     * @param string a given username
+     * @param array  the array with the course list codes
+     * @param the session id
+     * @return 0 if the user is not subscribed  otherwise it returns the user_id of the given username
+     * @author Julio Montoya Armas
+     */
+    function user_available_in_session($username, $course_list, $id_session) {
+        $table_user = Database::get_main_table(TABLE_MAIN_USER);
+        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $id_session = intval($id_session);
+        $username = Database::escape_string($username);
+        foreach($course_list as $enreg_course) {
+            $sql_select = " SELECT u.user_id FROM $tbl_session_rel_course_rel_user rel INNER JOIN $table_user u
+                            ON (rel.id_user=u.user_id)
+                            WHERE rel.id_session='$id_session' AND u.status='5' AND u.username ='$username' AND rel.course_code='$enreg_course'";
+            $rs = Database::query($sql_select);
+            if (Database::num_rows($rs) > 0) {
+                return Database::result($rs, 0, 0);
+            } else {
+                return 0;
+            }
+        }
+    }
+
+    /**
+    This function checks whether some users in the uploaded file repeated and creates unique usernames if necesary.
+    A case: Within the file there is an user repeted twice (Julio Montoya / Julio Montoya) and the username fields are empty.
+    Then, this function would create unique usernames based on the first and the last name. Two users wiould be created - jmontoya and jmontoya2.
+    Of course, if in the database there is a user with the name jmontoya, the newly created two users registered would be jmontoya2 and jmontoya3.
+    @param $users list of users
+    @author Julio Montoya Armas
+    */
+    function check_all_usernames($users, $course_list, $id_session) {
+        $table_user = Database::get_main_table(TABLE_MAIN_USER);
+        $usernames = array();
+        $new_users = array();
+        foreach ($users as $index => $user) {
+            $desired_username = array();
+            if (empty($user['UserName'])) {
+                $desired_username = MySpace::make_username($user['FirstName'], $user['LastName'], '');
+                $pre_username = $desired_username['username'].$desired_username['sufix'];
+                $user['UserName'] = $pre_username;
+                $user['create'] = '1';
+            } else {
+                if (UserManager::is_username_available($user['UserName'])) {
+                    $desired_username = MySpace::make_username($user['FirstName'], $user['LastName'], $user['UserName']);
+                    $user['UserName'] = $desired_username['username'].$desired_username['sufix'];
+                    $user['create'] = '1';
+                } else {
+                    $is_session_avail = MySpace::user_available_in_session($user['UserName'], $course_list, $id_session);
+                    if ($is_session_avail == 0) {
+                        $user_name = $user['UserName'];
+                        $sql_select = "SELECT user_id FROM $table_user WHERE username ='$user_name' ";
+                        $rs = Database::query($sql_select);
+                        $user['create'] = Database::result($rs, 0, 0); // This should be the ID because the user exists.
+                    } else {
+                        $user['create'] = $is_session_avail;
+                    }
+                }
+            }
+            // Usernames is the current list of users in the file.
+            $result_array = MySpace::check_user_in_array($usernames, $desired_username);
+            $usernames = $result_array[0];
+            $desired_username = $result_array[1];
+            $user['UserName'] = $desired_username['username'].$desired_username['sufix'];
+            $new_users[] = $user;
+        }
+        return $new_users;
+    }
+
+    /**
+     * This functions checks whether there are users that are already registered in the DB by different creator than the current coach.
+     * @param string a given username
+     * @param array  the array with the course list codes
+     * @param the session id
+     * @author Julio Montoya Armas
+     */
+    function get_user_creator($users, $course_list, $id_session) {
+        $errors = array();
+        foreach ($users as $index => $user) {
+            // database table definition
+            $table_user = Database::get_main_table(TABLE_MAIN_USER);
+            $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+            $username = Database::escape_string($user['UserName']);
+            //echo "<br>";
+            $sql = "SELECT creator_id FROM $table_user WHERE username='$username' ";
+
+            $rs = Database::query($sql);
+            $creator_id = Database::result($rs, 0, 0);
+            // check if we are the creators or not
+            if ($creator_id != '') {
+                if ($creator_id != api_get_user_id()) {
+                    $user['error'] = get_lang('UserAlreadyRegisteredByOtherCreator');
+                    $errors[] = $user;
+                }
+            }
+        }
+        return $errors;
+    }
+
+    /**
+     * Validates imported data.
+     * @param list of users
+     */
+    function validate_data($users, $id_session = null) {
+        $errors = array();
+        $usernames = array();
+        $new_users = array();
+        foreach ($users as $index => $user) {
+            // 1. Check whether mandatory fields are set.
+            $mandatory_fields = array('LastName', 'FirstName');
+            if (api_get_setting('registration', 'email') == 'true') {
+                $mandatory_fields[] = 'Email';
+            }
+
+            foreach ($mandatory_fields as $key => $field) {
+                if (!isset ($user[$field]) || strlen($user[$field]) == 0) {
+                    $user['error'] = get_lang($field.'Mandatory');
+                    $errors[] = $user;
+                }
+            }
+            // 2. Check whether the username is too long.
+            if (UserManager::is_username_too_long($user['UserName'])) {
+                $user['error'] = get_lang('UserNameTooLong');
+                $errors[] = $user;
+            }
+
+            $user['UserName'] = trim($user['UserName']);
+
+            if (empty($user['UserName'])) {
+                 $user['UserName'] = UserManager::create_username($user['FirstName'], $user['LastName']);
+            }
+            $new_users[] = $user;
+        }
+        $results = array('errors' => $errors, 'users' => $new_users);
+        return $results;
+    }
+
+    /**
+     * Adds missing user-information (which isn't required, like password, etc).
+     */
+    function complete_missing_data($user) {
+        // 1. Generate a password if it is necessary.
+        if (!isset ($user['Password']) || strlen($user['Password']) == 0) {
+            $user['Password'] = api_generate_password();
+        }
+        return $user;
+    }
+
+    /**
+     * Saves imported data.
+     */
+    function save_data($users, $course_list, $id_session) {
+        $tbl_session                        = Database::get_main_table(TABLE_MAIN_SESSION);
+        $tbl_session_rel_course             = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+        $tbl_session_rel_course_rel_user    = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $tbl_session_rel_user               = Database::get_main_table(TABLE_MAIN_SESSION_USER);
+
+        $id_session = intval($id_session);
+        $sendMail = $_POST['sendMail'] ? 1 : 0;
+
+        // Adding users to the platform.
+        $new_users = array();
+        foreach ($users as $index => $user) {
+            $user = MySpace::complete_missing_data($user);
+            // coach only will registered users
+            $default_status = '5';
+            if ($user['create'] == '1') {
+                $user['id'] = UserManager :: create_user($user['FirstName'], $user['LastName'], $default_status, $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], api_get_setting('PlatformLanguage'), $user['PhoneNumber'], '');
+                $user['added_at_platform'] = 1;
+            } else {
+                $user['id'] = $user['create'];
+                $user['added_at_platform'] = 0;
+            }
+            $new_users[] = $user;
+        }
+        // Update user list.
+        $users = $new_users;
+
+        // Inserting users.
+        $super_list = array();
+        foreach ($course_list as $enreg_course) {
+            $nbr_users = 0;
+            $new_users = array();
+            $enreg_course = Database::escape_string($enreg_course);
+            foreach ($users as $index => $user) {
+                $userid = intval($user['id']);
+                $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$userid')";
+                $course_session = array('course' => $enreg_course, 'added' => 1);
+                //$user['added_at_session'] = $course_session;
+                Database::query($sql);
+                if (Database::affected_rows()) {
+                    $nbr_users++;
+                }
+                $new_users[] = $user;
+            }
+            $super_list[] = $new_users;
+
+            //update the nbr_users field
+            $sql_select = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course'";
+            $rs = Database::query($sql_select);
+            list($nbr_users) = Database::fetch_array($rs);
+            $sql_update = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'";
+            Database::query($sql_update);
+
+            $sql_update = "UPDATE $tbl_session SET nbr_users= '$nbr_users' WHERE id='$id_session'";
+            Database::query($sql_update);
+        }
+        // We don't delete the users (thoughts while dreaming)
+        //$sql_delete = "DELETE FROM $tbl_session_rel_user WHERE id_session = '$id_session'";
+        //Database::query($sql_delete);
+
+        $new_users = array();
+        foreach ($users as $index => $user) {
+            $userid = $user['id'];
+            $sql_insert = "INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user) VALUES('$id_session','$userid')";
+            Database::query($sql_insert);
+            $user['added_at_session'] = 1;
+            $new_users[] = $user;
+        }
+
+        $users = $new_users;
+        $registered_users = get_lang('FileImported').'<br /> Import file results : <br />';
+        // Sending emails.
+        $addedto = '';
+        if ($sendMail) {
+            $i = 0;
+            foreach ($users as $index => $user) {
+                $emailto = api_get_person_name($user['FirstName'], $user['LastName'], null, PERSON_NAME_EMAIL_ADDRESS).' <'.$user['Email'].'>';
+                $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
+                $emailbody = get_lang('Dear').' '.api_get_person_name($user['FirstName'], $user['LastName']).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : $user[UserName]\n".get_lang('Pass')." : $user[Password]\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path(WEB_PATH)." \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')."";
+                $emailheaders = 'From: '.api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS).' <'.api_get_setting('emailAdministrator').">\n";
+                $emailheaders .= 'Reply-To: '.api_get_setting('emailAdministrator');
+                
+                /*$extra = get_user_overview_export_extra_fields($user['user_id']);
+                $additionalParameters = array(
                     'smsType' => WELCOME_LOGIN_PASSWORD,
                     'userId' => $user['user_id'],
                     'mobilePhoneNumber' => $extra['mobile_phone_number'],
                     'password' => "$user[Password]"
                 );*/
+                
+                @api_send_mail($emailto, $emailsubject, $emailbody, $emailheaders/*, $additionalParameters*/);
+
+                if (($user['added_at_platform'] == 1  && $user['added_at_session'] == 1) || $user['added_at_session'] == 1) {
+                    if ($user['added_at_platform'] == 1) {
+                        $addedto = get_lang('UserCreatedPlatform');
+                    } else  {
+                        $addedto = '          ';
+                    }
+
+                    if ($user['added_at_session'] == 1) {
+                        $addedto .= get_lang('UserInSession');
+                    }
+                    $registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
+                } else {
+                    $addedto = get_lang('UserNotAdded');
+                    $registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
+                }
+            }
+        } else {
+            $i = 0;
+            foreach ($users as $index => $user) {
+                if (($user['added_at_platform'] == 1 && $user['added_at_session'] == 1) || $user['added_at_session'] == 1) {
+                    if ($user['added_at_platform'] == 1) {
+                        $addedto = get_lang('UserCreatedPlatform');
+                    } else {
+                        $addedto = '          ';
+                    }
+
+                    if ($user['added_at_session'] == 1) {
+                        $addedto .= ' '.get_lang('UserInSession');
+                    }
+
+                    $registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
+                } else {
+                    $addedto = get_lang('UserNotAdded');
+                    $registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
+                }
+            }
+        }
+
+        header('Location: course.php?id_session='.$id_session.'&action=show_message&message='.urlencode($registered_users));
+        exit ();
+
+        //header('Location: resume_session.php?id_session='.$id_session);
+    }
+
+    /**
+     * Reads CSV-file.
+     * @param string $file Path to the CSV-file
+     * @return array All userinformation read from the file
+     */
+    function parse_csv_data($file) {
+        $users = Import :: csv_to_array($file);
+        foreach ($users as $index => $user) {
+            if (isset ($user['Courses'])) {
+                $user['Courses'] = explode('|', trim($user['Courses']));
+            }
+            $users[$index] = $user;
+        }
+        return $users;
+    }
+
+    /**
+     * XML-parser: the handler at the beginning of element.
+     */
+    function element_start($parser, $data) {
+        $data = api_utf8_decode($data);
+        global $user;
+        global $current_tag;
+        switch ($data) {
+            case 'Contact' :
+                $user = array ();
+                break;
+            default :
+                $current_tag = $data;
+        }
+    }
+
+    /**
+     * XML-parser: the handler at the end of element.
+     */
+    function element_end($parser, $data) {
+        $data = api_utf8_decode($data);
+        global $user;
+        global $users;
+        global $current_value;
+        global $purification_option_for_usernames;
+        $user[$data] = $current_value;
+        switch ($data) {
+            case 'Contact' :
+                $user['UserName'] = UserManager::purify_username($user['UserName'], $purification_option_for_usernames);
+                $users[] = $user;
+                break;
+            default :
+                $user[$data] = $current_value;
+                break;
+        }
+    }
+
+    /**
+     * XML-parser: the handler for character data.
+     */
+    function character_data($parser, $data) {
+        $data = trim(api_utf8_decode($data));
+        global $current_value;
+        $current_value = $data;
+    }
 
-				@api_send_mail($emailto, $emailsubject, $emailbody, $emailheaders/*, $additional_parameters*/);
-
-				if (($user['added_at_platform'] == 1  && $user['added_at_session'] == 1) || $user['added_at_session'] == 1) {
-					if ($user['added_at_platform'] == 1) {
-						$addedto = get_lang('UserCreatedPlatform');
-					} else  {
-						$addedto = '          ';
-					}
-
-					if ($user['added_at_session'] == 1) {
-						$addedto .= get_lang('UserInSession');
-					}
-					$registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
-				} else {
-					$addedto = get_lang('UserNotAdded');
-					$registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
-				}
-			}
-		} else {
-			$i = 0;
-			foreach ($users as $index => $user) {
-				if (($user['added_at_platform'] == 1 && $user['added_at_session'] == 1) || $user['added_at_session'] == 1) {
-					if ($user['added_at_platform'] == 1) {
-						$addedto = get_lang('UserCreatedPlatform');
-					} else {
-						$addedto = '          ';
-					}
-
-					if ($user['added_at_session'] == 1) {
-						$addedto .= ' '.get_lang('UserInSession');
-					}
-
-					$registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
-				} else {
-					$addedto = get_lang('UserNotAdded');
-					$registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
-				}
-			}
-		}
-
-		header('Location: course.php?id_session='.$id_session.'&action=show_message&message='.urlencode($registered_users));
-		exit ();
-
-		//header('Location: resume_session.php?id_session='.$id_session);
-	}
-
-	/**
-	 * Reads CSV-file.
-	 * @param string $file Path to the CSV-file
-	 * @return array All userinformation read from the file
-	 */
-	function parse_csv_data($file) {
-		$users = Import :: csv_to_array($file);
-		foreach ($users as $index => $user) {
-			if (isset ($user['Courses'])) {
-				$user['Courses'] = explode('|', trim($user['Courses']));
-			}
-			$users[$index] = $user;
-		}
-		return $users;
-	}
-
-	/**
-	 * XML-parser: the handler at the beginning of element.
-	 */
-	function element_start($parser, $data) {
-		$data = api_utf8_decode($data);
-		global $user;
-		global $current_tag;
-		switch ($data) {
-			case 'Contact' :
-				$user = array ();
-				break;
-			default :
-				$current_tag = $data;
-		}
-	}
-
-	/**
-	 * XML-parser: the handler at the end of element.
-	 */
-	function element_end($parser, $data) {
-		$data = api_utf8_decode($data);
-		global $user;
-		global $users;
-		global $current_value;
-		global $purification_option_for_usernames;
-		$user[$data] = $current_value;
-		switch ($data) {
-			case 'Contact' :
-				$user['UserName'] = UserManager::purify_username($user['UserName'], $purification_option_for_usernames);
-				$users[] = $user;
-				break;
-			default :
-				$user[$data] = $current_value;
-				break;
-		}
-	}
-
-	/**
-	 * XML-parser: the handler for character data.
-	 */
-	function character_data($parser, $data) {
-		$data = trim(api_utf8_decode($data));
-		global $current_value;
-		$current_value = $data;
-	}
-
-	/**
-	 * Reads XML-file.
-	 * @param string $file Path to the XML-file
-	 * @return array All userinformation read from the file
-	 */
-	function parse_xml_data($file) {
-		global $current_tag;
-		global $current_value;
-		global $user;
-		global $users;
-		$users = array ();
-		$parser = xml_parser_create('UTF-8');
-		xml_set_element_handler($parser, array('MySpace','element_start'), array('MySpace','element_end'));
-		xml_set_character_data_handler($parser, "character_data");
-		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
-		xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
-		xml_parser_free($parser);
-		return $users;
-	}
+    /**
+     * Reads XML-file.
+     * @param string $file Path to the XML-file
+     * @return array All userinformation read from the file
+     */
+    function parse_xml_data($file) {
+        global $current_tag;
+        global $current_value;
+        global $user;
+        global $users;
+        $users = array ();
+        $parser = xml_parser_create('UTF-8');
+        xml_set_element_handler($parser, array('MySpace','element_start'), array('MySpace','element_end'));
+        xml_set_character_data_handler($parser, "character_data");
+        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
+        xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
+        xml_parser_free($parser);
+        return $users;
+    }
 }
 
 

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

@@ -133,8 +133,7 @@ abstract class OpenofficeDocument extends learnpath
         } else {
             // get result from webservices
             $result = $this->_get_remote_ppt2lp_files($file);
-            $result = unserialize(base64_decode($result));
-
+            $result = unserialize($result);
             // Save remote images to server
             chmod($this->base_work_dir.$this->created_dir, api_get_permissions_for_new_directories());
             if (!empty($result['images'])) {
@@ -174,7 +173,6 @@ abstract class OpenofficeDocument extends learnpath
      */
     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');
 
@@ -182,27 +180,29 @@ abstract class OpenofficeDocument extends learnpath
         $secret_key = sha1(api_get_setting('service_ppt2lp', 'ftp_password'));
 
         // client
-        $client = new nusoap_client($ppt2lp_host, true);
-
+        $options = array(
+            'location' => $ppt2lp_host,
+            'uri' => $ppt2lp_host,
+            'trace' => 1,
+            'exception' => 1,
+            'cache_wsdl' => WSDL_CACHE_NONE,
+        );
+        $client = new SoapClient(null, $options);
         $result = '';
-        $err = $client->getError();
-        if (!$err) {
 
-            $file_data = base64_encode(file_get_contents($file['tmp_name']));
-            $file_name = $file['name'];
-            $service_ppt2lp_size = api_get_setting('service_ppt2lp', 'size');
+        $file_data = base64_encode(file_get_contents($file['tmp_name']));
+        $file_name = $file['name'];
+        $service_ppt2lp_size = api_get_setting('service_ppt2lp', 'size');
 
-            $params = array(
-                'secret_key' => $secret_key,
-                'file_data' => $file_data,
-                'file_name' => $file_name,
-                'service_ppt2lp_size' => $service_ppt2lp_size,
-            );
+        $params = array(
+            'secret_key' => $secret_key,
+            'file_data' => $file_data,
+            'file_name' => $file_name,
+            'service_ppt2lp_size' => $service_ppt2lp_size,
+        );
+
+        $result = $client->__call('wsConvertPpt', array('pptData' => $params));
 
-            $result = $client->call('ws_convert_ppt', array('convert_ppt' => $params));
-        } else {
-            return false;
-        }
         return $result;
     }
 

+ 15 - 3
main/social/profile.php

@@ -18,6 +18,7 @@ if (api_get_setting('allow_social_tool') !='true') {
 }
 
 $user_id = api_get_user_id();
+$isAdmin = api_is_platform_admin($user_id);
 
 $show_full_profile = true;
 //social tab
@@ -65,6 +66,13 @@ if (isset($_GET['u'])) {
 } else {
     $user_info    = UserManager::get_user_info_by_id($user_id);
 }
+
+if ($user_info['user_id'] == api_get_user_id()) {
+    $isSelfUser = true;
+} else {
+    $isSelfUser = false;
+}
+$userIsOnline = user_is_online($user_id);
 $libpath = api_get_path(LIBRARY_PATH);
 require_once api_get_path(SYS_CODE_PATH).'calendar/myagenda.inc.php';
 require_once api_get_path(SYS_CODE_PATH).'announcements/announcements.inc.php';
@@ -315,12 +323,14 @@ if (!empty($user_info['firstname']) || !empty($user_info['lastname'])) {
 
 if ($show_full_profile) {
     $personal_info .=  '<dl class="dl-horizontal">';
-    $personal_info .=  '<dt>'.get_lang('UserName').'</dt><dd>'. $user_info['username'].'    </dd>';
+    if ($isAdmin || $isSelfUser) {
+        $personal_info .=  '<dt>'.get_lang('UserName').'</dt><dd>'. $user_info['username'].'    </dd>';
+    }
     if (!empty($user_info['firstname']) || !empty($user_info['lastname'])) {
         $personal_info .=  '<dt>'.get_lang('Name')
             .'</dt><dd>'. api_get_person_name($user_info['firstname'], $user_info['lastname']).'</dd>';
     }
-    if (!empty($user_info['official_code'])) {
+    if (($isAdmin || $isSelfUser) && !empty($user_info['official_code'])) {
         $personal_info .=  '<dt>'.get_lang('OfficialCode').'</dt><dd>'.$user_info['official_code'].'</dd>';
     }
     if (!empty($user_info['email'])) {
@@ -335,7 +345,9 @@ if ($show_full_profile) {
 } else {
     $personal_info .=  '<dl class="dl-horizontal">';
     if (!empty($user_info['username'])) {
-        $personal_info .=  '<dt>'.get_lang('UserName').'</dt><dd>'. $user_info['username'].'</dd>';
+        if ($isAdmin || $isSelfUser) {
+            $personal_info .=  '<dt>'.get_lang('UserName').'</dt><dd>'. $user_info['username'].'</dd>';
+        }
     }
     $personal_info .=  '</dl>';
 }

+ 11 - 5
main/template/default/skill/skill_wheel.js.tpl

@@ -180,10 +180,16 @@ function set_skill_style(d, attribute, searched_skill_id) {
     }
     
     //4. Blue - if user achieved that skill
-    if (d.achieved) {        
-        return_fill = '#3A87AD';        
-        //return_stroke = '#FCD23A';
-    }
+    //var skill = false;
+    $.ajax({
+        url: url+'&a=get_user_skill&profile_id='+d.id,
+        async: false,
+        success: function(skill) {
+            if (skill == 1) {
+                return_fill = '#3A87AD';
+            }
+        }
+    }); 
 
     switch (attribute) {
         case 'fill':
@@ -490,7 +496,7 @@ function load_nodes(load_skill_id, main_depth, extra_parent_id) {
     //.size([1, 2])
     .value(function(d) {
         //return 5.8 - d.depth;
-        //When having more than 4 children seems that the code above doesn't work
+        //When having more than 4 children seems that the code above does not work
         return 1;
     });
 

+ 37 - 20
main/template/default/skill/skill_wheel.tpl

@@ -285,7 +285,8 @@ $(document).ready(function() {
     
     /* Click in profile */
     $("#saved_profiles").on("click", "a.load_profile", function() {
-        profile_id = $(this).attr('rel');        
+        profile_id = $(this).attr('rel');
+        $('#profile_id').attr('value',profile_id);        
         $.ajax({
            url: '{{ url }}&a=get_skills_by_profile&profile_id='+profile_id,
            success:function(json) {
@@ -372,16 +373,29 @@ $(document).ready(function() {
     load_nodes(0, main_depth);
     
     function open_save_profile_popup() {
+        var profileId = $("#profile_id").val();
+        $.ajax({
+            url: '{{ url }}&a=get_profile&profile_id='+profileId,
+            success:function(data) {
+                if (data) {
+                    var obj = jQuery.parseJSON (data);
+                    $("#name_profile").attr('value', obj.name);
+                    $("#description_profile").attr('value', obj.description);
+                }
+            }
+        });
+        
         $("#dialog-form-profile").dialog({
             buttons: {
                 "{{ "Save"|get_lang }}" : function() {
-                    var params = $("#save_profile_form").serialize();
+                    var name = $("#name_profile").val();
+                    var description = $("#description_profile").val();
                     var skill_list = return_skill_list_from_profile_search();                    
                     skill_list = { 'skill_id' : skill_list };
                     skill_params = $.param(skill_list);
         
                     $.ajax({
-                        url: '{{ url }}&a=save_profile&'+params+'&'+skill_params,
+                        url: '{{ url }}&a=save_profile&name='+name+'&description='+description+'&'+skill_params+'&profile='+profileId,
                         success:function(data) {
                             if (data == 1 ) {
                                 update_my_saved_profiles();
@@ -391,15 +405,17 @@ $(document).ready(function() {
                             }
                             
                             $("#dialog-form-profile").dialog("close");                            
-                            $("#name").attr('value', '');
-                            $("#description").attr('value', '');                             
+                            $("#name_profile").attr('value', '');
+                            $("#description_profile").attr('value', '');
+                            $("#profile_id").attr('value', '0');                             
                          }                           
                      });
                   }
             },
             close: function() {     
-                $("#name").attr('value', '');
-                $("#description").attr('value', '');                
+                $("#name_profile").attr('value', '');
+                $("#description_profile").attr('value', '');
+                $("#profile_id").attr('value', '0');                
             }
         });
         $("#dialog-form-profile").dialog("open");
@@ -445,7 +461,7 @@ $(document).ready(function() {
                     </select>
                     <br /><br />
                     <div class="btn-group">
-                        <a class="btn load_root" rel="0" href="#">{{ "SkillRoot"|get_lang }}</a>
+                        <a class="btn load_root" rel="0" href="#">{{ "ViewSkillsWheel"|get_lang }}</a>
                         <!-- <a id="clear_selection" class="btn">{{ "Clear"|get_lang }}</a> -->	
                     </div>
                     <ul id="skill_holder" class="holder holder_simple">
@@ -545,21 +561,22 @@ $(document).ready(function() {
 </div>
         
         
-<div id="dialog-form-profile" style="display:none;">    
-    <form id="save_profile_form" class="form-horizontal" name="form">       
+<div id="dialog-form-profile" style="display:none;">
+    <form id="save_profile_form" class="form-horizontal" name="form">
+        <input type="hidden" id="profile_id" name="profile_id"/>
         <fieldset>
-            <div class="control-group">            
-                <label class="control-label" for="name">{{"Name"|get_lang}}</label>            
+            <div class="control-group">
+                <label class="control-label" for="name">{{"Name"|get_lang}}</label>
                 <div class="controls">
-                    <input type="text" name="name" id="name" size="40" />             
+                    <input type="text" name="name" id="name_profile" size="40" />
                 </div>
-            </div>        
-            <div class="control-group">            
-                <label class="control-label" for="name">{{"Description"|get_lang}}</label>            
+            </div>
+            <div class="control-group">
+                <label class="control-label" for="name">{{"Description"|get_lang}}</label>
                 <div class="controls">
-                    <textarea name="description" id="description" class="span2"  rows="7"></textarea>
+                    <textarea name="description" id="description_profile" class="span2" rows="7"></textarea>
                 </div>
-            </div>  
+            </div>
         </fieldset>
-    </form>    
-</div>
+    </form>
+</div>

+ 22 - 14
main/user/user_add.php

@@ -1,13 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt*/
 /**
-*	@package chamilo.user
+* @package chamilo.user
 */
 /**
  * Code
  */
 
-/* INIT	*/
+/* INIT */
 
 // name of the language file that needs to be included
 $language_file="registration";
@@ -25,7 +25,7 @@ $tbl_courseUser    = "course_rel_user";
 
 
 
-/* DATA CHECKING	*/
+/* DATA CHECKING */
 
 if($register) {
     /*
@@ -94,9 +94,9 @@ if($register) {
 
                     break;
                 }
-            }				// end while $result
-        }					// end if num rows
-    }						// end if datachecked
+            }       // end while $result
+        }         // end if num rows
+    }           // end if datachecked
 
 
 
@@ -203,16 +203,24 @@ if($register) {
             $message = stripslashes(api_get_person_name($firstname_form, $lastname_form))." ".get_lang('AddedU');
         }
 
-        $additional_parameters = array(
+        $additionalParameters = array(
             'smsType' => BEEN_SUBSCRIBED_COURSE,
             'userId' => $user_id,
             'courseTitle' => $currentCourseName
         );
 
-        api_mail_html($recipient_name, $email_form, $emailsubject, $emailbody, 
-          $sender_name,$email_admin, null, null, null, $additional_parameters);
-
-        //@api_mail($recipient_name, $email_form, $emailsubject, $emailbody, $sender_name,$email_admin);
+        api_mail_html(
+            $recipient_name,
+            $email_form,
+            $emailsubject,
+            $emailbody,
+            $sender_name,
+            $email_admin,
+            null,
+            null,
+            null,
+            $additionalParameters
+        );
 
         /*
          * remove <form> variables to prevent any pre-filled fields
@@ -220,10 +228,10 @@ if($register) {
 
         unset($lastname_form, $firstname_form, $username_form, $password_form, $email_form, $admin_form, $tutor_form);
 
-    } 	// end if ($platformRegSucceed)
+    }   // end if ($platformRegSucceed)
     //else
     //{
-    //	$message = get_lang('UserAlreadyRegistered');
+    //  $message = get_lang('UserAlreadyRegistered');
     //}
 
 } // end if register request
@@ -335,7 +343,7 @@ if ($_cid) // if we're inside a course, then it's a course registration
 </tr>
 <?php
 
-}			// end if $_cid - for the case we're not in a course registration
+}     // end if $_cid - for the case we're not in a course registration
             // but a platform registration
 else
 {

+ 121 - 0
main/webservices/additional_webservices.php

@@ -0,0 +1,121 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * @package chamilo.webservices
+ * @author Francis Gonzales
+ */
+
+require_once '../inc/global.inc.php';
+$libpath = api_get_path(LIBRARY_PATH);
+require_once $libpath.'fileManage.lib.php';
+require_once $libpath.'fileUpload.lib.php';
+require_once api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php';
+require_once $libpath.'add_course.lib.inc.php';
+
+
+/**
+ * Function to convert from ppt to png
+ * This function is used from Chamilo Rapid Lesson
+ *
+ * @param array $pptData
+ * @return string
+ */
+function wsConvertPpt($pptData)
+{
+    $fileData = $pptData['file_data'];
+    $dataInfo = pathinfo($pptData['file_name']);
+    $fileName =  basename($pptData['file_name'], '.' . $dataInfo['extension']);
+    $fullFileName = $pptData['file_name'];
+
+    $tempArchivePath = api_get_path(SYS_ARCHIVE_PATH);
+    $tempPath = $tempArchivePath . 'wsConvert/' . $fileName . '/';
+    $tempPathNewFiles = $tempArchivePath . 'wsConvert/' . $fileName . '-n/';
+
+    $perms = api_get_permissions_for_new_directories();
+    if (!is_dir($tempPath)) {
+        mkdir($tempPath, $perms, true);
+    }
+    if (!is_dir($tempPathNewFiles)) {
+        mkdir($tempPathNewFiles, $perms, true);
+    }
+    if (!is_dir($tempPathNewFiles . $fileName)) {
+        mkdir($tempPathNewFiles . $fileName, $perms, true);
+    }
+
+    $file = base64_decode($fileData);
+    file_put_contents($tempPath . $fullFileName, $file);
+
+    if (IS_WINDOWS_OS) { // IS_WINDOWS_OS has been defined in main_api.lib.php
+        $converterPath = str_replace('/', '\\', api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png');
+        $classPath = $converterPath . ';' . $converterPath . '/jodconverter-2.2.2.jar;' . $converterPath . '/jodconverter-cli-2.2.2.jar';
+        $cmd = 'java -Dfile.encoding=UTF-8 -cp "' . $classPath . '" DokeosConverter';
+    } else {
+        $converterPath = api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png';
+        $classPath = ' -Dfile.encoding=UTF-8 -cp .:jodconverter-2.2.2.jar:jodconverter-cli-2.2.2.jar';
+        $cmd = 'cd ' . $converterPath . ' && java ' . $classPath . ' DokeosConverter';
+    }
+
+    $cmd .= ' -p ' . api_get_setting('service_ppt2lp', 'port');
+    $cmd .= ' -w 720 -h 540 -d oogie "' . $tempPath . $fullFileName.'"  "' . $tempPathNewFiles . $fileName . '.html"';
+
+    $perms = api_get_permissions_for_new_files();
+    chmod($tempPath, $perms);
+    chmod($tempPathNewFiles, $perms);
+    chmod($tempPathNewFiles . $fileName, $perms, true);
+
+    $files = array();
+    $return = 0;
+    $shell = exec($cmd, $files, $return);
+
+    if ($return === 0) {
+        $images = array();
+        foreach ($files as $file) {
+            $imageData = explode('||', $file);
+            $images[$imageData[1]] = base64_encode(file_get_contents($tempPathNewFiles . $fileName . '/' . $imageData[1]));
+        }
+        $data = array(
+            'files' => $files,
+            'images' => $images
+        );
+
+        deleteDirectory($tempPath);
+        deleteDirectory($tempPathNewFiles);
+
+        return serialize($data);
+    } else {
+        deleteDirectory($tempPath);
+        deleteDirectory($tempPathNewFiles);
+
+        return false;
+    }
+}
+
+/**
+ * @param $directoryPath
+ * @return bool
+ */
+function deleteDirectory($directoryPath)
+{
+    $files = array_diff(scandir($directoryPath), array('.','..'));
+    foreach ($files as $file) {
+        if (is_dir("$directoryPath/$file")) {
+            deleteDirectory("$directoryPath/$file");
+        } else {
+            unlink("$directoryPath/$file");
+        }
+    }
+
+    return rmdir($directoryPath);
+}
+
+
+$webPath = api_get_path(WEB_PATH);
+$webCodePath = api_get_path(WEB_CODE_PATH);
+$options = array(
+    'uri' => $webPath,
+    'location' => $webCodePath . 'webservices/additional_webservices.php'
+);
+
+$soapServer = new SoapServer(NULL, $options);
+$soapServer->addFunction('wsConvertPpt');
+$soapServer->handle();

+ 160 - 0
main/webservices/registration.soap.php

@@ -1526,6 +1526,166 @@ function WSEditUser($params) {
     return  $return;
 }
 
+/* Register WSEditUserWithPicture function */
+// Register the data structures used by the service
+$server->wsdl->addComplexType(
+    'editUserWithPicture',
+    'complexType',
+    'struct',
+    'all',
+    '',
+    array(
+        'original_user_id_value' => array('name' => 'original_user_id_value', 'type' => 'xsd:string'),
+        'original_user_id_name' => array('name' => 'original_user_id_name', 'type' => 'xsd:string'),
+        'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
+        'lastname' => array('name' => 'lastname', 'type' => 'xsd:string'),
+        'username' => array('name' => 'username', 'type' => 'xsd:string'),
+        'password' => array('name' => 'password', 'type' => 'xsd:string'),
+        'email' => array('name' => 'email', 'type' => 'xsd:string'),
+        'status' => array('name' => 'status', 'type' => 'xsd:string'),
+        'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
+        'expiration_date' => array('name' => 'expiration_date', 'type' => 'xsd:string'),
+        'extra' => array('name' => 'extra', 'type' => 'tns:extrasList'),
+        'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
+        'picture_url' => array('name' => 'picture_url', 'type' => 'xsd:string')
+    )
+);
+
+// Register the method to expose
+$server->register('WSEditUserWithPicture',              // method name
+    array('editUserWithPicture' => 'tns:editUserWithPicture'),     // input parameters
+    array('return' => 'xsd:string'),                    // output parameters
+    'urn:WSRegistration',                               // namespace
+    'urn:WSRegistration#WSEditUserWithPicture',         // soapaction
+    'rpc',                                              // style
+    'encoded',                                          // use
+    'This service edits a user from wiener'             // documentation
+);
+
+// Define the method WSEditUserWithPicture
+function WSEditUserWithPicture($params) {
+    global $_configuration;
+
+    if(!WSHelperVerifyKey($params)) {
+        return return_error(WS_ERROR_SECRET_KEY);
+    }
+
+    $table_user = Database :: get_main_table(TABLE_MAIN_USER);
+    $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+    $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+
+    $original_user_id_value = $params['original_user_id_value'];
+    $original_user_id_name = $params['original_user_id_name'];
+    $firstname = $params['firstname'];
+    $lastname = $params['lastname'];
+    $username = $params['username'];
+    $password = null;
+    $auth_source = null;
+    $email = $params['email'];
+    $status = $params['status'];
+    $official_code = '';
+    $phone = $params['phone'];
+    $picture_url = $params['picture_url'];
+    $picture_uri = '';
+    $expiration_date = $params['expiration_date'];
+    $active = 1;
+    $creator_id = null;
+    $hr_dept_id = 0;
+    $extra = null;
+    $extra_list = $params['extra'];
+
+    if (!empty($params['password'])) { $password = $params['password']; }
+
+
+    // Get user id from id wiener
+
+    $user_id = UserManager::get_user_id_from_original_id($original_user_id_value, $original_user_id_name);
+    
+    // Get picture and generate uri.
+    $filename = basename($picture_url);
+    $tempdir = sys_get_temp_dir();
+    $tempDir = api_get_path(SYS_ARCHIVE_PATH);
+    file_put_contents($tempDir.$filename, file_get_contents($picture_url));
+    $picture_uri = UserManager::update_user_picture($user_id, $filename, $tempDir.$filename);
+
+    if ($user_id == 0) {
+        return 0;
+    } else {
+        $sql = "SELECT user_id FROM $table_user WHERE user_id ='$user_id' AND active= '0'";
+        $resu = Database::query($sql);
+        $r_check_user = Database::fetch_row($resu);
+        if (!empty($r_check_user[0])) {
+            return 0;
+        }
+    }
+
+    // Check whether username already exits.
+    $sql = "SELECT username FROM $table_user WHERE username = '$username' AND user_id <> '$user_id'";
+    $res_un = Database::query($sql);
+    $r_username = Database::fetch_row($res_un);
+
+    if (!empty($r_username[0])) {
+        return 0;
+    }
+    // Edit lastname an firstname only if not empty
+    $sql = "UPDATE $table_user SET ";
+    if (!empty($lastname)) {
+        $sql .= " lastname='".Database::escape_string($lastname)."', ";
+    }
+    if (!empty($firstname)) {
+        $sql .= " firstname='".Database::escape_string($firstname)."', ";
+    }
+    $sql .= " username='".Database::escape_string($username)."',";
+    if (!is_null($password)) {
+        $password = $_configuration['password_encryption'] ? api_get_encrypted_password($password) : $password;
+        $sql .= " password='".Database::escape_string($password)."',";
+    }
+    if (!is_null($auth_source)) {
+        $sql .=    " auth_source='".Database::escape_string($auth_source)."',";
+    }
+
+    // Exception for admins in case no status is provided in WS call...
+    $t_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
+    $sqladmin = "SELECT user_id FROM $t_admin WHERE user_id = ".intval($user_id);
+    $resadmin = Database::query($sqladmin);
+    $is_admin = Database::num_rows($resadmin);
+
+    if (empty($status)) {
+        $status = 5;
+    }
+
+    if ($is_admin) {
+        $status = 1;
+    }
+
+    $sql .=    "
+            email='".Database::escape_string($email)."',
+            status='".Database::escape_string($status)."',
+            official_code='".Database::escape_string($official_code)."',
+            phone='".Database::escape_string($phone)."',
+            picture_uri='".Database::escape_string($picture_uri)."',
+            expiration_date='".Database::escape_string($expiration_date)."',
+            active='".Database::escape_string($active)."',
+            hr_dept_id=".intval($hr_dept_id);
+
+    if (!is_null($creator_id)) {
+        $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
+    }
+    $sql .=    " WHERE user_id='$user_id'";
+    $return = @Database::query($sql);
+
+    if (is_array($extra_list) && count($extra_list) > 0) {
+        foreach ($extra_list as $extra) {
+            $extra_field_name = $extra['field_name'];
+            $extra_field_value = $extra['field_value'];
+            // Save the external system's id into user_field_value table.
+            $res = UserManager::update_extra_field_value($user_id, $extra_field_name, $extra_field_value);
+        }
+    }
+
+    return  $return;
+}
+
 /* Register WSEditUsersPasswordCrypted function */
 // Register the data structures used by the service
 $server->wsdl->addComplexType(

File diff suppressed because it is too large
+ 359 - 359
main/work/work.lib.php


+ 8 - 4
plugin/clockworksms/config.php

@@ -1,11 +1,15 @@
 <?php
-/* For licensing terms, see /license.txt */
-
-/* bbb parameters that will be registered in the course settings */
+/* For licensing terms, see /vendor/license.txt */
 
+/**
+ * Clockwork parameters that will be registered in the current settings
+ *
+ * @package chamilo.plugin.clockworksms
+ * @author  Imanol Losada <imanol.losada@beeznest.com>
+ */
 require_once __DIR__ . '/../../main/inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'plugin.class.php';
 
 require_once 'lib/clockworksms.lib.php';
-require_once 'lib/clockworksms_api.php';
+require_once 'vendor/clockworksms_api.php';
 require_once 'lib/clockworksms_plugin.class.php';

+ 0 - 2
plugin/clockworksms/index.php

@@ -1,3 +1 @@
 <?php
-
-?>

+ 6 - 3
plugin/clockworksms/install.php

@@ -1,12 +1,15 @@
 <?php
+/* For licensing terms, see /vendor/license.txt */
+
 /**
  * This script is included by main/admin/settings.lib.php and generally
  * includes things to execute in the main database (settings_current table)
- * @package chamilo.plugin.bigbluebutton
+ *
+ * @package chamilo.plugin.clockworksms
+ * @author  Imanol Losada <imanol.losada@beeznest.com>
  */
 /**
  * Initialization
  */
-
 require_once dirname(__FILE__).'/config.php';
-ClockworksmsPlugin::create()->install();
+ClockworksmsPlugin::create()->install();

+ 87 - 87
plugin/clockworksms/lang/english.php

@@ -8,95 +8,95 @@ $strings['api_key_help'] = "This is the Clockwork SMS server security key. <a ta
 
 $strings['tool_enable'] = "Enable SMS sending";
 $strings['tool_enable_help'] = "Choose if you want to enable SMS sending tool.
-	Once enabled, they will be sent along with an email the selected SMS message types to the users who had filled their mobile phone number field in their profile<br />";
+    Once enabled, they will be sent along with an email the selected SMS message types to the users who had filled their mobile phone number field in their profile<br />";
 
 $strings['type'] = "Send SMS when";
 $strings['mobile_phone_number'] = "Mobile Phone (include country dialing code only)";
 
-$strings['MessageWelcomeXLoginXPasswordX'] 								= "A user is added to the platform";
-$strings['MessageXNewFileSharedCourseXByX'] 							= "A file is added to dropbox";
-$strings['MessageXAccountApprovedConnectX'] 							= "An account is approved";
-$strings['MessageXNewCourseXBeenCreatedX'] 								= "A new course is created";
-$strings['MessageXNewUserXSubscribedCourseX'] 							= "A user is subscribed to a course";
-$strings['MessageXNewCourseSuggestedTeacherX'] 							= "A new course is suggested";
-$strings['MessageXCourseOpeningRequestCodeXRegistered'] 				= "A new course opening request is registered";
-$strings['MessageXCourseOpeningRequestCourseCodeXApproved'] 			= "A new course opening request is approved";
-$strings['MessageXRequestOpenCourseCodeXReject'] 						= "A new course opening request is rejected";
-$strings['MessageXCourseOpeningRequestCourseCodeX'] 					= "Additional information is required for a new course opening request";
-$strings['MessageXBeenSubscribedCourseX'] 								= "A user is added to the course but not registered to it yet";
-$strings['MessageXAssignmentBeenCreatedCourseX'] 						= "Homework is created";
-$strings['MessageXAccountCreatedUpdatedLoginXPasswordX'] 				= "A user account is created or updated";
-$strings['MessageXPasswordUpdatedLoginXPasswordX'] 						= "A user password is updated";
-$strings['MessageXRequestedPasswordChange'] 							= "A user requests a password change";
-$strings['MessageXReceivedNewPersonalMessages'] 						= "New personal messages are received in user's inbox or forum";
-$strings['MessageXNewUserXPendingApproval'] 							= "A new user registration is pending for approval";
-$strings['MessageXXPostedForumXCourseX'] 								= "A user posts in forum";
-$strings['MessageXXXCheckEmailConnectMoreInfo'] 						= "An announcement is sent";
-$strings['MessageXXStudentXAnsweredTestX'] 								= "A student solves an exercise";
-$strings['MessageXXStudentXAnsweredTestXOpenQuestion'] 					= "A student solves an open question";
-$strings['MessageXXStudentXAnsweredTestXVoiceQuestion'] 				= "A student solves a voice question";
-$strings['MessageXXAnswerOpenQuestionTestXReviewed'] 					= "An open question answer is reviewed";
-$strings['MessageXXNewThreadXStartedForumX'] 							= "A new thread is started in forum";
-$strings['MessageXXNewAnswerPostedXForumX'] 							= "A new answer is posted in forum";
-$strings['MessageXXNewSystemAnnouncementAdded']							= "A new system announcement is added and the user does not want to send a test email";
-$strings['MessageXTestXNewSystemAnnouncementAdded'] 					= "A new system announcement is added and the user wants to send a test email";
-$strings['MessageXXSystemAnnouncementUpdate'] 							= "A new system announcement is updated and the user does not want to send a test email";
-$strings['MessageXTestXSystemAnnouncementUpdate'] 						= "A new system announcement is updated and the user wants to send a test email";
-$strings['MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper']	= "An assignment is uploaded and there is no current session (this will be sent only to coaches)";
-$strings['MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper'] 	= "An assignment is uploaded (this will be sent only to teachers)";
-$strings['MessageXUserXUploadedAssignmentXCourseX'] 					= "... and there is no current session (this will be sent only to coaches)";
-$strings['MessageXUserXUploadedAssignmentXCheckX'] 						= "... (this will be sent only to teachers)";
-$strings['MessageXSubscribedSessionX'] 									= "A session is created or updated and new users are subscribed";
-$strings['MessageXSubscribedSessionXCSV'] 								= "New users are subscribed to a session importing a CSV file";
-$strings['MessageXUserXSuggestedBeFriends'] 							= "A friendship invitation is received";
-$strings['MessageXUserXAnsweredInboxMessage'] 							= "A message reply is received in inbox";
-$strings['MessageXBeenInvitedJoinGroupX'] 								= "A group join invitation is received";
-$strings['MessageXMessagesSentEditedGroupXEdited'] 						= "A group topic message is updated";
-$strings['MessageXMessagesSentEditedGroupXAdded'] 						= "A group topic message is added";
-$strings['MessageXBeenInvitedCompleteSurveyXCourseX'] 					= "A new survey is created";
-$strings['MessageXReminderAssignmentXCourseXDue'] 						= "A reminder is sent to students who have not uploaded their assignment yet";
-$strings['MessageXUserDetailsModified'] 								= "User details have been updated";
+$strings['MessageWelcomeXLoginXPasswordX']                              = "A user is added to the platform";
+$strings['MessageXNewFileSharedCourseXByX']                             = "A file is added to dropbox";
+$strings['MessageXAccountApprovedConnectX']                             = "An account is approved";
+$strings['MessageXNewCourseXBeenCreatedX']                              = "A new course is created";
+$strings['MessageXNewUserXSubscribedCourseX']                           = "A user is subscribed to a course";
+$strings['MessageXNewCourseSuggestedTeacherX']                          = "A new course is suggested";
+$strings['MessageXCourseOpeningRequestCodeXRegistered']                 = "A new course opening request is registered";
+$strings['MessageXCourseOpeningRequestCourseCodeXApproved']             = "A new course opening request is approved";
+$strings['MessageXRequestOpenCourseCodeXReject']                        = "A new course opening request is rejected";
+$strings['MessageXCourseOpeningRequestCourseCodeX']                     = "Additional information is required for a new course opening request";
+$strings['MessageXBeenSubscribedCourseX']                               = "A user is added to the course but not registered to it yet";
+$strings['MessageXAssignmentBeenCreatedCourseX']                        = "Homework is created";
+$strings['MessageXAccountCreatedUpdatedLoginXPasswordX']                = "A user account is created or updated";
+$strings['MessageXPasswordUpdatedLoginXPasswordX']                      = "A user password is updated";
+$strings['MessageXRequestedPasswordChange']                             = "A user requests a password change";
+$strings['MessageXReceivedNewPersonalMessages']                         = "New personal messages are received in user's inbox or forum";
+$strings['MessageXNewUserXPendingApproval']                             = "A new user registration is pending for approval";
+$strings['MessageXXPostedForumXCourseX']                                = "A user posts in forum";
+$strings['MessageXXXCheckEmailConnectMoreInfo']                         = "An announcement is sent";
+$strings['MessageXXStudentXAnsweredTestX']                              = "A student solves an exercise";
+$strings['MessageXXStudentXAnsweredTestXOpenQuestion']                  = "A student solves an open question";
+$strings['MessageXXStudentXAnsweredTestXVoiceQuestion']                 = "A student solves a voice question";
+$strings['MessageXXAnswerOpenQuestionTestXReviewed']                    = "An open question answer is reviewed";
+$strings['MessageXXNewThreadXStartedForumX']                            = "A new thread is started in forum";
+$strings['MessageXXNewAnswerPostedXForumX']                             = "A new answer is posted in forum";
+$strings['MessageXXNewSystemAnnouncementAdded']                         = "A new system announcement is added and the user does not want to send a test email";
+$strings['MessageXTestXNewSystemAnnouncementAdded']                     = "A new system announcement is added and the user wants to send a test email";
+$strings['MessageXXSystemAnnouncementUpdate']                           = "A new system announcement is updated and the user does not want to send a test email";
+$strings['MessageXTestXSystemAnnouncementUpdate']                       = "A new system announcement is updated and the user wants to send a test email";
+$strings['MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper']  = "An assignment is uploaded and there is no current session (this will be sent only to coaches)";
+$strings['MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper']   = "An assignment is uploaded (this will be sent only to teachers)";
+$strings['MessageXUserXUploadedAssignmentXCourseX']                     = "... and there is no current session (this will be sent only to coaches)";
+$strings['MessageXUserXUploadedAssignmentXCheckX']                      = "... (this will be sent only to teachers)";
+$strings['MessageXSubscribedSessionX']                                  = "A session is created or updated and new users are subscribed";
+$strings['MessageXSubscribedSessionXCSV']                               = "New users are subscribed to a session importing a CSV file";
+$strings['MessageXUserXSuggestedBeFriends']                             = "A friendship invitation is received";
+$strings['MessageXUserXAnsweredInboxMessage']                           = "A message reply is received in inbox";
+$strings['MessageXBeenInvitedJoinGroupX']                               = "A group join invitation is received";
+$strings['MessageXMessagesSentEditedGroupXEdited']                      = "A group topic message is updated";
+$strings['MessageXMessagesSentEditedGroupXAdded']                       = "A group topic message is added";
+$strings['MessageXBeenInvitedCompleteSurveyXCourseX']                   = "A new survey is created";
+$strings['MessageXReminderAssignmentXCourseXDue']                       = "A reminder is sent to students who have not uploaded their assignment yet";
+$strings['MessageXUserDetailsModified']                                 = "User details have been updated";
 
-$strings['WelcomeXLoginXPasswordX'] 							= "Welcome to %s. Here are your user account details: login: %s, password: %s";
-$strings['XNewFileSharedCourseXByX'] 							= "%s: A new file has been shared with you in course %s by %s";
-$strings['XAccountApprovedConnectX'] 							= "%s: Your account has been approved by an administrator. You can now connect to %s";
-$strings['XNewCourseXBeenCreatedX'] 							= "%s: A new course (%s) has been created by %s";
-$strings['XNewUserXSubscribedCourseX'] 							= "%s: A new user (%s) has just subscribed to your course (%s)";
-$strings['XNewCourseSuggestedTeacherX'] 						= "%s: A new course has been suggested by teacher (%s). Please connect to the admin page to review it";
-$strings['XCourseOpeningRequestCodeXRegistered'] 				= "%s: Your course opening request (code %s) has been registered. You will be informed when it is approved";
-$strings['XCourseOpeningRequestCourseCodeXApproved'] 			= "%s: Your course opening request for course code %s has been approved. Connect to your portal to use it";
-$strings['XRequestOpenCourseCodeXReject'] 						= "%s: We are sorry to inform you that your request to open course code %s has been rejected";
-$strings['XCourseOpeningRequestCourseCodeX'] 					= "%s: Your course opening request for course code %s requires more information. Check e-mail for more info";
-$strings['XBeenSubscribedCourseX'] 								= "%s: You have been subscribed to course %s";
-$strings['XAssignmentBeenCreatedCourseX'] 						= "%s: A new assignment has been created in course %s. Please connect for more info";
-$strings['XAccountCreatedUpdatedLoginXPasswordX'] 				= "%s: Your account has been created or updated. You can now login as %s, password: %s";
-$strings['XPasswordUpdatedLoginXPasswordX'] 					= "%s: Your password has been updated. You can now login as %s, password: %s";
-$strings['XRequestedPasswordChange'] 							= "%s: You have requested a password change. Please check your e-mail for more information";
-$strings['XReceivedNewPersonalMessages'] 						= "%s: You have received new personal messages in your inbox or in the forum. Please check your e-mail for more info";
-$strings['XNewUserXPendingApproval'] 							= "%s: A new user (%s) registration is pending your approval. Please connect to the admin panel to review";
-$strings['XXPostedForumXCourseX'] 								= "%s: %s just posted on forum %s in course %s";
-$strings['XXXCheckEmailConnectMoreInfo'] 						= "%s: %s: %s. Check your e-mail or connect for more info";
-$strings['XXStudentXAnsweredTestX'] 							= "%s: %s: Student %s has just answered test %s";
-$strings['XXStudentXAnsweredTestXOpenQuestion'] 				= "%s: %s: Student %s answered test %s's open question. Please connect to review";
-$strings['XXStudentXAnsweredTestXVoiceQuestion'] 				= "%s: %s: Student %s answered test %s's voice question. Please connect to review";
-$strings['XXAnswerOpenQuestionTestXReviewed'] 					= "%s: %s: Your answer to an open question in test %s has been reviewed";
-$strings['XXNewThreadXStartedForumX'] 							= "%s: %s: A new thread (%s) has been started in forum %s";
-$strings['XXNewAnswerPostedXForumX'] 							= "%s: %s: A new answer has been posted to (%s) in forum %s";
-$strings['XXNewSystemAnnouncementAdded'] 						= "%s: %s";
-$strings['XTestXNewSystemAnnouncementAdded'] 					= "%s (test): %s";
-$strings['XXSystemAnnouncementUpdate'] 							= "%s: %s (update)";
-$strings['XTestXSystemAnnouncementUpdate'] 						= "%s (test): %s";
-$strings['XUserXUploadedAssignmentXCourseXStudentSubmitsPaper'] = "%s: User %s uploaded assignment %s in course %s";
-$strings['XUserXUploadedAssignmentXCheckXStudentSubmitsPaper'] 	= "%s: User %s uploaded assignment %s. Check %s";
-$strings['XUserXUploadedAssignmentXCourseX'] 					= "%s: User %s uploaded assignment %s in course %s";
-$strings['XUserXUploadedAssignmentXCheckX'] 					= "%s: User %s uploaded assignment %s. Check %s";
-$strings['XSubscribedSessionX'] 								= "%s: You have been subscribed to session %s";
-$strings['XSubscribedSessionXCSV'] 								= "%s: You have been subscribed to session %s";
-$strings['XUserXSuggestedBeFriends'] 							= "%s: User %s suggested you should be friends. Check your inbox or e-mail for details";
-$strings['XUserXAnsweredInboxMessage'] 							= "%s: User %s just answered your Inbox message";
-$strings['XBeenInvitedJoinGroupX'] 								= "%s: you have been invited to join group %s. Check your Inbox for details";
-$strings['XMessagesSentEditedGroupXEdited'] 					= "%s: Messages sent or edited in group %s. Check your Inbox for details";
-$strings['XMessagesSentEditedGroupXAdded'] 						= "%s: Messages sent or edited in group %s. Check your Inbox for details";
-$strings['XBeenInvitedCompleteSurveyXCourseX'] 					= "%s: You have been invited to complete survey %s in course %s";
-$strings['XReminderAssignmentXCourseXDue'] 						= "%s: This is a simple reminder that your assignment (%s) in course %s is still due";
-$strings['XUserDetailsModified'] 								= "%s: Your user details have been modified. Please check your e-mail for more information";
+$strings['WelcomeXLoginXPasswordX']                                     = "Welcome to %s. Here are your user account details: login: %s, password: %s";
+$strings['XNewFileSharedCourseXByX']                                    = "%s: A new file has been shared with you in course %s by %s";
+$strings['XAccountApprovedConnectX']                                    = "%s: Your account has been approved by an administrator. You can now connect to %s";
+$strings['XNewCourseXBeenCreatedX']                                     = "%s: A new course (%s) has been created by %s";
+$strings['XNewUserXSubscribedCourseX']                                  = "%s: A new user (%s) has just subscribed to your course (%s)";
+$strings['XNewCourseSuggestedTeacherX']                                 = "%s: A new course has been suggested by teacher (%s). Please connect to the admin page to review it";
+$strings['XCourseOpeningRequestCodeXRegistered']                        = "%s: Your course opening request (code %s) has been registered. You will be informed when it is approved";
+$strings['XCourseOpeningRequestCourseCodeXApproved']                    = "%s: Your course opening request for course code %s has been approved. Connect to your portal to use it";
+$strings['XRequestOpenCourseCodeXReject']                               = "%s: We are sorry to inform you that your request to open course code %s has been rejected";
+$strings['XCourseOpeningRequestCourseCodeX']                            = "%s: Your course opening request for course code %s requires more information. Check e-mail for more info";
+$strings['XBeenSubscribedCourseX']                                      = "%s: You have been subscribed to course %s";
+$strings['XAssignmentBeenCreatedCourseX']                               = "%s: A new assignment has been created in course %s. Please connect for more info";
+$strings['XAccountCreatedUpdatedLoginXPasswordX']                       = "%s: Your account has been created or updated. You can now login as %s, password: %s";
+$strings['XPasswordUpdatedLoginXPasswordX']                             = "%s: Your password has been updated. You can now login as %s, password: %s";
+$strings['XRequestedPasswordChange']                                    = "%s: You have requested a password change. Please check your e-mail for more information";
+$strings['XReceivedNewPersonalMessages']                                = "%s: You have received new personal messages in your inbox or in the forum. Please check your e-mail for more info";
+$strings['XNewUserXPendingApproval']                                    = "%s: A new user (%s) registration is pending your approval. Please connect to the admin panel to review";
+$strings['XXPostedForumXCourseX']                                       = "%s: %s just posted on forum %s in course %s";
+$strings['XXXCheckEmailConnectMoreInfo']                                = "%s: %s: %s. Check your e-mail or connect for more info";
+$strings['XXStudentXAnsweredTestX']                                     = "%s: %s: Student %s has just answered test %s";
+$strings['XXStudentXAnsweredTestXOpenQuestion']                         = "%s: %s: Student %s answered test %s's open question. Please connect to review";
+$strings['XXStudentXAnsweredTestXVoiceQuestion']                        = "%s: %s: Student %s answered test %s's voice question. Please connect to review";
+$strings['XXAnswerOpenQuestionTestXReviewed']                           = "%s: %s: Your answer to an open question in test %s has been reviewed";
+$strings['XXNewThreadXStartedForumX']                                   = "%s: %s: A new thread (%s) has been started in forum %s";
+$strings['XXNewAnswerPostedXForumX']                                    = "%s: %s: A new answer has been posted to (%s) in forum %s";
+$strings['XXNewSystemAnnouncementAdded']                                = "%s: %s";
+$strings['XTestXNewSystemAnnouncementAdded']                            = "%s (test): %s";
+$strings['XXSystemAnnouncementUpdate']                                  = "%s: %s (update)";
+$strings['XTestXSystemAnnouncementUpdate']                              = "%s (test): %s";
+$strings['XUserXUploadedAssignmentXCourseXStudentSubmitsPaper']         = "%s: User %s uploaded assignment %s in course %s";
+$strings['XUserXUploadedAssignmentXCheckXStudentSubmitsPaper']          = "%s: User %s uploaded assignment %s. Check %s";
+$strings['XUserXUploadedAssignmentXCourseX']                            = "%s: User %s uploaded assignment %s in course %s";
+$strings['XUserXUploadedAssignmentXCheckX']                             = "%s: User %s uploaded assignment %s. Check %s";
+$strings['XSubscribedSessionX']                                         = "%s: You have been subscribed to session %s";
+$strings['XSubscribedSessionXCSV']                                      = "%s: You have been subscribed to session %s";
+$strings['XUserXSuggestedBeFriends']                                    = "%s: User %s suggested you should be friends. Check your inbox or e-mail for details";
+$strings['XUserXAnsweredInboxMessage']                                  = "%s: User %s just answered your Inbox message";
+$strings['XBeenInvitedJoinGroupX']                                      = "%s: you have been invited to join group %s. Check your Inbox for details";
+$strings['XMessagesSentEditedGroupXEdited']                             = "%s: Messages sent or edited in group %s. Check your Inbox for details";
+$strings['XMessagesSentEditedGroupXAdded']                              = "%s: Messages sent or edited in group %s. Check your Inbox for details";
+$strings['XBeenInvitedCompleteSurveyXCourseX']                          = "%s: You have been invited to complete survey %s in course %s";
+$strings['XReminderAssignmentXCourseXDue']                              = "%s: This is a simple reminder that your assignment (%s) in course %s is still due";
+$strings['XUserDetailsModified']                                        = "%s: Your user details have been modified. Please check your e-mail for more information";

+ 87 - 87
plugin/clockworksms/lang/spanish.php

@@ -1,4 +1,4 @@
-<?php 
+<?php
 
 $strings['plugin_title']        = "Envío de SMS";
 $strings['plugin_comment']      = "Ofrece la posibilidad de enviar SMS a celulares cuando se envían e-mails de notificación.";
@@ -13,90 +13,90 @@ $strings['tool_enable_help'] = "Escoja si desea activar la herramienta de envío
 $strings['sms_types'] = "Enviar un SMS cuando";
 $strings['mobile_phone_number'] = "Celular (incluya sólo el código de llamada del país)";
 
-$strings['MessageWelcomeXLoginXPasswordX'] 								= "Se añada un usuario a la plataforma";
-$strings['MessageXNewFileSharedCourseXByX'] 							= "Un archivo se añada a dropbox";
-$strings['MessageXAccountApprovedConnectX'] 							= "Se apruebe una cuenta de usuario";
-$strings['MessageXNewCourseXBeenCreatedX'] 								= "Se cree un curso nuevo";
-$strings['MessageXNewUserXSubscribedCourseX'] 							= "Un usuario se suscriba a un curso";
-$strings['MessageXNewCourseSuggestedTeacherX'] 							= "Un profesor sugiera un curso nuevo";
-$strings['MessageXCourseOpeningRequestCodeXRegistered'] 				= "Se registre una solicitud de apertura de curso";
-$strings['MessageXCourseOpeningRequestCourseCodeXApproved'] 			= "Se apruebe una solicitud de apertura de curso";
-$strings['MessageXRequestOpenCourseCodeXReject'] 						= "Se rechace una solicitud de apertura de curso";
-$strings['MessageXCourseOpeningRequestCourseCodeX'] 					= "Se requiera más información de una solicitud de apertura de curso";
-$strings['MessageXBeenSubscribedCourseX'] 								= "Se le suscriba a un curso a un usuario que aún no está registrado";
-$strings['MessageXAssignmentBeenCreatedCourseX'] 						= "Se cree una nueva tarea en un curso";
-$strings['MessageXAccountCreatedUpdatedLoginXPasswordX'] 				= "Se cree o actualice una cuenta de usuario";
-$strings['MessageXPasswordUpdatedLoginXPasswordX'] 						= "Se actualice la contraseña de un usuario";
-$strings['MessageXRequestedPasswordChange'] 							= "Un usuario solicite un cambio de contraseña";
-$strings['MessageXReceivedNewPersonalMessages'] 						= "Se reciban mensajes personales nuevos en la bandeja de entrada o en el foro";
-$strings['MessageXNewUserXPendingApproval'] 							= "Una inscripción de un nuevo usuario esté pendiente de aprobación";
-$strings['MessageXXPostedForumXCourseX'] 								= "Un usuario escriba en el foro";
-$strings['MessageXXXCheckEmailConnectMoreInfo'] 						= "Se envíe una notificación";
-$strings['MessageXXStudentXAnsweredTestX'] 								= "Un estudiante resuelva un ejercicio de un examen";
-$strings['MessageXXStudentXAnsweredTestXOpenQuestion'] 					= "Un estudiante conteste a una pregunta abierta de un examen";
-$strings['MessageXXStudentXAnsweredTestXVoiceQuestion'] 				= "Un estudiante conteste a una pregunta de voz de un examen";
-$strings['MessageXXAnswerOpenQuestionTestXReviewed'] 					= "Se revise una pregunta abierta de un examen";
-$strings['MessageXXNewThreadXStartedForumX'] 							= "Se cree un hilo nuevo en el foro";
-$strings['MessageXXNewAnswerPostedXForumX'] 							= "Se escriba una respuesta nueva en el foro";
-$strings['MessageXXNewSystemAnnouncementAdded']							= "Se añada una notificación y el usuario no desee enviar un examen por correo electrónico";
-$strings['MessageXTestXNewSystemAnnouncementAdded'] 					= "Se añada una notificación y el usuario desee enviar un examen por correo electrónico";
-$strings['MessageXXSystemAnnouncementUpdate'] 							= "Se actualice una notificación y el usuario no desee enviar un examen por correo electrónico";
-$strings['MessageXTestXSystemAnnouncementUpdate'] 						= "Se actualice una notificación y el usuario desee enviar un examen por correo electrónico";
-$strings['MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper']	= "Un estudiante suba su tarea y no exista una sesión (se enviará sólo a coordinadores)";
-$strings['MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper'] 	= "Un estudiante suba su tarea (se enviará sólo a profesores)";
-$strings['MessageXUserXUploadedAssignmentXCourseX'] 					= "... y no exista una sesión (se enviará sólo a coordinadores)";
-$strings['MessageXUserXUploadedAssignmentXCheckX'] 						= "... (se enviará sólo a profesores)";
-$strings['MessageXSubscribedSessionX'] 									= "Se cree o edite una sesión nueva y se suscriban a usuarios nuevos";
-$strings['MessageXSubscribedSessionXCSV'] 								= "Se suscriban a usuarios nuevos desde un archivo CSV";
-$strings['MessageXUserXSuggestedBeFriends'] 							= "Se reciba una invitación de amistad";
-$strings['MessageXUserXAnsweredInboxMessage'] 							= "Se reciba la contestación a un mensaje en la bandeja de entrada";
-$strings['MessageXBeenInvitedJoinGroupX'] 								= "Se reciba una invitación para unirse a un grupo";
-$strings['MessageXMessagesSentEditedGroupXEdited'] 						= "Se actualice un mensaje en un tema de grupo";
-$strings['MessageXMessagesSentEditedGroupXAdded'] 						= "Se añada un mensaje en un tema de grupo";
-$strings['MessageXBeenInvitedCompleteSurveyXCourseX'] 					= "Se cree una encuesta nueva";
-$strings['MessageXReminderAssignmentXCourseXDue'] 						= "Se envíe un recordatorio a los estudiantes que no hayan enviado su tarea";
-$strings['MessageXUserDetailsModified'] 								= "Se actualice información de un usuario";
+$strings['MessageWelcomeXLoginXPasswordX']                              = "Se añada un usuario a la plataforma";
+$strings['MessageXNewFileSharedCourseXByX']                             = "Un archivo se añada a dropbox";
+$strings['MessageXAccountApprovedConnectX']                             = "Se apruebe una cuenta de usuario";
+$strings['MessageXNewCourseXBeenCreatedX']                              = "Se cree un curso nuevo";
+$strings['MessageXNewUserXSubscribedCourseX']                           = "Un usuario se suscriba a un curso";
+$strings['MessageXNewCourseSuggestedTeacherX']                          = "Un profesor sugiera un curso nuevo";
+$strings['MessageXCourseOpeningRequestCodeXRegistered']                 = "Se registre una solicitud de apertura de curso";
+$strings['MessageXCourseOpeningRequestCourseCodeXApproved']             = "Se apruebe una solicitud de apertura de curso";
+$strings['MessageXRequestOpenCourseCodeXReject']                        = "Se rechace una solicitud de apertura de curso";
+$strings['MessageXCourseOpeningRequestCourseCodeX']                     = "Se requiera más información de una solicitud de apertura de curso";
+$strings['MessageXBeenSubscribedCourseX']                               = "Se le suscriba a un curso a un usuario que aún no está registrado";
+$strings['MessageXAssignmentBeenCreatedCourseX']                        = "Se cree una nueva tarea en un curso";
+$strings['MessageXAccountCreatedUpdatedLoginXPasswordX']                = "Se cree o actualice una cuenta de usuario";
+$strings['MessageXPasswordUpdatedLoginXPasswordX']                      = "Se actualice la contraseña de un usuario";
+$strings['MessageXRequestedPasswordChange']                             = "Un usuario solicite un cambio de contraseña";
+$strings['MessageXReceivedNewPersonalMessages']                         = "Se reciban mensajes personales nuevos en la bandeja de entrada o en el foro";
+$strings['MessageXNewUserXPendingApproval']                             = "Una inscripción de un nuevo usuario esté pendiente de aprobación";
+$strings['MessageXXPostedForumXCourseX']                                = "Un usuario escriba en el foro";
+$strings['MessageXXXCheckEmailConnectMoreInfo']                         = "Se envíe una notificación";
+$strings['MessageXXStudentXAnsweredTestX']                              = "Un estudiante resuelva un ejercicio de un examen";
+$strings['MessageXXStudentXAnsweredTestXOpenQuestion']                  = "Un estudiante conteste a una pregunta abierta de un examen";
+$strings['MessageXXStudentXAnsweredTestXVoiceQuestion']                 = "Un estudiante conteste a una pregunta de voz de un examen";
+$strings['MessageXXAnswerOpenQuestionTestXReviewed']                    = "Se revise una pregunta abierta de un examen";
+$strings['MessageXXNewThreadXStartedForumX']                            = "Se cree un hilo nuevo en el foro";
+$strings['MessageXXNewAnswerPostedXForumX']                             = "Se escriba una respuesta nueva en el foro";
+$strings['MessageXXNewSystemAnnouncementAdded']                         = "Se añada una notificación y el usuario no desee enviar un examen por correo electrónico";
+$strings['MessageXTestXNewSystemAnnouncementAdded']                     = "Se añada una notificación y el usuario desee enviar un examen por correo electrónico";
+$strings['MessageXXSystemAnnouncementUpdate']                           = "Se actualice una notificación y el usuario no desee enviar un examen por correo electrónico";
+$strings['MessageXTestXSystemAnnouncementUpdate']                       = "Se actualice una notificación y el usuario desee enviar un examen por correo electrónico";
+$strings['MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper']  = "Un estudiante suba su tarea y no exista una sesión (se enviará sólo a coordinadores)";
+$strings['MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper']   = "Un estudiante suba su tarea (se enviará sólo a profesores)";
+$strings['MessageXUserXUploadedAssignmentXCourseX']                     = "... y no exista una sesión (se enviará sólo a coordinadores)";
+$strings['MessageXUserXUploadedAssignmentXCheckX']                      = "... (se enviará sólo a profesores)";
+$strings['MessageXSubscribedSessionX']                                  = "Se cree o edite una sesión nueva y se suscriban a usuarios nuevos";
+$strings['MessageXSubscribedSessionXCSV']                               = "Se suscriban a usuarios nuevos desde un archivo CSV";
+$strings['MessageXUserXSuggestedBeFriends']                             = "Se reciba una invitación de amistad";
+$strings['MessageXUserXAnsweredInboxMessage']                           = "Se reciba la contestación a un mensaje en la bandeja de entrada";
+$strings['MessageXBeenInvitedJoinGroupX']                               = "Se reciba una invitación para unirse a un grupo";
+$strings['MessageXMessagesSentEditedGroupXEdited']                      = "Se actualice un mensaje en un tema de grupo";
+$strings['MessageXMessagesSentEditedGroupXAdded']                       = "Se añada un mensaje en un tema de grupo";
+$strings['MessageXBeenInvitedCompleteSurveyXCourseX']                   = "Se cree una encuesta nueva";
+$strings['MessageXReminderAssignmentXCourseXDue']                       = "Se envíe un recordatorio a los estudiantes que no hayan enviado su tarea";
+$strings['MessageXUserDetailsModified']                                 = "Se actualice información de un usuario";
 
-$strings['WelcomeXLoginXPasswordX'] 							= "Bienvenido a %s. Éstos son sus datos de acceso: usuario: %s, contraseña: %s";
-$strings['XNewFileSharedCourseXByX'] 							= "%s: Un nuevo archivo ha sido compartido contigo en el curso %s por %s";
-$strings['XAccountApprovedConnectX'] 							= "%s: Su cuenta ha sido aprobada por un administrador. Ya puede conectarse a %s";
-$strings['XNewCourseXBeenCreatedX'] 							= "%s: Un nuevo curso (%s) ha sido creado por %s";
-$strings['XNewUserXSubscribedCourseX'] 							= "%s: Un nuevo usuario (%s) se ha suscrito a su curso (%s)";
-$strings['XNewCourseSuggestedTeacherX'] 						= "%s: Un nuevo curso ha sido sugerido por el profesor (%s). Por favor, conéctese a la página de administración para revisarlo";
-$strings['XCourseOpeningRequestCodeXRegistered'] 				= "%s: Su solicitud de apertura de curso (código %s) ha sido registrada. Será informado cuando ésta sea aprobada";
-$strings['XCourseOpeningRequestCourseCodeXApproved'] 			= "%s: Su solicitud de apertura de curso para el código de curso %s ha sido aprobada. Conéctese a su portal para usarlo";
-$strings['XRequestOpenCourseCodeXReject'] 						= "%s: Lamentamos informarle que su solicitud de apertura de curso para el código de curso %s ha sido rechazada";
-$strings['XCourseOpeningRequestCourseCodeX'] 					= "%s: Su solicitud de apertura de curso para el código de curso %s requiere más información. Compruebe su e-mail para más información";
-$strings['XBeenSubscribedCourseX'] 								= "%s: Ha sido suscrito al curso %s";
-$strings['XAssignmentBeenCreatedCourseX'] 						= "%s: Una nueva tarea ha sido creada en el curso %s. Por favor, conéctese para más información";
-$strings['XAccountCreatedUpdatedLoginXPasswordX'] 				= "%s: Su cuenta ha sido creada o actualizada. Ya puede conectarse como %s, contraseña: %s";
-$strings['XPasswordUpdatedLoginXPasswordX'] 					= "%s: Su contraseña ha sido actualizada. Ya puede conectarse como %s, contraseña: %s";
-$strings['XRequestedPasswordChange'] 							= "%s: Ha solicitado un cambio de contraseña. Por favor, compruebe su e-mail para más información";
-$strings['XReceivedNewPersonalMessages'] 						= "%s: Ha recibido mensajes personales nuevos en su bandeja de entrada o en el foro. Por favor, compruebe su e-mail para más información";
-$strings['XNewUserXPendingApproval'] 							= "%s: Una inscripción de un nuevo usuario (%s) está pendiente de su aprobación. Por favor, conéctese al panel de administración para revisarla";
-$strings['XXPostedForumXCourseX'] 								= "%s: %s acaba de escribir en el foro %s del curso %s";
-$strings['XXXCheckEmailConnectMoreInfo'] 						= "%s: %s: %s. Compruebe su e-mail o conéctese para más información";
-$strings['XXStudentXAnsweredTestX'] 							= "%s: %s: El estudiante %s acaba de contestar al test %s";
-$strings['XXStudentXAnsweredTestXOpenQuestion'] 				= "%s: %s: El estudiante %s contestó a la pregunta abierta del test %s. Por favor, conéctese para revisarla";
-$strings['XXStudentXAnsweredTestXVoiceQuestion'] 				= "%s: %s: El estudiante %s contestó a la pregunta de voz del test %s. Por favor, conéctese para revisarla";
-$strings['XXAnswerOpenQuestionTestXReviewed'] 					= "%s: %s: Su respuesta a la pregunta abierta en el test %s ha sido revisada.";
-$strings['XXNewThreadXStartedForumX'] 							= "%s: %s: Se ha comenzado un nuevo hilo (%s) en el foro %s";
-$strings['XXNewAnswerPostedXForumX'] 							= "%s: %s: Se ha escrito una nueva respuesta a (%s) en el foro %s";
-$strings['XXNewSystemAnnouncementAdded']						= "%s: %s";
-$strings['XTestXNewSystemAnnouncementAdded'] 					= "%s (prueba): %s";
-$strings['XXSystemAnnouncementUpdate'] 							= "%s: %s (actualización)";
-$strings['XTestXSystemAnnouncementUpdate'] 						= "%s (prueba): %s";
-$strings['XUserXUploadedAssignmentXCourseXStudentSubmitsPaper']	= "%s: El usuario %s subió la tarea %s al curso %s";
-$strings['XUserXUploadedAssignmentXCheckXStudentSubmitsPaper'] 	= "%s: El usuario %s subió la tarea %s. Compruébelo en %s";
-$strings['XUserXUploadedAssignmentXCourseX'] 					= "%s: El usuario %s subió la tarea %s al curso %s";
-$strings['XUserXUploadedAssignmentXCheckX'] 					= "%s: El usuario %s subió la tarea %s. Compruébelo en %s";
-$strings['XSubscribedSessionX'] 								= "%s: Ha sido suscrito a la sesión %s";
-$strings['XSubscribedSessionXCSV'] 								= "%s: Ha sido suscrito a la sesión %s";
-$strings['XUserXSuggestedBeFriends'] 							= "%s: El usuario %s le sugirió que podrían ser amigos. Compruebe su bandeja de entrada o su e-mail para más detalles";
-$strings['XUserXAnsweredInboxMessage'] 							= "%s: El usuario acaba de contestar a su mensaje de la bandeja de entrada";
-$strings['XBeenInvitedJoinGroupX'] 								= "%s: Ha sido invitado a unirse al grupo %s. Compruebe su bandeja de entrada para más detalles";
-$strings['XMessagesSentEditedGroupXEdited'] 					= "%s: Hay mensajes enviados o editados en el grupo %s. Compruebe su bandeja de entrada para más detalles";
-$strings['XMessagesSentEditedGroupXAdded'] 						= "%s: Hay mensajes enviados o editados en el grupo %s. Compruebe su bandeja de entrada para más detalles";
-$strings['XBeenInvitedCompleteSurveyXCourseX'] 					= "%s: Ha sido invitado a completar la encuesta %s del curso %s";
-$strings['XReminderAssignmentXCourseXDue'] 						= "%s: Se le recuerda que su tarea (%s) del curso %s aún está pendiente";
-$strings['XUserDetailsModified'] 								= "%s: Su información de usuario ha sido modificada. Compruebe su e-mail para más información";
+$strings['WelcomeXLoginXPasswordX']                                     = "Bienvenido a %s. Éstos son sus datos de acceso: usuario: %s, contraseña: %s";
+$strings['XNewFileSharedCourseXByX']                                    = "%s: Un nuevo archivo ha sido compartido contigo en el curso %s por %s";
+$strings['XAccountApprovedConnectX']                                    = "%s: Su cuenta ha sido aprobada por un administrador. Ya puede conectarse a %s";
+$strings['XNewCourseXBeenCreatedX']                                     = "%s: Un nuevo curso (%s) ha sido creado por %s";
+$strings['XNewUserXSubscribedCourseX']                                  = "%s: Un nuevo usuario (%s) se ha suscrito a su curso (%s)";
+$strings['XNewCourseSuggestedTeacherX']                                 = "%s: Un nuevo curso ha sido sugerido por el profesor (%s). Por favor, conéctese a la página de administración para revisarlo";
+$strings['XCourseOpeningRequestCodeXRegistered']                        = "%s: Su solicitud de apertura de curso (código %s) ha sido registrada. Será informado cuando ésta sea aprobada";
+$strings['XCourseOpeningRequestCourseCodeXApproved']                    = "%s: Su solicitud de apertura de curso para el código de curso %s ha sido aprobada. Conéctese a su portal para usarlo";
+$strings['XRequestOpenCourseCodeXReject']                               = "%s: Lamentamos informarle que su solicitud de apertura de curso para el código de curso %s ha sido rechazada";
+$strings['XCourseOpeningRequestCourseCodeX']                            = "%s: Su solicitud de apertura de curso para el código de curso %s requiere más información. Compruebe su e-mail para más información";
+$strings['XBeenSubscribedCourseX']                                      = "%s: Ha sido suscrito al curso %s";
+$strings['XAssignmentBeenCreatedCourseX']                               = "%s: Una nueva tarea ha sido creada en el curso %s. Por favor, conéctese para más información";
+$strings['XAccountCreatedUpdatedLoginXPasswordX']                       = "%s: Su cuenta ha sido creada o actualizada. Ya puede conectarse como %s, contraseña: %s";
+$strings['XPasswordUpdatedLoginXPasswordX']                             = "%s: Su contraseña ha sido actualizada. Ya puede conectarse como %s, contraseña: %s";
+$strings['XRequestedPasswordChange']                                    = "%s: Ha solicitado un cambio de contraseña. Por favor, compruebe su e-mail para más información";
+$strings['XReceivedNewPersonalMessages']                                = "%s: Ha recibido mensajes personales nuevos en su bandeja de entrada o en el foro. Por favor, compruebe su e-mail para más información";
+$strings['XNewUserXPendingApproval']                                    = "%s: Una inscripción de un nuevo usuario (%s) está pendiente de su aprobación. Por favor, conéctese al panel de administración para revisarla";
+$strings['XXPostedForumXCourseX']                                       = "%s: %s acaba de escribir en el foro %s del curso %s";
+$strings['XXXCheckEmailConnectMoreInfo']                                = "%s: %s: %s. Compruebe su e-mail o conéctese para más información";
+$strings['XXStudentXAnsweredTestX']                                     = "%s: %s: El estudiante %s acaba de contestar al test %s";
+$strings['XXStudentXAnsweredTestXOpenQuestion']                         = "%s: %s: El estudiante %s contestó a la pregunta abierta del test %s. Por favor, conéctese para revisarla";
+$strings['XXStudentXAnsweredTestXVoiceQuestion']                        = "%s: %s: El estudiante %s contestó a la pregunta de voz del test %s. Por favor, conéctese para revisarla";
+$strings['XXAnswerOpenQuestionTestXReviewed']                           = "%s: %s: Su respuesta a la pregunta abierta en el test %s ha sido revisada.";
+$strings['XXNewThreadXStartedForumX']                                   = "%s: %s: Se ha comenzado un nuevo hilo (%s) en el foro %s";
+$strings['XXNewAnswerPostedXForumX']                                    = "%s: %s: Se ha escrito una nueva respuesta a (%s) en el foro %s";
+$strings['XXNewSystemAnnouncementAdded']                                = "%s: %s";
+$strings['XTestXNewSystemAnnouncementAdded']                            = "%s (prueba): %s";
+$strings['XXSystemAnnouncementUpdate']                                  = "%s: %s (actualización)";
+$strings['XTestXSystemAnnouncementUpdate']                              = "%s (prueba): %s";
+$strings['XUserXUploadedAssignmentXCourseXStudentSubmitsPaper']         = "%s: El usuario %s subió la tarea %s al curso %s";
+$strings['XUserXUploadedAssignmentXCheckXStudentSubmitsPaper']          = "%s: El usuario %s subió la tarea %s. Compruébelo en %s";
+$strings['XUserXUploadedAssignmentXCourseX']                            = "%s: El usuario %s subió la tarea %s al curso %s";
+$strings['XUserXUploadedAssignmentXCheckX']                             = "%s: El usuario %s subió la tarea %s. Compruébelo en %s";
+$strings['XSubscribedSessionX']                                         = "%s: Ha sido suscrito a la sesión %s";
+$strings['XSubscribedSessionXCSV']                                      = "%s: Ha sido suscrito a la sesión %s";
+$strings['XUserXSuggestedBeFriends']                                    = "%s: El usuario %s le sugirió que podrían ser amigos. Compruebe su bandeja de entrada o su e-mail para más detalles";
+$strings['XUserXAnsweredInboxMessage']                                  = "%s: El usuario acaba de contestar a su mensaje de la bandeja de entrada";
+$strings['XBeenInvitedJoinGroupX']                                      = "%s: Ha sido invitado a unirse al grupo %s. Compruebe su bandeja de entrada para más detalles";
+$strings['XMessagesSentEditedGroupXEdited']                             = "%s: Hay mensajes enviados o editados en el grupo %s. Compruebe su bandeja de entrada para más detalles";
+$strings['XMessagesSentEditedGroupXAdded']                              = "%s: Hay mensajes enviados o editados en el grupo %s. Compruebe su bandeja de entrada para más detalles";
+$strings['XBeenInvitedCompleteSurveyXCourseX']                          = "%s: Ha sido invitado a completar la encuesta %s del curso %s";
+$strings['XReminderAssignmentXCourseXDue']                              = "%s: Se le recuerda que su tarea (%s) del curso %s aún está pendiente";
+$strings['XUserDetailsModified']                                        = "%s: Su información de usuario ha sido modificada. Compruebe su e-mail para más información";

+ 49 - 13
plugin/clockworksms/lib/clockworksms.lib.php

@@ -1,11 +1,12 @@
 <?php
-/* For licensing terms, see /license.txt */
+/* For licensing terms, see /vendor/license.txt */
 
 /**
- * Class clockworksms
- * This script initiates a video conference session, calling the Clockworksms
- * API
- * @package chamilo.plugin.clockworksms
+ * Class Clockworksms
+ * This script handles incoming SMS information, process it and sends an SMS if everything is right
+ * 
+ * @package chamilo.plugin.clockworksms.lib
+ * @author  Imanol Losada <imanol.losada@beeznest.com>
  *
  * Clockworksms-Chamilo connector class
  */
@@ -18,20 +19,21 @@ class Clockworksms
 
     /**
      * Constructor (generates a connection to the API)
-     * @param string $apiKey
+     * @param   string  Clockworksms API key required to use the plugin
+     * @return  void
      */
     public function __construct($apiKey = null)
     {
         $plugin = ClockworksmsPlugin::create();
-        $clockworksms_plugin = $plugin->get('tool_enable');
+        $clockWorkSMSPlugin = $plugin->get('tool_enable');
         if (empty($apiKey)) {
-            $clockworksmsApiKey = $plugin->get('api_key');
+            $clockWorkSMSApiKey = $plugin->get('api_key');
         } else {
-            $clockworksmsApiKey = $apiKey;
+            $clockWorkSMSApiKey = $apiKey;
         }
         $this->table = Database::get_main_table('user_field_values');
-        if ($clockworksms_plugin == true) {
-            $this->apiKey = $clockworksmsApiKey;
+        if ($clockWorkSMSPlugin == true) {
+            $this->apiKey = $clockWorkSMSApiKey;
             // Setting Clockworksms api
             define('CONFIG_SECURITY_API_KEY', $this->apiKey);
             $trimmedApiKey = trim(CONFIG_SECURITY_API_KEY);
@@ -57,8 +59,9 @@ class Clockworksms
     }
 
     /**
-     * @param int $userId
-     * @return mixed
+     * getMobilePhoneNumberById (retrieves a user mobile phone number by user id)
+     * @param   int User id
+     * @return  int User's mobile phone number
      */
     private function getMobilePhoneNumberById($userId)
     {
@@ -74,6 +77,18 @@ class Clockworksms
         return $mobilePhoneNumberExtraFieldValue['field_value'];
     }
 
+    /**
+     * send (sends an SMS to the user)
+     * @param   array   Data needed to send the SMS. It is mandatory to include the
+     *                  'smsType' and 'userId' (or 'mobilePhoneNumber') fields at least.
+     *                  More data may be neccesary depending on the message type
+     * Example: $additional_parameters = array(
+     *              'smsType' => EXAMPLE_SMS_TYPE,
+     *              'userId' => $userId,
+     *              'moreData' => $moreData
+     *          );
+     * @return  void
+     */
     public function send($additionalParameters)
     {
         $trimmedKey = trim(CONFIG_SECURITY_API_KEY);
@@ -99,6 +114,15 @@ class Clockworksms
         }
     }
 
+    /**
+     * buildSms (builds an SMS from a template and data)
+     * @param   object  ClockworksmsPlugin object
+     * @param   object  Template object
+     * @param   string  Template file name
+     * @param   string  Text key from lang file
+     * @param   array   Data to fill message variables (if any)
+     * @return  object  Template object with message property updated
+     */
     public function buildSms($plugin, $tpl, $templateName, $messageKey, $parameters = null)
     {
         $result = Database::select(
@@ -124,6 +148,18 @@ class Clockworksms
         return $tpl->params['message'];
     }
 
+    /**
+     * getSms (returns an SMS message depending of its type)
+     * @param   array   Data needed to send the SMS. It is mandatory to include the
+     *                  'smsType' and 'userId' (or 'mobilePhoneNumber') fields at least.
+     *                  More data may be neccesary depending on the message type
+     * Example: $additional_parameters = array(
+     *              'smsType' => EXAMPLE_SMS_TYPE,
+     *              'userId' => $userId,
+     *              'moreData' => $moreData
+     *          );
+     * @return  string  A ready to be sent SMS
+     */
     public function getSms($additionalParameters)
     {
         $plugin = ClockworksmsPlugin::create();

+ 33 - 2
plugin/clockworksms/lib/clockworksms_plugin.class.php

@@ -1,6 +1,12 @@
 <?php
+/* For licensing terms, see /vendor/license.txt */
+
 /**
  * Class ClockworksmsPlugin
+ * This script contains SMS type constants and basic plugin functions
+ * 
+ * @package chamilo.plugin.clockworksms.lib
+ * @author  Imanol Losada <imanol.losada@beeznest.com>
  */
 class ClockworksmsPlugin extends Plugin
 {
@@ -51,12 +57,21 @@ class ClockworksmsPlugin extends Plugin
     public $isCoursePlugin = true;
     public $isMailPlugin = true;
 
-    static function create()
+    /**
+     * create (a singleton function that ensures ClockworksmsPlugin instance is
+     * created only once. If it is already created, it returns the instance)
+     * @return  object  ClockworksmsPlugin instance
+     */
+    public static function create()
     {
         static $result = null;
         return $result ? $result : $result = new self();
     }
 
+    /**
+     * Constructor
+     * @return  void
+     */
     protected function __construct()
     {
         $fields = array('tool_enable' => 'boolean', 'api_key' => 'text');
@@ -67,6 +82,11 @@ class ClockworksmsPlugin extends Plugin
         parent::__construct('0.1', 'Imanol Losada', $fields);
     }
 
+    /**
+     * addMobilePhoneNumberField (adds a mobile phone number field if it is not
+     * already created)
+     * @return  void
+     */
     private function addMobilePhoneNumberField()
     {
         $result = Database::select('mobile_phone_number', 'user_field');
@@ -86,6 +106,10 @@ class ClockworksmsPlugin extends Plugin
         }
     }
 
+    /**
+     * getSmsTypeOptions (returns all SMS types)
+     * @return  array   SMS types
+     */
     private function getSmsTypeOptions()
     {
         return array(
@@ -135,11 +159,18 @@ class ClockworksmsPlugin extends Plugin
         );
     }
 
+    /**
+     * install (installs the plugin)
+     * @return  void
+     */
     public function install()
     {
         $this->addMobilePhoneNumberField();
     }
-
+    /**
+     * install (uninstalls the plugin and removes all plugin's tables and/or rows)
+     * @return  void
+     */
     public function uninstall()
     {
         $tSettings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);

+ 5 - 0
plugin/clockworksms/plugin.php

@@ -1,5 +1,10 @@
 <?php
+/* For licensing terms, see /vendor/license.txt */
 
+/**
+ * @package chamilo.plugin.clockworksms
+ * @author  Imanol Losada <imanol.losada@beeznest.com>
+ */
 require_once dirname(__FILE__).'/config.php';
 
 $plugin_info = ClockworksmsPlugin::create()->get_info();

+ 2 - 252
plugin/clockworksms/readme.txt

@@ -1,253 +1,3 @@
-# Clockwork SMS API Wrapper for PHP
+This plugin enables Chamilo to send SMS messages to Chamilo users when a notification email is sent.
 
-This wrapper lets you interact with Clockwork without the hassle of having to create any XML or make HTTP calls.
-
-## What's Clockwork?
-
-[Clockwork][2] is Mediaburst's SMS API.
-
-### Prerequisites
-
-* A [Clockwork][2] account
-
-## Usage
-
-Require the Clockwork library:
-
-```php
-require 'class-Clockwork.php';
-```
-
-### Sending a message
-
-```php
-$clockwork = new Clockwork( $API_KEY );
-$message = array( 'to' => '441234567891', 'message' => 'This is a test!' );
-$result = $clockwork->send( $message );
-```
-
-### Sending multiple messages
-
-We recommend you use batch sizes of 500 messages or fewer. By limiting the batch size it prevents any timeouts when sending.
-
-```php
-$clockwork = new Clockwork( $API_KEY );
-$messages = array( 
-    array( 'to' => '441234567891', 'message' => 'This is a test!' ),
-    array( 'to' => '441234567892', 'message' => 'This is a test 2!' )
-);
-$results = $clockwork->send( $messages );
-```
-
-### Handling the response
-
-The responses come back as arrays, these contain the unique Clockwork message ID, whether the message worked (`success`), and the original SMS so you can update your database.
-
-    Array
-    (
-        [id] => VE_164732148
-        [success] => 1
-        [sms] => Array
-            (
-                [to] => 441234567891
-                [message] => This is a test!
-            )
-
-    )
-
-If you send multiple SMS messages in a single send, you'll get back an array of results, one per SMS.
-
-The result will look something like this:
-
-    Array
-    (
-        [0] => Array
-            (
-                [id] => VI_143228951
-                [success] => 1
-                [sms] => Array
-                    (
-                        [to] => 441234567891
-                        [message] => This is a test!
-                    )
-
-            )
-
-        [1] => Array
-            (
-                [id] => VI_143228952
-                [success] => 1
-                [sms] => Array
-                    (
-                        [to] => 441234567892
-                        [message] => This is a test 2!
-                    )
-
-            )
-
-    )
-
-If a message fails, the reason for failure will be set in `error_code` and `error_message`.  
-
-For example, if you send to invalid phone number "abc":
-
-    Array
-    (
-        [error_code] => 10
-        [error_message] => Invalid 'To' Parameter
-        [success] => 0
-        [sms] => Array
-            (
-                [to] => abc
-                [message] => This is a test!
-            )
-
-    )
-
-### Checking your balance
-
-Check your available SMS balance:
-
-```php
-$clockwork = new Clockwork( $API_KEY );
-$clockwork->checkBalance();
-```    
-
-This will return:
-
-    Array 
-    (
-        [symbol] => £
-        [balance] => 351.91
-        [code] => GBP
-    )
-    
-### Handling Errors
-
-The Clockwork wrapper will throw a `ClockworkException` if the entire call failed.
-
-```php
-try 
-{
-    $clockwork = new Clockwork( 'invalid_key' );
-    $message = array( 'to' => 'abc', 'message' => 'This is a test!' );
-    $result = $clockwork->send( $message );
-}
-catch( ClockworkException $e )
-{
-    print $e->getMessage();
-    // Invalid API Key
-}
-```    
-
-### Advanced Usage
-
-This class has a few additional features that some users may find useful, if these are not set your account defaults will be used.
-
-### Optional Parameters
-
-See the [Clockwork Documentation](http://www.clockworksms.com/doc/clever-stuff/xml-interface/send-sms/) for full details on these options.
-
-*   $from [string]
-
-    The from address displayed on a phone when they receive a message
-
-*   $long [boolean]  
-
-    Enable long SMS. A standard text can contain 160 characters, a long SMS supports up to 459.
-
-*   $truncate [nullable boolean]  
-
-    Truncate the message payload if it is too long, if this is set to false, the message will fail if it is too long.
-
-*	$invalid_char_action [string]
-
-	What to do if the message contains an invalid character. Possible values are
-	* error			 - Fail the message
-	* remove		 - Remove the invalid characters then send
-	* replace		 - Replace some common invalid characters such as replacing curved quotes with straight quotes
-
-*   $ssl [boolean, default: true]
-  
-    Use SSL when making an HTTP request to the Clockwork API
-
-
-### Setting Options
-
-#### Global Options
-
-Options set on the API object will apply to all SMS messages unless specifically overridden.
-
-In this example both messages will be sent from Clockwork:
-
-```php
-$options = array( 'from' => 'Clockwork' );
-$clockwork = new Clockwork( $API_KEY, $options );
-$messages = array( 
-    array( 'to' => '441234567891', 'message' => 'This is a test!' ),
-    array( 'to' => '441234567892', 'message' => 'This is a test 2!' )
-);
-$results = $clockwork->send( $messages );
-```
-
-#### Per-message Options
-
-Set option values individually on each message.
-
-In this example, one message will be from Clockwork and the other from 84433:
-
-```php
-$clockwork = new Clockwork( $API_KEY, $options );
-$messages = array( 
-    array( 'to' => '441234567891', 'message' => 'This is a test!', 'from' => 'Clockwork' ),
-    array( 'to' => '441234567892', 'message' => 'This is a test 2!', 'from' => '84433' )
-);
-$results = $clockwork->send( $messages );
-```
-
-### SSL Errors
-
-Due to the huge variety of PHP setups out there a small proportion of users may get PHP errors when making API calls due to their SSL configuration.
-
-The errors will generally look something like this:
-
-```
-Fatal error: 
-Uncaught exception 'Exception' with message 'HTTP Error calling Clockwork API
-HTTP Status: 0
-cURL Erorr: SSL certificate problem, verify that the CA cert is OK. 
-Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed'
-```
-
-If you're seeing this error there are two fixes available, the first is easy, simply disable SSL on Clockwork calls. Alternatively you can setup your PHP install with the correct root certificates.
-
-#### Disable SSL on Clockwork calls
-
-```php
-$options = array( 'ssl' => false );
-$clockwork = new Clockwork( $API_KEY, $options );
-```
-
-#### Setup SSL root certificates on your server
-
-This is much more complicated as it depends on your setup, however there are many guides available online. 
-Try a search term like "windows php curl root certificates" or "ubuntu update root certificates".
-
-
-# License
-
-This project is licensed under the ISC open-source license.
-
-A copy of this license can be found in license.txt.
-
-# Contributing
-
-If you have any feedback on this wrapper drop us an email to [hello@clockworksms.com][1].
-
-The project is hosted on GitHub at [https://github.com/mediaburst/clockwork-php][3].
-If you would like to contribute a bug fix or improvement please fork the project 
-and submit a pull request.
-
-[1]: mailto:hello@clockworksms.com
-[2]: http://www.clockworksms.com/
-[3]: https://github.com/mediaburst/clockwork-php
+SMS message types (a new course is created, an account is approved and so on) can be enabled or disabled from it's plugin configuration option.

+ 1 - 1
plugin/clockworksms/sms_templates/account_approved_connect.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/account_created_updated_login_password.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/answer_open_question_test_reviewed.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/assignment_been_created_course.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/been_invited_complete_survey_course.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/been_invited_join_group.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/been_subscribed_course.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/check_email_connect_more_info.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/course_opening_request_code_registered.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/course_opening_request_course_code.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/course_opening_request_course_code_approved.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/messages_sent_edited_group_added.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/messages_sent_edited_group_edited.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/new_answer_posted_forum.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/new_course_been_created.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/new_course_suggested_teacher.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/new_file_shared_course_by.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/new_system_announcement_added.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/new_thread_started_forum.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/new_user_pending_approval.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/new_user_subscribed_course.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/password_updated_login_password.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/posted_forum_course.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/received_new_personal_messages.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/reminder_assignment_course_due.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/request_open_course_code_rejected.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/requested_password_change.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/student_answered_test.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/student_answered_test_open_question.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/student_answered_test_voice_question.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

+ 1 - 1
plugin/clockworksms/sms_templates/subscribed_session.tpl

@@ -1 +1 @@
-{{ message }}
+{{ message }}

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