From 86bfd6af9ecb30224f628e08c16d30532ac8a8f5 Mon Sep 17 00:00:00 2001
From: Hubert Borderiou <baelmyhu@gmail.com>
Date: Wed, 4 Sep 2013 11:09:38 +0200
Subject: [PATCH 01/65] Fix bug in graded thread view tab in course session -
 ref #6589

---
 main/forum/forumfunction.inc.php | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/main/forum/forumfunction.inc.php b/main/forum/forumfunction.inc.php
index 966a270654..9ea4eebb71 100644
--- a/main/forum/forumfunction.inc.php
+++ b/main/forum/forumfunction.inc.php
@@ -1705,8 +1705,8 @@ function get_thread_users_qualify($thread_id)
                   AND user.user_id = session_rel_user_rel_course.id_user
                   AND session_rel_user_rel_course.status<>'2'
                   AND session_rel_user_rel_course.id_user NOT IN ($user_to_avoid)
-                  AND qualify.thread_id = '".Database::escape_string($thread_id)."
-                  AND thread_id = '".Database::escape_string($thread_id)."'
+                  AND qualify.thread_id = '".Database::escape_string($thread_id)."'
+                  AND post.thread_id = '".Database::escape_string($thread_id)."'
                   AND id_session = '".api_get_session_id()."'
                   AND course_code = '".$course_code."' AND
                   qualify.c_id = $course_id AND

From d00ea9aafee21ceda775a5da22e386692d88c532 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Wed, 4 Sep 2013 11:21:29 +0200
Subject: [PATCH 02/65] Fixing PHP warning.

---
 main/admin/course_information.php | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/main/admin/course_information.php b/main/admin/course_information.php
index 8a936ef7d0..d28babc330 100644
--- a/main/admin/course_information.php
+++ b/main/admin/course_information.php
@@ -68,11 +68,11 @@ Display::display_header($tool_name);
 <div class="actions">
 <a href="<?php echo api_get_path(WEB_COURSE_PATH).$course->directory; ?>"><?php Display::display_icon('home.png', get_lang('CourseHomepage'), array(), ICON_SIZE_MEDIUM); ?></a>
 </div>
-<?php 
+<?php
 
 echo Display::page_header(get_lang('CourseUsage'));
 
-$id_session = intval($_GET['id_session']);
+$id_session = isset($_GET['id_session']) ? $_GET['id_session'] : 0;
 $table = new SortableTableFromArray(get_course_usage($course->code,$id_session),0,20,'usage_table');
 $table->set_additional_parameters(array ('code' => Security::remove_XSS($_GET['code'])));
 $table->set_other_tables(array('user_table','class_table'));
@@ -129,11 +129,11 @@ $session_list = SessionManager::get_session_by_course($course->code);
 
 $url = api_get_path(WEB_CODE_PATH);
 if (!empty($session_list)) {
-    foreach($session_list as &$session)  {    
+    foreach($session_list as &$session)  {
         $session[0] = Display::url($session[0], $url.'admin/resume_session.php?id_session='.$session['id'] );
         unset($session[1]);
     }
-    echo Display::page_header(get_lang('Sessions')); 
+    echo Display::page_header(get_lang('Sessions'));
     $table = new SortableTableFromArray($session_list, 0, 20,'user_table');
     $table->display();
 }
@@ -141,10 +141,10 @@ if (!empty($session_list)) {
 /*$group = new UserGroup();
 $usegroups = $group->get_usergroup_by_course($course->id);*/
 
-/*@todo This should be dissapear classes are a deprecated feature*/ 
+/*@todo This should be dissapear classes are a deprecated feature*/
 /*
 //Show all classes subscribed in this course
- 
+
 $table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
 $table_class 		= Database :: get_main_table(TABLE_MAIN_CLASS);
 $sql = "SELECT * FROM $table_course_class cc, $table_class c WHERE cc.class_id = c.id AND cc.course_code = '".$code."'";
@@ -170,4 +170,4 @@ if (Database::num_rows($res) > 0) {
 	echo '<p>'.get_lang('NoClassesForThisCourse').'</p>';
 }*/
 /*	FOOTER	*/
-Display::display_footer();
\ No newline at end of file
+Display::display_footer();

From 54145d4f26ac10006d122d288c44dc5abe5edbdf Mon Sep 17 00:00:00 2001
From: Hubert Borderiou <baelmyhu@gmail.com>
Date: Wed, 4 Sep 2013 17:50:49 +0200
Subject: [PATCH 03/65] Fix [start|end] date bug in quiz advanced properties
 when creating a quiz - ref #6586

---
 main/exercice/exercise.class.php | 43 +++++++++++++++++++++++---------
 1 file changed, 31 insertions(+), 12 deletions(-)

diff --git a/main/exercice/exercise.class.php b/main/exercice/exercise.class.php
index b93d108c0b..132cc2013a 100644
--- a/main/exercice/exercise.class.php
+++ b/main/exercice/exercise.class.php
@@ -709,19 +709,21 @@ class Exercise {
 
         $expired_time = intval($this->expired_time);
 
-        if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
-            $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
-        } else {
-            $start_time = '0000-00-00 00:00:00';
-        }
-        if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
-            $end_time 	= Database::escape_string(api_get_utc_datetime($this->end_time));
-        } else {
-            $end_time = '0000-00-00 00:00:00';
-        }
-
         // Exercise already exists
         if ($id) {
+            // we prepare date in the database using the api_get_utc_datetime() function
+            if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
+                $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
+            } else {
+                $start_time = '0000-00-00 00:00:00';
+            }
+
+            if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
+                $end_time 	= Database::escape_string(api_get_utc_datetime($this->end_time));
+            } else {
+                $end_time = '0000-00-00 00:00:00';
+            }
+
             $sql="UPDATE $TBL_EXERCICES SET
 				    title='".Database::escape_string($exercise)."',
 					description='".Database::escape_string($description)."'";
@@ -756,6 +758,22 @@ class Exercise {
             }
         } else {
             // creates a new exercise
+
+            // In this case of new exercise, we don't do the api_get_utc_datetime() for date because, bellow, we call function api_set_default_visibility()
+            // In this function, api_set_default_visibility, the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
+            // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
+            if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
+                $start_time = Database::escape_string($this->start_time);
+            } else {
+                $start_time = '0000-00-00 00:00:00';
+            }
+
+            if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
+                $end_time 	= Database::escape_string(($this->end_time));
+            } else {
+                $end_time = '0000-00-00 00:00:00';
+            }
+
             $sql = "INSERT INTO $TBL_EXERCICES (c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,
                                                 results_disabled, max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,
                                                 text_when_finished, display_category_name, pass_percentage)
@@ -785,7 +803,7 @@ class Exercise {
 
             // insert into the item_property table
             api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
-            api_set_default_visibility($this->id, TOOL_QUIZ);
+            api_set_default_visibility($this->id, TOOL_QUIZ, null, true); // This function save the quiz again, carefull about start_time and end_time if you remove this line (see above)
 
             if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
                 $this->search_engine_save();
@@ -1234,6 +1252,7 @@ class Exercise {
             $start_time['d'] = sprintf('%02d', $start_time['d']);
 
             $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
+
         } else {
             $this->start_time = '0000-00-00 00:00:00';
         }

From 37d724fc5fc7f4c6957fe4235777d15b0d8c95dd Mon Sep 17 00:00:00 2001
From: Yannick Warnier <ywarnier@beeznest.org>
Date: Wed, 4 Sep 2013 23:52:47 -0500
Subject: [PATCH 04/65] Fixed icon in users folder in documents - loosely refs
 BT#6660

---
 main/document/document.inc.php | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/main/document/document.inc.php b/main/document/document.inc.php
index c3560f1209..2fec8cdb69 100644
--- a/main/document/document.inc.php
+++ b/main/document/document.inc.php
@@ -360,6 +360,7 @@ function build_document_icon_tag($type, $path) {
     $basename = basename($path);
     $current_session_id = api_get_session_id();
     $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
+    $user_image = false;
     if ($type == 'file') {
         $icon = choose_image($basename);
 
@@ -384,7 +385,9 @@ function build_document_icon_tag($type, $path) {
             if ($image_path['file'] == 'unknown.jpg') {
                 $icon = $image_path['file'];
             } else {
-                $icon = '../upload/users/' . substr($basename, 8) . '/' . $image_path['file'];
+                //$icon = '../upload/users/' . substr($basename, 8) . '/' . $image_path['file'];
+                $user_image = true;
+                $icon = $image_path['dir'] . $image_path['file'];
             }
 
             $basename = get_lang('UserFolder') . ' ' . api_get_person_name($userinfo['firstname'], $userinfo['lastname']);
@@ -450,7 +453,9 @@ function build_document_icon_tag($type, $path) {
             }
         }
     }
-
+    if ($user_image) {
+        return Display::img($icon, $basename, array());
+    }
     return Display::return_icon($icon, $basename, array());
 }
 

From 440f248475a2116cf5ff8c4a0f57953062b82237 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Wed, 4 Sep 2013 11:22:31 +0200
Subject: [PATCH 05/65] Deleting extra field sessions values when deleting a
 session see #6664

---
 main/admin/course_information.php   | 188 ++++++++++++++++------------
 main/inc/lib/sessionmanager.lib.php |  79 +++---------
 2 files changed, 120 insertions(+), 147 deletions(-)

diff --git a/main/admin/course_information.php b/main/admin/course_information.php
index d28babc330..2c50b8cd37 100644
--- a/main/admin/course_information.php
+++ b/main/admin/course_information.php
@@ -4,7 +4,7 @@
  * This script gives information about a course
  * @author Bart Mollet
  * @package chamilo.admin
-*/
+ */
 /**
  * INIT SECTION
  */
@@ -19,43 +19,66 @@ api_protect_admin_script();
 /**
  *
  */
-function get_course_usage($course_code, $session_id = 0) {
-	$table = Database::get_main_table(TABLE_MAIN_COURSE);
+function get_course_usage($course_code, $session_id = 0)
+{
+    $table       = Database::get_main_table(TABLE_MAIN_COURSE);
     $course_code = Database::escape_string($course_code);
-	$sql = "SELECT * FROM $table WHERE code='".$course_code."'";
-	$res = Database::query($sql);
-	$course = Database::fetch_object($res);
-	// Learnpaths
-	$table = Database :: get_course_table(TABLE_LP_MAIN);
-	$usage[] = array (get_lang(ucfirst(TOOL_LEARNPATH)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Forums
-	$table = Database :: get_course_table(TABLE_FORUM);
-	$usage[] = array (get_lang('Forums'), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Quizzes
-	$table = Database :: get_course_table(TABLE_QUIZ_TEST);
-	$usage[] = array (get_lang(ucfirst(TOOL_QUIZ)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Documents
-	$table = Database :: get_course_table(TABLE_DOCUMENT);
-	$usage[] = array (get_lang(ucfirst(TOOL_DOCUMENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Groups
-	$table = Database :: get_course_table(TABLE_GROUP);
-	$usage[] = array (get_lang(ucfirst(TOOL_GROUP)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Calendar
-	$table = Database :: get_course_table(TABLE_AGENDA);
-	$usage[] = array (get_lang(ucfirst(TOOL_CALENDAR_EVENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Link
-	$table = Database::get_course_table(TABLE_LINK);
-	$usage[] = array(get_lang(ucfirst(TOOL_LINK)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Announcements
-	$table = Database::get_course_table(TABLE_ANNOUNCEMENT);
-	$usage[] = array(get_lang(ucfirst(TOOL_ANNOUNCEMENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	return $usage;
+    $sql         = "SELECT * FROM $table WHERE code='".$course_code."'";
+    $res         = Database::query($sql);
+    $course      = Database::fetch_object($res);
+    // Learnpaths
+    $table   = Database :: get_course_table(TABLE_LP_MAIN);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_LEARNPATH)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Forums
+    $table   = Database :: get_course_table(TABLE_FORUM);
+    $usage[] = array(get_lang('Forums'), CourseManager::count_rows_course_table($table, $session_id, $course->id));
+    // Quizzes
+    $table   = Database :: get_course_table(TABLE_QUIZ_TEST);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_QUIZ)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Documents
+    $table   = Database :: get_course_table(TABLE_DOCUMENT);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_DOCUMENT)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Groups
+    $table   = Database :: get_course_table(TABLE_GROUP);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_GROUP)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Calendar
+    $table   = Database :: get_course_table(TABLE_AGENDA);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_CALENDAR_EVENT)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Link
+    $table   = Database::get_course_table(TABLE_LINK);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_LINK)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Announcements
+    $table   = Database::get_course_table(TABLE_ANNOUNCEMENT);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_ANNOUNCEMENT)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    return $usage;
 }
+
 if (!isset ($_GET['code'])) {
-	api_not_allowed();
+    api_not_allowed();
 }
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ("url" => 'course_list.php', "name" => get_lang('Courses'));
+$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array("url" => 'course_list.php', "name" => get_lang('Courses'));
 $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 $code = Database::escape_string($_GET['code']);
 $sql = "SELECT * FROM $table_course WHERE code = '".$code."'";
@@ -63,78 +86,79 @@ $res = Database::query($sql);
 $course = Database::fetch_object($res);
 $tool_name = $course->title.' ('.$course->visual_code.')';
 Display::display_header($tool_name);
-/* <a href="course_create_content.php?course_code=<?php echo $course->code ?>"><?php echo get_lang('AddDummyContentToCourse') ?></a> */
 ?>
-<div class="actions">
-<a href="<?php echo api_get_path(WEB_COURSE_PATH).$course->directory; ?>"><?php Display::display_icon('home.png', get_lang('CourseHomepage'), array(), ICON_SIZE_MEDIUM); ?></a>
-</div>
+    <div class="actions">
+        <a href="<?php echo api_get_path(WEB_COURSE_PATH).$course->directory; ?>">
+            <?php Display::display_icon('home.png', get_lang('CourseHomepage'), array(), ICON_SIZE_MEDIUM); ?>
+        </a>
+    </div>
 <?php
 
 echo Display::page_header(get_lang('CourseUsage'));
 
 $id_session = isset($_GET['id_session']) ? $_GET['id_session'] : 0;
-$table = new SortableTableFromArray(get_course_usage($course->code,$id_session),0,20,'usage_table');
-$table->set_additional_parameters(array ('code' => Security::remove_XSS($_GET['code'])));
-$table->set_other_tables(array('user_table','class_table'));
-$table->set_header(0,get_lang('Tool'), true);
-$table->set_header(1,get_lang('NumberOfItems'), true);
+$table      = new SortableTableFromArray(get_course_usage($course->code, $id_session), 0, 20, 'usage_table');
+$table->set_additional_parameters(array('code' => Security::remove_XSS($_GET['code'])));
+$table->set_other_tables(array('user_table', 'class_table'));
+$table->set_header(0, get_lang('Tool'), true);
+$table->set_header(1, get_lang('NumberOfItems'), true);
 $table->display();
 
 /**
  * Show all users subscribed in this course
  */
 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);
+$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);
 $is_western_name_order = api_is_western_name_order();
 if (Database::num_rows($res) > 0) {
-	$users = array ();
-	while ($obj = Database::fetch_object($res)) {
-		$user = array ();
-		$user[] = $obj->official_code;
-		if ($is_western_name_order) {
-			$user[] = $obj->firstname;
-			$user[] = $obj->lastname;
-		} else {
-			$user[] = $obj->lastname;
-			$user[] = $obj->firstname;
-		}
-		$user[] = Display :: encrypted_mailto_link($obj->email, $obj->email);
-		$user[] = $obj->course_status == 5 ? get_lang('Student') : get_lang('Teacher');
-		$user[] = '<a href="user_information.php?user_id='.$obj->user_id.'">'.Display::return_icon('synthese_view.gif',get_lang('UserInfo')).'</a>';
-		$users[] = $user;
-	}
-	$table = new SortableTableFromArray($users,0,20,'user_table');
-	$table->set_additional_parameters(array ('code' => $code));
-	$table->set_other_tables(array('usage_table','class_table'));
-	$table->set_header(0,get_lang('OfficialCode'), true);
-	if ($is_western_name_order) {
-		$table->set_header(1,get_lang('FirstName'), true);
-		$table->set_header(2,get_lang('LastName'), true);
-	} else {
-		$table->set_header(1,get_lang('LastName'), true);
-		$table->set_header(2,get_lang('FirstName'), true);
-	}
-	$table->set_header(3,get_lang('Email'), true);
-	$table->set_header(4,get_lang('Status'), true);
-	$table->set_header(5,'', false);
-	$table->display();
+    $users = array();
+    while ($obj = Database::fetch_object($res)) {
+        $user   = array();
+        $user[] = $obj->official_code;
+        if ($is_western_name_order) {
+            $user[] = $obj->firstname;
+            $user[] = $obj->lastname;
+        } else {
+            $user[] = $obj->lastname;
+            $user[] = $obj->firstname;
+        }
+        $user[]  = Display :: encrypted_mailto_link($obj->email, $obj->email);
+        $user[]  = $obj->course_status == 5 ? get_lang('Student') : get_lang('Teacher');
+        $user[]  = '<a href="user_information.php?user_id='.$obj->user_id.'">'.Display::return_icon('synthese_view.gif', get_lang('UserInfo')).'</a>';
+        $users[] = $user;
+    }
+    $table = new SortableTableFromArray($users, 0, 20, 'user_table');
+    $table->set_additional_parameters(array('code' => $code));
+    $table->set_other_tables(array('usage_table', 'class_table'));
+    $table->set_header(0, get_lang('OfficialCode'), true);
+    if ($is_western_name_order) {
+        $table->set_header(1, get_lang('FirstName'), true);
+        $table->set_header(2, get_lang('LastName'), true);
+    } else {
+        $table->set_header(1, get_lang('LastName'), true);
+        $table->set_header(2, get_lang('FirstName'), true);
+    }
+    $table->set_header(3, get_lang('Email'), true);
+    $table->set_header(4, get_lang('Status'), true);
+    $table->set_header(5, '', false);
+    $table->display();
 } else {
-	echo get_lang('NoUsersInCourse');
+    echo get_lang('NoUsersInCourse');
 }
 
 $session_list = SessionManager::get_session_by_course($course->code);
 
 $url = api_get_path(WEB_CODE_PATH);
 if (!empty($session_list)) {
-    foreach($session_list as &$session)  {
-        $session[0] = Display::url($session[0], $url.'admin/resume_session.php?id_session='.$session['id'] );
+    foreach ($session_list as &$session) {
+        $session[0] = Display::url($session[0], $url.'admin/resume_session.php?id_session='.$session['id']);
         unset($session[1]);
     }
     echo Display::page_header(get_lang('Sessions'));
-    $table = new SortableTableFromArray($session_list, 0, 20,'user_table');
+    $table = new SortableTableFromArray($session_list, 0, 20, 'user_table');
     $table->display();
 }
 
diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 38fe127085..415cfd20c7 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -302,7 +302,7 @@ class SessionManager
         if (!empty($options['order'])) {
             $query .= " ORDER BY ".$options['order'];
         }
-        
+
 		$result = Database::query($query);
 		$formatted_sessions = array();
 		if (Database::num_rows($result)) {
@@ -488,15 +488,21 @@ class SessionManager
      * @return	void	Nothing, or false on error
 	 * The parameters is a array to delete sessions
 	 **/
-	public static function delete_session($id_checked,$from_ws = false) {
+	public static function delete_session($id_checked,$from_ws = false)
+    {
 		$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);
 		$tbl_url_session                  = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 
-		global $_user;
-		if(is_array($id_checked)) {
+        // Extra session fields
+		$t_sf 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
+		$t_sfv 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
+
+		$userId = api_get_user_id();
+
+		if (is_array($id_checked)) {
 			$id_checked = Database::escape_string(implode(',',$id_checked));
 		} else {
 			$id_checked = intval($id_checked);
@@ -505,77 +511,20 @@ class SessionManager
 		if (!api_is_platform_admin() && !$from_ws) {
 			$sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_checked;
 			$rs  = Database::query($sql);
-			if (Database::result($rs,0,0)!=$_user['user_id']) {
+			if (Database::result($rs, 0, 0) != $userId) {
 				api_not_allowed(true);
 			}
 		}
+
 		Database::query("DELETE FROM $tbl_session WHERE id IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
 
-		// delete extra session fields
-		$t_sf 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
-		$t_sfv 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
+		$sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'";
+		Database::query($sql_delete_sfv);
 
-		// Delete extra fields from session where field variable is "SECCION"
-		$sql = "SELECT t_sfv.field_id FROM $t_sfv t_sfv, $t_sf t_sf  WHERE t_sfv.session_id = '$id_checked' AND t_sf.field_variable = 'SECCION' ";
-		$rs_field = Database::query($sql);
-
-		$field_id = 0;
-		if (Database::num_rows($rs_field) == 1) {
-			$row_field = Database::fetch_row($rs_field);
-			$field_id = $row_field[0];
-
-			$sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
-			$rs_delete_sfv = Database::query($sql_delete_sfv);
-		}
-
-		$sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
-		$rs_field_id = Database::query($sql);
-
-		if (Database::num_rows($rs_field_id) == 0) {
-			$sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
-			$rs_delete_sf = Database::query($sql_delete_sf);
-		}
-
-		/*
-		$sql = "SELECT distinct field_id FROM $t_sfv  WHERE session_id = '$id_checked'";
-		$res_field_ids = @Database::query($sql);
-
-		if (Database::num_rows($res_field_ids) > 0) {
-			while($row_field_id = Database::fetch_row($res_field_ids)){
-				$field_ids[] = $row_field_id[0];
-			}
-		}
-
-		//delete from table_session_field_value from a given session id
-
-		$sql_session_field_value = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'";
-		@Database::query($sql_session_field_value);
-
-		$sql = "SELECT distinct field_id FROM $t_sfv";
-		$res_field_all_ids = @Database::query($sql);
-
-		if (Database::num_rows($res_field_all_ids) > 0) {
-			while($row_field_all_id = Database::fetch_row($res_field_all_ids)){
-				$field_all_ids[] = $row_field_all_id[0];
-			}
-		}
-
-		if (count($field_ids) > 0 && count($field_all_ids) > 0) {
-			foreach($field_ids as $field_id) {
-				// check if field id is used into table field value
-				if (in_array($field_id,$field_all_ids)) {
-					continue;
-				} else {
-					$sql_session_field = "DELETE FROM $t_sf WHERE id = '$field_id'";
-					Database::query($sql_session_field);
-				}
-			}
-		}
-		*/
 		// Add event to system log
 		$user_id = api_get_user_id();
 		event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $user_id);

From 17718e3c62747717d7e8d9cfc6d347754e963134 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 5 Sep 2013 11:15:52 +0200
Subject: [PATCH 06/65] Minor - format code, doc update

---
 main/inc/lib/sessionmanager.lib.php | 13 ++++---------
 1 file changed, 4 insertions(+), 9 deletions(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 415cfd20c7..66fe4246e9 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -483,22 +483,18 @@ class SessionManager
 	/**
 	 * Delete session
 	 * @author Carlos Vargas  from existing code
-	 * @param	array	id_checked
+	 * @param	array	id_checked an array to delete sessions
 	 * @param   boolean  optional, true if the function is called by a webservice, false otherwise.
      * @return	void	Nothing, or false on error
-	 * The parameters is a array to delete sessions
 	 **/
-	public static function delete_session($id_checked,$from_ws = false)
+	public static function delete_session($id_checked, $from_ws = false)
     {
 		$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);
 		$tbl_url_session                  = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-
-        // Extra session fields
-		$t_sf 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
-		$t_sfv 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
+		$t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
 
 		$userId = api_get_user_id();
 
@@ -526,8 +522,7 @@ class SessionManager
 		Database::query($sql_delete_sfv);
 
 		// Add event to system log
-		$user_id = api_get_user_id();
-		event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $user_id);
+		event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $userId);
 	}
 
     public static function clear_session_ref_promotion($id_promotion) {

From baefc76bba4c36fd0d611562124c2f236597ed85 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 5 Sep 2013 11:32:17 +0200
Subject: [PATCH 07/65] Minor - Removing virtual course exception in session
 import.

---
 main/inc/lib/sessionmanager.lib.php | 94 +----------------------------
 1 file changed, 3 insertions(+), 91 deletions(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 66fe4246e9..f823eaab28 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -1874,7 +1874,6 @@ class SessionManager
             $tag_names = array();
 
             foreach ($content as $key => $enreg) {
-
                 $enreg = explode(';', trim($enreg));
                 if ($key) {
                     foreach ($tag_names as $tag_key => $tag_name) {
@@ -1908,7 +1907,7 @@ class SessionManager
                 $visibility             = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
                 $session_category_id    = $enreg['SessionCategory'];
 
-                // Searching a coach.
+                // Searching a general coach.
                 if (!empty($enreg['Coach'])) {
                     $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
                     if ($coach_id === false) {
@@ -2078,22 +2077,9 @@ class SessionManager
 
                     if (CourseManager::course_exists($course_code)) {
 
-                        $coach = api_strstr($course, '[');
-                        $coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
-
-                        if (!empty($coach)) {
-                            $coach_id = UserManager::get_user_id_from_username($coach);
-                            if ($coach_id === false) {
-                                $coach_id = '';
-                            }
-                        } else {
-                            $coach = '';
-                        }
-
                         // Adding the course to a session.
-                        $sql_course = "INSERT IGNORE INTO $tbl_session_course SET
-                                course_code = '$course_code',
-                                id_session='$session_id'";
+                        $sql_course = "INSERT IGNORE INTO $tbl_session_course
+                                       SET course_code = '$course_code', id_session='$session_id'";
                         Database::query($sql_course);
 
                         if ($debug) {
@@ -2159,80 +2145,6 @@ class SessionManager
 
                         $course_info = CourseManager::get_course_information($course_code);
                         $inserted_in_course[$course_code] = $course_info['title'];
-                    } else {
-                        // TODO: We should create the course as in the XML import.
-                    }
-
-
-                    if (CourseManager::course_exists($course_code, true)) {
-
-                        $list = CourseManager :: get_courses_info_from_visual_code($course_code);
-
-                        foreach ($list as $vcourse) {
-
-                            if ($vcourse['code'] == $course_code) {
-                                // Ignore, this has already been inserted.
-                            } else {
-
-                                $coach = api_strstr($course, '[');
-                                $coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
-
-                                // Adding the relationship "Session - Course".
-                                $sql_course = "INSERT IGNORE INTO $tbl_session_course SET
-                                                course_code = '".$vcourse['code']."',
-                                                id_session='$session_id'";
-
-                                Database::query($sql_course);
-
-                                if ($debug) {
-                                    $logger->addInfo("Sessions - Adding course to session: course: '".$vcourse['code']."' and session #$session_id");
-                                }
-
-                                // Adding coachs to session course user
-                                foreach ($course_coaches as $course_coach) {
-                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
-                                    if ($coach_id !== false) {
-                                        $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-                                                id_user='$coach_id',
-                                                course_code='{$vcourse['code']}',
-                                                id_session = '$session_id',
-                                                status = 2 ";
-                                        Database::query($sql);
-
-                                        if ($debug) {
-                                            $logger->addInfo("Sessions - Adding coach to session: user #$coach_id ($course_coach) course: '".$vcourse['code']."' and session #$session_id");
-                                        }
-
-                                    } else {
-                                        $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
-                                    }
-                                }
-
-
-                                $users_in_course_counter = 0;
-                                // Adding the relationship "Session - Course - User".
-                                foreach ($course_users as $user) {
-                                    $user_id = UserManager::get_user_id_from_username($user);
-                                    if ($user_id !== false) {
-                                        $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-                                                id_user='$user_id',
-                                                course_code='{$vcourse['code']}',
-                                                id_session = '$session_id'";
-                                        Database::query($sql);
-
-                                        if ($debug) {
-                                            $logger->addInfo("Sessions - Adding user to session: user #$user_id ($user) course: '".$vcourse['code']."' and session #$session_id");
-                                        }
-
-                                        $users_in_course_counter++;
-                                    } else {
-                                        $error_message .= get_lang('UserDoesNotExist').' : '.$user.$eol;
-                                    }
-                                }
-                                Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='".$vcourse['code']."'");
-                            }
-                        }
-                        $inserted_in_course[$vcourse['code']] = $vcourse['title'];
                     }
                 }
                 $access_url_id = api_get_current_access_url_id();

From 3112a126f8598f3ffdf1f1aef6e3e390902009a9 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 5 Sep 2013 17:52:10 +0200
Subject: [PATCH 08/65] Fixing category code when creating a course see BT#6666

---
 main/admin/course_add.php | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/main/admin/course_add.php b/main/admin/course_add.php
index 8046956948..1a9814e04d 100644
--- a/main/admin/course_add.php
+++ b/main/admin/course_add.php
@@ -124,7 +124,7 @@ $default_course_visibility = api_get_setting('courses_default_creation_visibilit
 if (isset($default_course_visibility)) {
     $values['visibility']       = api_get_setting('courses_default_creation_visibility');
 } else {
-    $values['visibility']       = COURSE_VISIBILITY_OPEN_PLATFORM;    
+    $values['visibility']       = COURSE_VISIBILITY_OPEN_PLATFORM;
 }
 $values['subscribe']        = 1;
 $values['unsubscribe']      = 0;
@@ -135,21 +135,19 @@ $form->setDefaults($values);
 
 // Validate the form
 if ($form->validate()) {
-    $course          = $form->exportValues();    
-    //$tutor_name      = $teachers[$course['tutor_id']];
+    $course          = $form->exportValues();
     $teacher_id      = $course['tutor_id'];
-    $course_teachers = $course['course_teachers'];    
-    
+    $course_teachers = $course['course_teachers'];
+
     $course['disk_quota'] = $course['disk_quota']*1024*1024;
-    
+
     $course['exemplary_content']    = empty($course['exemplary_content']) ? false : true;
     $course['teachers']             = $course_teachers;
-    //$course['tutor_name']           = $tutor_name;
-    $course['user_id']              = $teacher_id;  
+    $course['user_id']              = $teacher_id;
     $course['wanted_code']          = $course['visual_code'];
-    
-    $course['gradebook_model_id']   = isset($course['gradebook_model_id']) ? $course['gradebook_model_id'] : null;            
-    
+    $course['gradebook_model_id']   = isset($course['gradebook_model_id']) ? $course['gradebook_model_id'] : null;
+    // Fixing category code
+    $course['course_category'] = $course['category_code'];
     $course_info = CourseManager::create_course($course);
 
     header('Location: course_list.php'.($course_info===false?'?action=show_msg&warn='.api_get_last_failure():''));

From 85a1d62a15aa1c5083f30788de995100d695e33f Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 9 Sep 2013 11:52:50 +0200
Subject: [PATCH 09/65] Fixing bug in the search ajax filemanager see BT#6675

---
 .../ajaxfilemanager/inc/function.base.php      | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/function.base.php b/main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/function.base.php
index 9e176e9622..2e80ca7168 100644
--- a/main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/function.base.php
+++ b/main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/function.base.php
@@ -726,8 +726,18 @@ if (!function_exists('mime_content_type')) {
  * @param string $path the path to the document
  * @return boolean
  */
-function isListingDocument($path) {
+function isListingDocument($path)
+{
+    global $PathChamiloAjaxFileManager;
     $file = basename($path);
+    $filePath = realpath($path);
+    $allowedPath = realpath($PathChamiloAjaxFileManager);
+
+    $check = Security::check_abs_path($filePath, $allowedPath);
+    if ($check == false) {
+        return false;
+    }
+
     if (CONFIG_SYS_PATTERN_FORMAT == 'list') {// comma delimited vague file/folder name
         if (is_dir($path)) {
             $includeDir = trimlrm(CONFIG_SYS_INC_DIR_PATTERN);
@@ -752,14 +762,10 @@ function isListingDocument($path) {
         }
     } elseif (CONFIG_SYS_PATTERN_FORMAT == 'csv') {//comma delimited file/folder name
         if (is_dir($path)) {
-
             $includeDir = trimlrm(CONFIG_SYS_INC_DIR_PATTERN);
             $excludeDir = trimlrm(CONFIG_SYS_EXC_DIR_PATTERN);
-
             if (!empty($includeDir) && !empty($excludeDir)) {
-
                 $validDir = explode(',', $includeDir);
-
                 $invalidDir = explode(",", $excludeDir);
 
                 if (array_search(basename($path), $validDir) !== false && array_search(basename($path), $invalidDir) === false) {
@@ -1081,4 +1087,4 @@ function hideFolderName($folderName) {
         !preg_match("/$thumbs_folder/", $folderName) && $show_doc_group == true) {
         return substr($folderName, strpos($folderName, '-'), strlen($folderName)); //hide the firsts numbers
     }
-}
\ No newline at end of file
+}

From ea749fa82bcc728f5fd65b19abed53199a631051 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 9 Sep 2013 11:58:57 +0200
Subject: [PATCH 10/65] User must logged in, to search a document.

---
 .../ajaxfilemanager/inc/config.base.php       | 28 +++++++++++--------
 1 file changed, 16 insertions(+), 12 deletions(-)

diff --git a/main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.base.php b/main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.base.php
index 969c96c6ed..7a036fb141 100644
--- a/main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.base.php
+++ b/main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.base.php
@@ -45,7 +45,7 @@ if(empty($_course['path']) || Security::remove_XSS($_GET['editor'])=="stand_alon
 	define('CONFIG_OPTIONS_UPLOAD', true);
 	define('CONFIG_OPTIONS_EDITABLE', false); //disable image editor and text editor
 } else {
-	
+
 	if(api_is_allowed_to_edit()) {
 		//api_is_allowed_to_edit() from Chamilo
 		define('CONFIG_OPTIONS_DELETE', true);
@@ -99,15 +99,19 @@ if(!empty($_course['path']) && Security::remove_XSS($_GET['editor'])!="stand_alo
 		$PathChamiloAjaxFileManager='../../../../../../../home/default_platform_document/';
 	} else {
 		//my profile
-		$my_path					= UserManager::get_user_picture_path_by_id(api_get_user_id(),'none');
-                $dir = api_get_path(SYS_CODE_PATH).$my_path['dir'];
-                if (!is_dir($dir)) {
-                    mkdir($dir);
-                }
-                if (!is_dir($dir.'my_files')) {
-                    mkdir($dir.'my_files');
-                }
-		$PathChamiloAjaxFileManager	= '../../../../../../../main/'.$my_path['dir'].'my_files/';
+		$my_path = UserManager::get_user_picture_path_by_id(api_get_user_id(),'none');
+        if (!empty($my_path['dir'])) {
+            $dir = api_get_path(SYS_CODE_PATH).$my_path['dir'];
+            if (!is_dir($dir)) {
+                mkdir($dir);
+            }
+            if (!is_dir($dir.'my_files')) {
+                mkdir($dir.'my_files');
+            }
+            $PathChamiloAjaxFileManager	= '../../../../../../../main/'.$my_path['dir'].'my_files/';
+        } else {
+            api_not_allowed();
+        }
 	}
 }
 
@@ -141,12 +145,12 @@ define('CONFIG_EDITABLE_VALID_EXTS', 'txt,htm,html'); //make you include all the
 
 define('CONFIG_OVERWRITTEN', false); //overwirte when processing paste
 define('CONFIG_UPLOAD_VALID_EXTS', 'gif,jpg,jpeg,png,bmp,tif,psd,zip,sit,rar,gz,tar,htm,html,mov,mpg,avi,asf,mpeg,wmv,ogg,ogx,ogv,oga, aif,aiff,wav,mp3,swf,flv, mp4, aac, ppt,rtf,doc, pdf,xls,txt,flv,odt,ods,odp,odg,odc,odf,odb,odi,pps,docx,pptx,xlsx,accdb,xml,mid, midi, svg, svgz, mm');//Updated for Chamilo
-	
+
 //define viewable valid exts
 $viewable='gif,bmp,txt,jpg,jpeg,png,tif,html,htm,mp3,wav,wmv,wma,rm,rmvb,mov,swf,flv,mp4,aac,avi,mpg,mpeg,asf,mid,midi';//updated by Chamilo
 $viewable_array = explode(" ",$viewable);
 
-if (api_browser_support('svg')){				
+if (api_browser_support('svg')){
 	$viewable_array[]=',svg';
 }
 if (api_browser_support('ogg')){

From f6028602f518223d00e30d019c1309992734a3d0 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 9 Sep 2013 12:17:18 +0200
Subject: [PATCH 11/65] Minor - adding isset.

---
 main/inc/lib/sessionmanager.lib.php | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index f823eaab28..a3fb8982a0 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -1905,7 +1905,7 @@ class SessionManager
                 $date_start             = $enreg['DateStart'];
                 $date_end               = $enreg['DateEnd'];
                 $visibility             = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
-                $session_category_id    = $enreg['SessionCategory'];
+                $session_category_id    = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
 
                 // Searching a general coach.
                 if (!empty($enreg['Coach'])) {
@@ -1923,6 +1923,7 @@ class SessionManager
                     $unique_name = false; // This MUST be initializead.
                     $i = 0;
                     // Change session name, verify that session doesn't exist.
+                    $suffix = null;
                     while (!$unique_name) {
                         if ($i > 1) {
                             $suffix = ' - '.$i;

From c9dc7ae249a1e18aafe66acc2f0886c45436a3a8 Mon Sep 17 00:00:00 2001
From: Yannick Warnier <ywarnier@beeznest.org>
Date: Tue, 10 Sep 2013 12:25:14 -0500
Subject: [PATCH 12/65] Fixed issue returning student instead of teacher in
 certificates in sessions - refs #6694

---
 main/inc/lib/usermanager.lib.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php
index f9d8efa86b..4e741aaa4c 100644
--- a/main/inc/lib/usermanager.lib.php
+++ b/main/inc/lib/usermanager.lib.php
@@ -3492,7 +3492,7 @@ class UserManager
         } elseif ($session > 0) {
             $sql = 'SELECT u.user_id FROM '.$table_user.' u
                 INNER JOIN '.$table_session_course_user.' sru
-                ON sru.id_user=u.user_id WHERE sru.course_code="'.Database::escape_string($course_id).'" ';
+                ON sru.id_user=u.user_id WHERE sru.course_code="'.Database::escape_string($course_id).'" AND sru.status=2';
             $rs = Database::query($sql);
             $row = Database::fetch_array($rs);
 

From 06cae6093dac25af74df57638933b25332d814d0 Mon Sep 17 00:00:00 2001
From: Yannick Warnier <ywarnier@beeznest.org>
Date: Wed, 11 Sep 2013 00:19:46 -0500
Subject: [PATCH 13/65] Added new GetLearnpathHighestLessonLocation()
 webservice - refs BT#6667

---
 main/webservices/soap.test.php         | 44 ++++++++++++++++++++++++++
 main/webservices/soap_report.php       | 10 ++++--
 main/webservices/webservice_report.php | 33 ++++++++++++++++++-
 3 files changed, 84 insertions(+), 3 deletions(-)
 create mode 100644 main/webservices/soap.test.php

diff --git a/main/webservices/soap.test.php b/main/webservices/soap.test.php
new file mode 100644
index 0000000000..59d71a99e9
--- /dev/null
+++ b/main/webservices/soap.test.php
@@ -0,0 +1,44 @@
+<?php /* For licensing terms, see /license.txt */
+/**
+ * Test script for soap.php
+ * @author Yannick Warnier <yannick.warnier@beeznest.com>
+ * @package chamilo.webservices
+ */
+/**
+ * Init
+ */
+exit; //remove to enable
+// Include the necessary files, assuming this script is located in main/newscorm/ or something like that
+require_once '../inc/global.inc.php';
+global $_configuration;
+
+// First build the signature to use with the webservice. We assume
+// we are calling the webservice from the same server, so getting
+// the IP (part of the signature) can be done through $_SERVER['REMOTE_ADDR']
+$ip = trim($_SERVER['REMOTE_ADDR']);
+$signature = sha1($ip.$_configuration['security_key']);
+
+// Prepare the arguments to the webservice, based on the user ID (int), the course ID (int), the learnpath_id and the learnpath_item_id:
+$uid = 1; // set to your user ID
+$cid = 1; // set to your course ID
+$lpid = 1; // set to your learnpath ID
+$lpiid = 1; // set to your learnpath item ID
+
+// Build the server's SOAP script address
+$server = api_get_path(WEB_CODE_PATH).'webservices/soap.php?wsdl';
+
+/**
+ * Call the webservice
+ */
+
+// Init the SOAP connection
+$client = new SoapClient($server, array('cache_wsdl' => WSDL_CACHE_NONE));
+
+// Call the function we want with the right params...
+$response = $client->{'WSReport.test'}();
+//$response = $client->{'WSReport.GetLearnpathStatusSingleItem'}($signature, 'chamilo_user_id', $uid, 'chamilo_course_id', $cid, $lpid, $lpiid);
+//$response = $client->{'WSReport.GetLearnpathProgress'}($signature, 'chamilo_user_id', $uid, 'chamilo_course_id', $cid, $lpid);
+//$response = $client->{'WSReport.GetLearnpathHighestLessonLocation'}($signature, 'chamilo_user_id', $uid, 'chamilo_course_id', $cid, $lpid);
+// Print the output, or do whatever you like with it (it's the status for this item):
+echo '<pre>'.$response.'</pre>';
+// This should print "complete", "incomplete" or any other active status.
\ No newline at end of file
diff --git a/main/webservices/soap_report.php b/main/webservices/soap_report.php
index f8d07db64d..d252cefb2e 100755
--- a/main/webservices/soap_report.php
+++ b/main/webservices/soap_report.php
@@ -146,14 +146,20 @@ $s->register(
 );
 
 $s->register(
-    'WSReport.GetLearnpathScoreSingleItem',
+    'WSReport.GetLearnpathHighestLessonLocation',
     array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string'),
+    array('return' => 'xsd:string')
+);
+
+$s->register(
+    'WSReport.GetLearnpathScoreSingleItem',
+    array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string', 'learnpath_item_id' => 'xsd:string'),
     array('return' => 'tns:score_result')
 );
 
 $s->register(
     'WSReport.GetLearnpathStatusSingleItem',
-    array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string'),
+    array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string', 'learnpath_item_id' => 'xsd:string'),
     array('return' => 'xsd:string')
 );
 
diff --git a/main/webservices/webservice_report.php b/main/webservices/webservice_report.php
index 9be643e2a8..08ed3bcccf 100755
--- a/main/webservices/webservice_report.php
+++ b/main/webservices/webservice_report.php
@@ -129,13 +129,44 @@ class WSReport extends WS {
         }
         require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
         $lp = new learnpath($course_code, $learnpath_id, $user_id);
-        $items = $lp->items[$learnpath_id];
         $return = array(
           'progress_bar_mode' => $lp->progress_bar_mode,
           'progress_db' => $lp->progress_db,
         );
         return $return;
     }
+
+    /**
+     * Gets the highest element seen (lesson_location) in the given learning
+     * path by the given user. If the user saw the learning path several times,
+     * the last time (lp_view) is assumed. If there are several items in the lp,
+     * the last item seen (lp_view.last_item) is considered as the relevant one
+     * to get the lesson_location from.
+     *
+     * @param string User id field name
+     * @param string User id value
+     * @param string Course id field name
+     * @param string Course id value
+     * @param string Learnpath ID
+     * @return string The last item's lesson_location value
+     */
+    public function GetLearnpathHighestLessonLocation($secret_key, $user_id_field_name, $user_id_value, $course_id_field_name, $course_id_value, $learnpath_id) {
+        $user_id = $this->getUserId($user_id_field_name, $user_id_value);
+        if($user_id instanceof WSError) {
+            return $user_id;
+        }
+        $course_id = $this->getCourseId($course_id_field_name, $course_id_value);
+        if($course_id instanceof WSError) {
+            return $course_id;
+        } else {
+            $course_code = CourseManager::get_course_code_from_course_id($course_id);
+        }
+        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
+        $lp = new learnpath($course_code, $learnpath_id, $user_id);
+        $item = $lp->last_item_seen;
+        $return = $lp->items[$item]->get_lesson_location();
+        return $return;
+    }
     
     /**
      * Gets score obtained in the given learning path by the given user,

From 0f57807d4093ee0b1923342af64710a39bbceff6 Mon Sep 17 00:00:00 2001
From: Hubert Borderiou <baelmyhu@gmail.com>
Date: Wed, 11 Sep 2013 11:59:32 +0200
Subject: [PATCH 14/65] Fix some bugs in learning path item drag-n-drop - ref
 #6622

---
 main/inc/ajax/lp.ajax.php         | 115 +++++++++++++++++----
 main/newscorm/learnpath.class.php | 140 +-------------------------
 main/newscorm/lp_controller.php   | 159 ++++++++++++++++++++++++++++++
 3 files changed, 257 insertions(+), 157 deletions(-)

diff --git a/main/inc/ajax/lp.ajax.php b/main/inc/ajax/lp.ajax.php
index 3056b6fa74..70029db07a 100644
--- a/main/inc/ajax/lp.ajax.php
+++ b/main/inc/ajax/lp.ajax.php
@@ -23,34 +23,52 @@ switch ($action) {
         break;
     case 'update_lp_item_order':
         if (api_is_allowed_to_edit(null, true)) {
+
             $new_order   = $_POST['new_order'];
+
             $sections	= explode('^', $new_order);
             $new_array = array();
-            $i = 0;
 
+            // We have to update parent_item_id, previous_item_id, next_item_id, display_order in the database
+            $LP_item_list = new LP_item_order_list();
             foreach ($sections as $items) {
                 if (!empty($items)) {
                     list($id, $parent_id) = explode('|', $items);
-                    $new_array[$i]['id'] = intval($id);
-                    $new_array[$i]['parent_id'] = intval($parent_id);
-                    $i++;
+                    $item = new LP_item_order_item($id, $parent_id);
+                    $LP_item_list->add($item);
+                }
+            }
+
+            $tab_parents_id = $LP_item_list->get_list_of_parents();
+
+            foreach ($tab_parents_id as $parent_id) {
+                $Same_parent_LP_item_list = $LP_item_list->get_item_with_same_parent($parent_id);
+                $previous_item_id = 0;
+                for ($i=0; $i < count($Same_parent_LP_item_list->list);$i++) {
+                    $item_id = $Same_parent_LP_item_list->list[$i]->id;
+                    // display_order
+                    $display_order = $i + 1;
+                    $LP_item_list->set_parameters_for_id($item_id, $display_order, "display_order");
+                    // previous_item_id
+                    $LP_item_list->set_parameters_for_id($item_id, $previous_item_id, "previous_item_id");
+                    $previous_item_id = $item_id;
+                    // next_item_id
+                    $next_item_id = 0;
+                    if ($i < count($Same_parent_LP_item_list->list) - 1) {
+                        $next_item_id = $Same_parent_LP_item_list->list[$i+1]->id;
+                    }
+                    $LP_item_list->set_parameters_for_id($item_id, $next_item_id, "next_item_id");
                 }
             }
 
-            $counter = 1;
-            for ($i=0; $i < count($new_array); $i++) {
-            	$params = array();
-            	$id = $new_array[$i]['id'];
-            	if (empty($id)) {
-            		continue;
-            	}
-            	$parent_id = isset($new_array[$i]['parent_id']) ? $new_array[$i]['parent_id'] : 0;
-            	$params['display_order'] 	= $counter;
-            	$params['previous_item_id']	= isset($new_array[$i-1]) &&  isset($new_array[$i-1]['id']) ? $new_array[$i-1]['id'] : 0;
-            	$params['next_item_id']		= isset($new_array[$i+1]) &&  isset($new_array[$i+1]['id']) ? $new_array[$i+1]['id'] : 0;
-            	$params['parent_item_id']	= $parent_id;
-            	Database::update($tbl_lp_item, $params, array('id = ? AND c_id = ? '=> array(intval($id), $course_id)));
-                $counter ++;
+            foreach ($LP_item_list->list as $LP_item) {
+                $params = array();
+                $params['display_order']    = $LP_item->display_order;
+                $params['previous_item_id']	= $LP_item->previous_item_id;
+                $params['next_item_id']     = $LP_item->next_item_id;
+                $params['parent_item_id']	= $LP_item->parent_item_id;
+
+                Database::update($tbl_lp_item, $params, array('id = ? AND c_id = ? '=> array(intval($LP_item->id), $course_id)));
             }
             Display::display_confirmation_message(get_lang('Saved'));
         }
@@ -117,3 +135,64 @@ switch ($action) {
         echo '';
 }
 exit;
+
+
+/*
+ * Classes to create a special data structure to manipulate LP Items
+ * used only in this file
+ */
+class LP_item_order_list {
+    public $list = array();
+
+    public function __construct() {
+        $this->list = array();
+    }
+
+    public function add($in_LP_item_order_item) {
+        $this->list[] = $in_LP_item_order_item;
+    }
+
+    public function get_item_with_same_parent($in_parent_id) {
+        $out_res = new LP_item_order_list();
+        for ($i=0; $i < count($this->list); $i++) {
+            if ($this->list[$i]->parent_item_id == $in_parent_id) {
+                $out_res->add($this->list[$i]);
+            }
+        }
+        return $out_res;
+    }
+
+    public function get_list_of_parents() {
+        $tab_out_res = array();
+        foreach ($this->list as $LP_item) {
+            if (!in_array($LP_item->parent_item_id, $tab_out_res)) {
+                $tab_out_res[] = $LP_item->parent_item_id;
+            }
+        }
+        return $tab_out_res;
+    }
+
+    public function set_parameters_for_id($in_id, $in_value, $in_parameters) {
+        for ($i=0; $i < count($this->list); $i++) {
+            if ($this->list[$i]->id == $in_id) {
+                $this->list[$i]->$in_parameters = $in_value;
+                break;
+            }
+        }
+    }
+
+}
+
+class LP_item_order_item {
+    public $id = 0;
+    public $parent_item_id = 0;
+    public $previous_item_id = 0;
+    public $next_item_id = 0;
+    public $display_order = 0;
+
+    public function __construct($in_id=0, $in_parent_id=0) {
+        $this->id = $in_id;
+        $this->parent_item_id = $in_parent_id;
+    }
+
+}
\ No newline at end of file
diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php
index 0f2f3099be..653718cba8 100644
--- a/main/newscorm/learnpath.class.php
+++ b/main/newscorm/learnpath.class.php
@@ -582,7 +582,6 @@ class learnpath {
                                SET ref = " . $new_item_id . "
                                WHERE c_id = $course_id AND id = " . $new_item_id;
             Database::query($sql_update_ref);
-
         }
 
         // Upload audio.
@@ -4921,144 +4920,7 @@ class learnpath {
     }
 
     public function return_new_tree($update_audio = 'false', $drop_element_here = false) {
-        $ajax_url = api_get_path(WEB_AJAX_PATH).'lp.ajax.php';
-
-        $return = '<script>
-        var newOrderData= "";
-        function processChildren(parentId) {
-            //Loop through the children of the UL element defined by the parentId
-            var ulParentID= "UL_" + parentId;
-            $("#" + ulParentID).children().each(function () {
-
-                /*Only process elements with an id attribute (in order to skip the blank,
-                    unmovable <li> elements.*/
-
-                if ($(this).attr("id")) {
-                    /*Build a string of data with the childs ID and parent ID,
-                        using the "|" as a delimiter between the two IDs and the "^"
-                        as a record delimiter (these delimiters were chosen in case the data
-                        involved includes more common delimiters like commas within the content)
-                    */
-                    newOrderData= newOrderData + $(this).attr("id") + "|" + parentId + "^";
-
-                    //Determine if this child is a containter
-                    if ($(this).is(".container")) {
-                        //Process the child elements of the container
-                        processChildren($(this).attr("id"));
-                    }
-                }
-            });  //end of children loop
-        } //end of processChildren function
-
-        $(function() {
-
-            $(".item_data").live("mouseover", function(event) {
-                $(".button_actions", this).show();
-            });
-
-            $(".item_data").live("mouseout", function() {
-                $(".button_actions",this).hide();
-            });
-
-            $(".button_actions").hide();
-
-            $( ".lp_resource" ).sortable({
-                items: ".lp_resource_element ",
-                handle: ".moved", //only the class "moved"
-                cursor: "move",
-                connectWith: "#lp_item_list",
-                placeholder: "ui-state-highlight", //defines the yellow highlight
-
-                start: function(event, ui) {
-                    $(ui.item).css("width", "160px");
-                    $(ui.item).find(".item_data").attr("style", "");
-
-                },
-                stop: function(event, ui) {
-                    $(ui.item).css("width", "100%");
-                },
-            });
-
-            $("#lp_item_list").sortable({
-                items: "li",
-                handle: ".moved", //only the class "moved"
-                cursor: "move",
-                placeholder: "ui-state-highlight", //defines the yellow highlight
-
-                update: function(event, ui) {
-
-                    //Walk through the direct descendants of the lp_item_list <ul>
-                    $("#lp_item_list").children().each(function () {
-
-                        /*Only process elements with an id attribute (in order to skip the blank,
-                        unmovable <li> elements.*/
-
-                        if ($(this).attr("id")) {
-                                /*Build a string of data with the child s ID and parent ID,
-                                using the "|" as a delimiter between the two IDs and the "^"
-                                as a record delimiter (these delimiters were chosen in case the data
-                                involved includes more common delimiters like commas within the content)
-                                */
-                                newOrderData= newOrderData + $(this).attr("id") + "|" + "0" + "^";
-
-                                //Determine if this child is a containter
-                                if ($(this).is(".li_container")) {
-                                    //Process the child elements of the container
-                                    processChildren($(this).attr("id"));
-                                }
-                            }
-                    }); //end of lp_item_list children loop
-
-                    var order = "new_order="+ newOrderData + "&a=update_lp_item_order";
-                    $.post("'.$ajax_url.'", order, function(reponse){
-                        $("#message").html(reponse);
-                    });
-                },
-                receive: function(event, ui) {
-
-                    var id = $(ui.item).attr("data_id");
-                    var type = $(ui.item).attr("data_type");
-                    var title = $(ui.item).attr("title");
-
-                    if (ui.item.parent()[0]) {
-                        var parent_id = $(ui.item.parent()[0]).attr("id");
-                        var previous_id = $(ui.item.prev()).attr("id");
-
-                        if (parent_id) {
-                            parent_id = parent_id.split("_")[1];
-                            var params = {
-                                    "a": "add_lp_item",
-                                    "id": id,
-                                    "parent_id": parent_id,
-                                    "previous_id": previous_id,
-                                    "type": type,
-                                    "title" : title
-                                };
-                            $.ajax({
-                                type: "GET",
-                                url: "'.$ajax_url.'",
-                                data: params,
-                                async: false,
-                                success: function(data) {
-                                    if (data == -1) {
-                                    } else {
-
-                                        $(".normal-message").hide();
-                                        $(ui.item).attr("id", data);
-                                        $(ui.item).addClass("lp_resource_element_new");
-                                        $(ui.item).find(".item_data").attr("style", "");
-                                        $(ui.item).addClass("record li_container");
-                                        $(ui.item).removeClass("lp_resource_element");
-                                        $(ui.item).removeClass("doc_resource");
-                                    }
-                                }
-                            });
-                        }
-                    }//
-                }//end receive
-            });
-        });
-        </script>';
+        $return = '';
 
         $is_allowed_to_edit = api_is_allowed_to_edit(null,true);
 
diff --git a/main/newscorm/lp_controller.php b/main/newscorm/lp_controller.php
index a2004f3da4..1e6f82dc3d 100644
--- a/main/newscorm/lp_controller.php
+++ b/main/newscorm/lp_controller.php
@@ -69,6 +69,165 @@ form .label {
     text-shadow:none;
 }
 </style>';
+$ajax_url = api_get_path(WEB_AJAX_PATH).'lp.ajax.php';
+$htmlHeadXtra[] = '
+<script>
+    /*
+    Script to manipuplate Learning Path items with Drag and drop
+     */
+    var newOrderData = "";
+    var lptree_debug = "";  // for debug
+    var lp_id_list = "";    // for debug
+
+    // uncomment for some debug display utility
+    /*
+    $(document).ready(function() {
+        buildLPtree_debug($("#lp_item_list"), 0, 0);
+        alert(lp_id_list+"\n\n"+lptree_debug);
+    });
+    */
+
+    function buildLPtree(in_elem, in_parent_id) {
+        var item_tag = in_elem.get(0).tagName;
+        var item_id =  in_elem.attr("id");
+        var parent_id = item_id;
+
+        if (item_tag == "LI" && item_id != undefined) {
+            // in_parent_id de la forme UL_x
+            newOrderData += item_id+"|"+get_UL_integer_id(in_parent_id)+"^";
+        }
+
+        in_elem.children().each(function () {
+            buildLPtree($(this), parent_id);
+        });
+    }
+
+    // same than buildLPtree with some text display for debug in string lptree_debug
+    function buildLPtree_debug(in_elem, in_lvl, in_parent_id) {
+        var item_tag = in_elem.get(0).tagName;
+        var item_id =  in_elem.attr("id");
+        var parent_id = item_id;
+
+        if (item_tag == "LI" && item_id != undefined) {
+            for (i=0; i < 4 * in_lvl; i++) {
+                lptree_debug += " ";
+            }
+            lptree_debug += " Lvl="+(in_lvl - 1)/2+" ("+item_tag+" "+item_id+" Fils de="+in_parent_id+") \n";
+            // in_parent_id de la forme UL_x
+            lp_id_list += item_id+"|"+get_UL_integer_id(in_parent_id)+"^";
+        }
+
+        in_elem.children().each(function () {
+            buildLPtree_debug($(this), in_lvl + 1, parent_id);
+        });
+    }
+
+    // return the interge part of an UL id
+    // (0 for lp_item_list)
+    function get_UL_integer_id(in_ul_id) {
+        in_parent_integer_id = in_ul_id;
+        in_parent_integer_id = in_parent_integer_id.replace("lp_item_list", "0");
+        in_parent_integer_id = in_parent_integer_id.replace("UL_", "");
+        return in_parent_integer_id;
+    }
+
+    $(function() {
+
+        $(".item_data").live("mouseover", function(event) {
+            $(".button_actions", this).show();
+        });
+
+        $(".item_data").live("mouseout", function() {
+            $(".button_actions",this).hide();
+        });
+
+        $(".button_actions").hide();
+
+        $( ".lp_resource" ).sortable({
+            items: ".lp_resource_element ",
+            handle: ".moved", //only the class "moved"
+            cursor: "move",
+            connectWith: "#lp_item_list",
+            placeholder: "ui-state-highlight", //defines the yellow highlight
+
+            start: function(event, ui) {
+                $(ui.item).css("width", "160px");
+                $(ui.item).find(".item_data").attr("style", "");
+
+            },
+            stop: function(event, ui) {
+                $(ui.item).css("width", "100%");
+            },
+        });
+
+        $("#lp_item_list").sortable({
+            items: "li",
+            handle: ".moved", //only the class "moved"
+            cursor: "move",
+            placeholder: "ui-state-highlight", //defines the yellow highlight
+
+            update: function(event, ui) {
+                buildLPtree($("#lp_item_list"), 0);
+                var order = "new_order="+ newOrderData + "&a=update_lp_item_order";
+
+                $.post(
+                    "'.$ajax_url.'",
+                    order,
+                    function(reponse){
+                        $("#message").html(reponse);
+                        order = "";
+                        newOrderData = "";
+                    }
+                );
+            },
+
+            receive: function(event, ui) {
+                var id = $(ui.item).attr("data_id");
+                var type = $(ui.item).attr("data_type");
+                var title = $(ui.item).attr("title");
+                processReceive = true;
+
+                if (ui.item.parent()[0]) {
+                    var parent_id = $(ui.item.parent()[0]).attr("id");
+                    var previous_id = $(ui.item.prev()).attr("id");
+
+                    if (parent_id) {
+                        parent_id = parent_id.split("_")[1];
+                        var params = {
+                            "a": "add_lp_item",
+                            "id": id,
+                            "parent_id": parent_id,
+                            "previous_id": previous_id,
+                            "type": type,
+                            "title" : title
+                        };
+                        $.ajax({
+                            type: "GET",
+                            url: "'.$ajax_url.'",
+                            data: params,
+                            async: false,
+                            success: function(data) {
+                                if (data == -1) {
+                                } else {
+                                    $(".normal-message").hide();
+                                    $(ui.item).attr("id", data);
+                                    $(ui.item).addClass("lp_resource_element_new");
+                                    $(ui.item).find(".item_data").attr("style", "");
+                                    $(ui.item).addClass("record li_container");
+                                    $(ui.item).removeClass("lp_resource_element");
+                                    $(ui.item).removeClass("doc_resource");
+                                }
+                            }
+                        });
+                    }
+                }//
+            }//end receive
+        });
+        processReceive = false;
+    });
+</script>
+';
+
 
 // Flag to allow for anonymous user - needs to be set before global.inc.php.
 $use_anonymous = true;

From f0504a01ad06329633331ef6eb1a8089a4f9bc5e Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Wed, 11 Sep 2013 16:26:49 +0200
Subject: [PATCH 15/65] Minor - format code

---
 main/newscorm/scorm.class.php | 41 +++++++++++++++++++++--------------
 1 file changed, 25 insertions(+), 16 deletions(-)

diff --git a/main/newscorm/scorm.class.php b/main/newscorm/scorm.class.php
index 0d220d819b..92df74970a 100644
--- a/main/newscorm/scorm.class.php
+++ b/main/newscorm/scorm.class.php
@@ -19,7 +19,8 @@ require_once 'scormResource.class.php';
  * Defines the "scorm" child of class "learnpath"
  * @package chamilo.learnpath
  */
-class scorm extends learnpath {
+class scorm extends learnpath
+{
     public $manifest = array();
     public $resources = array();
     public $resources_att = array();
@@ -41,7 +42,8 @@ class scorm extends learnpath {
      * @param	integer	Learnpath ID in DB
      * @param	integer	User ID
      */
-    function __construct($course_code = null, $resource_id = null, $user_id = null) {
+    function __construct($course_code = null, $resource_id = null, $user_id = null)
+    {
         if ($this->debug > 0) { error_log('New LP - scorm::scorm('.$course_code.','.$resource_id.','.$user_id.') - In scorm constructor', 0); }
         if (!empty($course_code) && !empty($resource_id) && !empty($user_id)) {
             parent::__construct($course_code, $resource_id, $user_id);
@@ -54,7 +56,8 @@ class scorm extends learnpath {
      * Opens a resource
      * @param	integer	Database ID of the resource
      */
-    function open($id) {
+    function open($id)
+    {
         if ($this->debug > 0) { error_log('New LP - scorm::open() - In scorm::open method', 0); }
         // redefine parent method
     }
@@ -72,11 +75,13 @@ class scorm extends learnpath {
      * @param	string	Path to the imsmanifest.xml file on the system. If not defined, uses the base path of the course's scorm dir
      * @return	array	Structured array representing the imsmanifest's contents
      */
-    function parse_manifest($file = '') {
+    function parse_manifest($file = '')
+    {
         if ($this->debug > 0) { error_log('In scorm::parse_manifest('.$file.')', 0); }
         if (empty($file)) {
             // Get the path of the imsmanifest file.
         }
+
         if (is_file($file) && is_readable($file) && ($xml = @file_get_contents($file))) {
 
             // Parsing using PHP5 DOMXML methods.
@@ -118,7 +123,7 @@ class scorm extends learnpath {
                             switch ($child->tagName) {
                                 case 'metadata':
                                     // Parse items from inside the <metadata> element.
-                                    $this->metadata = new scormMetadata('manifest',$child);
+                                    $this->metadata = new scormMetadata('manifest', $child);
                                     break;
                                 case 'organizations':
                                     // Contains the course structure - this element appears 1 and only 1 time in a package imsmanifest. It contains at least one 'organization' sub-element.
@@ -262,7 +267,8 @@ class scorm extends learnpath {
      * @param	string	Unique course code
      * @return	bool	Returns -1 on error
      */
-    function import_manifest($course_code, $use_max_score = 1) {
+    function import_manifest($course_code, $use_max_score = 1)
+    {
         if ($this->debug > 0) { error_log('New LP - Entered import_manifest('.$course_code.')', 0); }
         $course_info = api_get_course_info($course_code);
         $course_id = $course_info['real_id'];
@@ -323,7 +329,7 @@ class scorm extends learnpath {
                         $outdated_parent = array_pop($parents_stack);
                     }
                     $parent = array_pop($parents_stack); // Just save that value, then add it back.
-                    array_push($parents_stack,$parent);
+                    array_push($parents_stack, $parent);
                 }
                 $path = '';
                 $type = 'dir';
@@ -340,10 +346,12 @@ class scorm extends learnpath {
                 $level = $item['level'];
                 $field_add = '';
                 $value_add = '';
+
                 if (!empty($item['masteryscore'])) {
                     $field_add .= 'mastery_score, ';
                     $value_add .= $item['masteryscore'].',';
                 }
+
                 if (!empty($item['maxtimeallowed'])) {
                     $field_add .= 'max_time_allowed, ';
                     $value_add .= "'".$item['maxtimeallowed']."',";
@@ -354,14 +362,14 @@ class scorm extends learnpath {
                 $max_score = Database::escape_string($item['max_score']);
 
                 if ($max_score == 0 || is_null($max_score) || $max_score == '') {
-                    //If max score is not set The use_max_score parameter is check in order to use 100 (chamilo style) or '' (strict scorm)
+                    // If max score is not set The use_max_score parameter is check in order to use 100 (chamilo style) or '' (strict scorm)
                     if ($use_max_score) {
                         $max_score = "'100'";
                     } else {
                         $max_score = "NULL";
                     }
                 } else {
-                    //Otherwise save the max score
+                    // Otherwise save the max score.
                     $max_score = "'$max_score'";
                 }
 
@@ -373,9 +381,8 @@ class scorm extends learnpath {
 
                 $prereq = Database::escape_string($item['prerequisites']);
 
-                $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters) VALUES " .
-                        "($course_id, $lp_id, '$type','$identifier', '$title', '$path' , 0, $max_score, $value_add" .
-                        "$parent, $previous, 0, " .
+                $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters)
+                        VALUES ($course_id, $lp_id, '$type','$identifier', '$title', '$path' , 0, $max_score, $value_add $parent, $previous, 0, " .
                         "'$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."'," .
                         "'".$item['parameters']."'" .
                         ")";
@@ -397,7 +404,7 @@ class scorm extends learnpath {
 
                     $di = new ChamiloIndexer();
                     isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
-                    $di->connectDb(NULL, NULL, $lang);
+                    $di->connectDb(null, null, $lang);
                     $ic_slide = new IndexableChunk();
                     $ic_slide->addValue('title', $title);
                     $specific_fields = get_specific_field_list();
@@ -449,7 +456,8 @@ class scorm extends learnpath {
      * @param	string	Current path (optional)
      * @return string	Absolute path to the imsmanifest.xml file or empty string on error
      */
-    function import_local_package($file_path, $current_dir = '') {
+    function import_local_package($file_path, $current_dir = '')
+    {
         // TODO: Prepare info as given by the $_FILES[''] vector.
         $file_info = array();
         $file_info['tmp_name'] = $file_path;
@@ -463,7 +471,8 @@ class scorm extends learnpath {
      * @param	string	Zip file info as given by $_FILES['userFile']
      * @return	string	Absolute path to the imsmanifest.xml file or empty string on error
      */
-    function import_package($zip_file_info, $current_dir = '') {
+    function import_package($zip_file_info, $current_dir = '')
+    {
         if ($this->debug > 0) { error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method', 0); }
 
         $maxFilledSpace = DocumentManager :: get_course_quota();
@@ -595,7 +604,7 @@ class scorm extends learnpath {
 
             if ($dir = @opendir($course_sys_dir.$new_dir)) {
                 if ($this->debug >= 1) { error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0); }
-                while ($file=readdir($dir)) {
+                while ($file = readdir($dir)) {
                     if ($file != '.' && $file != '..') {
                         $filetype = 'file';
 

From 45c6d9e537fb8eafc2d14aa1d17cc56b0c197928 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Wed, 11 Sep 2013 16:55:21 +0200
Subject: [PATCH 16/65] Minor - format code

---
 main/newscorm/learnpathItem.class.php | 14 +++++----
 main/newscorm/lp_ajax_save_item.php   | 43 +++++++++++++++------------
 2 files changed, 33 insertions(+), 24 deletions(-)

diff --git a/main/newscorm/learnpathItem.class.php b/main/newscorm/learnpathItem.class.php
index 235631470d..f9eacc84c3 100644
--- a/main/newscorm/learnpathItem.class.php
+++ b/main/newscorm/learnpathItem.class.php
@@ -11,7 +11,8 @@
  * lp_item defines items belonging to a learnpath. Each item has a name, a score, a use time and additional
  * information that enables tracking a user's progress in a learning path
  */
-class learnpathItem {
+class learnpathItem
+{
 	public $attempt_id; // Also called "objectives" SCORM-wise.
 	public $audio; // The path to an audio file (stored in document/audio/).
 	public $children = array(); // Contains the ids of children items.
@@ -1844,7 +1845,8 @@ class learnpathItem {
 	 * @return  void
 	 * @todo //todo insert into lp_item_view if lp_view not exists
 	 */
-	public function set_lp_view($lp_view_id, $course_id = null) {
+	public function set_lp_view($lp_view_id, $course_id = null)
+    {
 	    if (empty($course_id)) {
 	        $course_id = api_get_course_int_id();
 	    } else {
@@ -1935,7 +1937,8 @@ class learnpathItem {
 	 * @param	float	Score
 	 * @return	boolean	True on success, false otherwise
 	 */
-	public function set_score($score) {
+	public function set_score($score)
+    {
         //$possible_status = array('not attempted','incomplete','completed','passed','failed','browsed');
         $debug = self::debug;
    		if ($debug > 0) { error_log('learnpathItem::set_score('.$score.')', 0); }
@@ -1944,7 +1947,7 @@ class learnpathItem {
    			$master = $this->get_mastery_score();
    			$current_status = $this->get_status(false);
 
-            //Fixes bug when SCORM doesn't send a mastery score even if they sent a score!
+            // Fixes bug when SCORM doesn't send a mastery score even if they sent a score!
             if ($master == -1) {
                 $master = $this->max_score;
             }
@@ -1989,7 +1992,8 @@ class learnpathItem {
 	 * @param	string	Status - must be one of the values defined in $this->possible_status
 	 * @return	boolean	True on success, false on error
 	 */
-	public function set_status($status) {
+	public function set_status($status)
+    {
    		if (self::debug > 0) { error_log('learnpathItem::set_status('.$status.')', 0); }
 	 	$found = false;
 	 	foreach ($this->possible_status  as $possible) {
diff --git a/main/newscorm/lp_ajax_save_item.php b/main/newscorm/lp_ajax_save_item.php
index 164c003ef6..359da10362 100644
--- a/main/newscorm/lp_ajax_save_item.php
+++ b/main/newscorm/lp_ajax_save_item.php
@@ -44,7 +44,8 @@ require_once 'aiccItem.class.php';
  * @param   array   Interactions array
  * @param   string  Core exit SCORM string
  */
-function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1, $min = -1, $status = '', $time = 0, $suspend = '', $location = '', $interactions = array(), $core_exit = 'none') {
+function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1, $min = -1, $status = '', $time = 0, $suspend = '', $location = '', $interactions = array(), $core_exit = 'none')
+{
     $return = null;
 
     if ($debug > 0) {
@@ -82,6 +83,8 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
     }
 
     $prereq_check = $mylp->prerequisites_match($item_id);
+
+    /** @var learnpathItem $mylpi */
     $mylpi = $mylp->items[$item_id];
 
     if (empty($mylpi)) {
@@ -91,14 +94,14 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
         return false;
     }
 
-    //This functions sets the $this->db_item_view_id variable needed in get_status() see BT#5069
+    // This functions sets the $this->db_item_view_id variable needed in get_status() see BT#5069
     $mylpi->set_lp_view($view_id);
 
     if ($prereq_check === true) {
         if ($debug > 1) { error_log('Prereq are check'); }
 
         // Launch the prerequisites check and set error if needed
-        if (isset($max) && $max != -1)  {
+        if (isset($max) && $max != -1) {
             $mylpi->max_score = $max;
             $mylpi->set_max_score($max);
             if ($debug > 1) { error_log("Setting max_score: $max"); }
@@ -109,7 +112,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
             if ($debug > 1) { error_log("Setting min_score: $min"); }
         }
 
-        //set_score function already saves the status
+        // set_score function already saves the status
         if (isset($score) && $score != -1) {
             if ($debug > 1) { error_log('Calling set_score('.$score.')', 0); }
             if ($debug > 1) { error_log('set_score changes the status to failed/passed if mastery score is provided', 0); }
@@ -118,7 +121,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
         } else {
             if ($debug > 1) { error_log("Score not updated"); }
 
-            //Default behaviour
+            // Default behaviour
             if (isset($status) && $status != '' && $status != 'undefined') {
                 if ($debug > 1) { error_log('Calling set_status('.$status.')', 0); }
                 $mylpi->set_status($status);
@@ -266,6 +269,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
 
     Session::write('lpobject', serialize($mylp));
     if ($debug > 0) { error_log('---------------- lp_ajax_save_item.php : save_item end ----- '); }
+
     return $return;
 }
 
@@ -274,7 +278,7 @@ if (isset($_REQUEST['interact'])) {
     if (is_array($_REQUEST['interact'])) {
         foreach ($_REQUEST['interact'] as $idx => $interac) {
             $interactions[$idx] = split(',', substr($interac, 1, -1));
-            if(!isset($interactions[$idx][7])){ // Make sure there are 7 elements.
+            if (!isset($interactions[$idx][7])) { // Make sure there are 7 elements.
                 $interactions[$idx][7] = '';
             }
         }
@@ -282,16 +286,17 @@ if (isset($_REQUEST['interact'])) {
 }
 
 echo save_item(
-            (!empty($_REQUEST['lid'])?$_REQUEST['lid']:null),
-            (!empty($_REQUEST['uid'])?$_REQUEST['uid']:null),
-            (!empty($_REQUEST['vid'])?$_REQUEST['vid']:null),
-            (!empty($_REQUEST['iid'])?$_REQUEST['iid']:null),
-            (!empty($_REQUEST['s'])?$_REQUEST['s']:null),
-            (!empty($_REQUEST['max'])?$_REQUEST['max']:null),
-            (!empty($_REQUEST['min'])?$_REQUEST['min']:null),
-            (!empty($_REQUEST['status'])?$_REQUEST['status']:null),
-            (!empty($_REQUEST['t'])?$_REQUEST['t']:null),
-            (!empty($_REQUEST['suspend'])?$_REQUEST['suspend']:null),
-            (!empty($_REQUEST['loc'])?$_REQUEST['loc']:null),
-            $interactions,
-            (!empty($_REQUEST['core_exit'])?$_REQUEST['core_exit']:''));
\ No newline at end of file
+    (!empty($_REQUEST['lid'])?$_REQUEST['lid']:null),
+    (!empty($_REQUEST['uid'])?$_REQUEST['uid']:null),
+    (!empty($_REQUEST['vid'])?$_REQUEST['vid']:null),
+    (!empty($_REQUEST['iid'])?$_REQUEST['iid']:null),
+    (!empty($_REQUEST['s'])?$_REQUEST['s']:null),
+    (!empty($_REQUEST['max'])?$_REQUEST['max']:null),
+    (!empty($_REQUEST['min'])?$_REQUEST['min']:null),
+    (!empty($_REQUEST['status'])?$_REQUEST['status']:null),
+    (!empty($_REQUEST['t'])?$_REQUEST['t']:null),
+    (!empty($_REQUEST['suspend'])?$_REQUEST['suspend']:null),
+    (!empty($_REQUEST['loc'])?$_REQUEST['loc']:null),
+    $interactions,
+    (!empty($_REQUEST['core_exit'])?$_REQUEST['core_exit']:'')
+);

From fc02e40582f6ef059a8125f0fe9b9e579db7b37b Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 12 Sep 2013 11:10:34 +0200
Subject: [PATCH 17/65] Minor - format code

---
 main/admin/course_edit.php | 64 +++++++++++++++-----------------------
 1 file changed, 25 insertions(+), 39 deletions(-)

diff --git a/main/admin/course_edit.php b/main/admin/course_edit.php
index f0ca8518d9..1e8a74af0b 100644
--- a/main/admin/course_edit.php
+++ b/main/admin/course_edit.php
@@ -33,7 +33,7 @@ $sql = "SELECT * FROM $course_table WHERE code='".Database::escape_string($cours
 $result = Database::query($sql);
 if (Database::num_rows($result) != 1) {
 	header('Location: course_list.php');
-	exit ();
+	exit();
 }
 $course = Database::fetch_array($result,'ASSOC');
 
@@ -44,7 +44,7 @@ $sql = "SELECT user.user_id,lastname,firstname FROM $table_user as user,$table_c
 $res = Database::query($sql);
 $course_teachers = array();
 while ($obj = Database::fetch_object($res)) {
-	$course_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
+    $course_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 }
 
 // Get all possible teachers without the course teachers
@@ -54,34 +54,32 @@ if ($_configuration['multiple_access_urls']) {
 			INNER JOIN $access_url_rel_user_table url_rel_user
 			ON (u.user_id=url_rel_user.user_id) WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1".$order_clause;
 } else {
-
 	$sql = "SELECT user_id,lastname,firstname FROM $table_user WHERE status='1'".$order_clause;
 }
 
 $res = Database::query($sql);
 $teachers = array();
 
-
 $platform_teachers[0] = '-- '.get_lang('NoManager').' --';
 while ($obj = Database::fetch_object($res)) {
 
-	if (!array_key_exists($obj->user_id,$course_teachers)) {
-		$teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
-	}
+    if (!array_key_exists($obj->user_id,$course_teachers)) {
+        $teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
+    }
 
-	if ($course['tutor_name'] == $course_teachers[$obj->user_id]) {
-		$course['tutor_name'] = $obj->user_id;
-	}
-	//We add in the array platform teachers
-	$platform_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
+    if ($course['tutor_name'] == $course_teachers[$obj->user_id]) {
+        $course['tutor_name'] = $obj->user_id;
+    }
+    //We add in the array platform teachers
+    $platform_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 }
 
 //Case where there is no teacher in the course
-if (count($course_teachers)==0) {
-	$sql='SELECT tutor_name FROM '.$course_table.' WHERE code="'.$course_code.'"';
-	$res = Database::query($sql);
-	$tutor_name=Database::result($res,0,0);
-	$course['tutor_name']=array_search($tutor_name,$platform_teachers);
+if (count($course_teachers) == 0) {
+    $sql='SELECT tutor_name FROM '.$course_table.' WHERE code="'.$course_code.'"';
+    $res = Database::query($sql);
+    $tutor_name=Database::result($res,0,0);
+    $course['tutor_name']=array_search($tutor_name,$platform_teachers);
 }
 
 // Build the form
@@ -103,13 +101,6 @@ $form->add_textfield('visual_code', array(get_lang('VisualCode'), get_lang('Only
 $form->applyFilter('visual_code','strtoupper');
 $form->applyFilter('visual_code','html_filter');
 
-//$form->addElement('text', tutor_name', get_lang('CourseTitular'));
-
-//$form->addElement('select', 'tutor_name', get_lang('CourseTitular'), $platform_teachers, array('style'=>'width:350px','id'=>'tutor_name_id', 'class'=>'chzn-select'));
-//$form->applyFilter('tutor_name','html_filter');
-
-//$form->addElement('select', 'course_teachers', get_lang('CourseTeachers'), $teachers, 'multiple=multiple size="4" style="width: 150px;"');
-
 $group=array();
 $group[] = $form->createElement('select', 'platform_teachers', '', $teachers,        ' id="platform_teachers" multiple=multiple size="4" style="width:300px;"');
 $group[] = $form->createElement('select', 'course_teachers', '',   $course_teachers, ' id="course_teachers" multiple=multiple size="4" style="width:300px;"');
@@ -135,20 +126,18 @@ $form -> addGroup($group,'group',get_lang('CourseTeachers'),'</td><td width="80"
 		'<input class="arrowr" style="width:30px;height:30px;padding-right:12px" type="button" onclick="moveItem(document.getElementById(\'platform_teachers\'), document.getElementById(\'course_teachers\'))" ><br><br>' .
 		'<input class="arrowl" style="width:30px;height:30px;padding-left:13px" type="button" onclick="moveItem(document.getElementById(\'course_teachers\'), document.getElementById(\'platform_teachers\'))" ></td><td>');
 
-
 $categories_select = $form->addElement('select', 'category_code', get_lang('CourseFaculty'), $categories , array('style'=>'width:350px','id'=>'category_code_id', 'class'=>'chzn-select'));
 $categories_select->addOption('-','');
 CourseManager::select_and_sort_categories($categories_select);
 
-$form->add_textfield( 'department_name', get_lang('CourseDepartment'), false,array ('size' => '60'));
+$form->add_textfield('department_name', get_lang('CourseDepartment'), false,array ('size' => '60'));
 $form->applyFilter('department_name','html_filter');
 $form->applyFilter('department_name','trim');
 
-$form->add_textfield( 'department_url', get_lang('CourseDepartmentURL'),false, array ('size' => '60'));
+$form->add_textfield('department_url', get_lang('CourseDepartmentURL'),false, array ('size' => '60'));
 $form->applyFilter('department_url','html_filter');
 $form->applyFilter('department_url','trim');
 
-
 $form->addElement('select_language', 'course_language', get_lang('CourseLanguage'));
 $form->applyFilter('select_language','html_filter');
 
@@ -163,13 +152,12 @@ $form->addGroup($group,'', get_lang('CourseAccess'), '<br />');
 $group = array();
 $group[]= $form->createElement('radio', 'subscribe', get_lang('Subscription'), get_lang('Allowed'), 1);
 $group[]= $form->createElement('radio', 'subscribe', null, get_lang('Denied'), 0);
-$form->addGroup($group,'', get_lang('Subscription'), '<br />');
+$form->addGroup($group, '', get_lang('Subscription'), '<br />');
 
 $group = array();
 $group[]= $form->createElement('radio', 'unsubscribe', get_lang('Unsubscription'), get_lang('AllowedToUnsubscribe'), 1);
 $group[]= $form->createElement('radio', 'unsubscribe', null, get_lang('NotAllowedToUnsubscribe'), 0);
-$form->addGroup($group,'', get_lang('Unsubscription'), '<br />');
-
+$form->addGroup($group, '', get_lang('Unsubscription'), '<br />');
 
 $form->addElement('text', 'disk_quota', array(get_lang('CourseQuota'), null, get_lang('MB')));
 $form->addRule('disk_quota', get_lang('ThisFieldIsRequired'), 'required');
@@ -194,18 +182,17 @@ $form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'),
 //$course['disk_quota'] = round($course['disk_quota']/1024/1024, 1);
 $course['disk_quota'] = round(DocumentManager::get_course_quota($course_code) /1024/1024, 1);
 $course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);
-
 $course['real_code'] = $course['code'];
 
 $form->setDefaults($course);
 
 // Validate form
 if ($form->validate()) {
-	$course = $form->getSubmitValues();
-	$dbName = $_POST['dbName'];
-	$course_code = $course['code'];
-	$visual_code = $course['visual_code'];
-	$visual_code = generate_course_code($visual_code);
+    $course = $form->getSubmitValues();
+    $dbName = $_POST['dbName'];
+    $course_code = $course['code'];
+    $visual_code = $course['visual_code'];
+    $visual_code = generate_course_code($visual_code);
 
     // Check if the visual code is already used by *another* course
     $visual_code_is_used = false;
@@ -346,8 +333,7 @@ function valide() {
 	document.update_course.submit();
 }
 </script>";
-//api_display_tool_title($tool_name);
 // Display the form
 $form->display();
-/* FOOTER */
+
 Display :: display_footer();

From e39ec8cb083bc606a3e9dc34f560f7e5b1bb0ae1 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 12 Sep 2013 11:49:10 +0200
Subject: [PATCH 18/65] course_edit.php page has an option to add/remove
 teachers in all course session coaches.

---
 main/admin/course_edit.php          | 15 ++++++++++-----
 main/inc/lib/course.lib.php         | 30 ++++++++++++++++++++++++++++-
 main/inc/lib/sessionmanager.lib.php | 20 ++++++++++++++++++-
 3 files changed, 58 insertions(+), 7 deletions(-)

diff --git a/main/admin/course_edit.php b/main/admin/course_edit.php
index 1e8a74af0b..554d6d3073 100644
--- a/main/admin/course_edit.php
+++ b/main/admin/course_edit.php
@@ -121,13 +121,15 @@ $element_template = <<<EOT
 EOT;
 
 $renderer = $form->defaultRenderer();
-$renderer -> setElementTemplate($element_template, 'group');
-$form -> addGroup($group,'group',get_lang('CourseTeachers'),'</td><td width="80" align="center">'.
+$renderer->setElementTemplate($element_template, 'group');
+$form->addGroup($group,'group',get_lang('CourseTeachers'),'</td><td width="80" align="center">'.
 		'<input class="arrowr" style="width:30px;height:30px;padding-right:12px" type="button" onclick="moveItem(document.getElementById(\'platform_teachers\'), document.getElementById(\'course_teachers\'))" ><br><br>' .
 		'<input class="arrowl" style="width:30px;height:30px;padding-left:13px" type="button" onclick="moveItem(document.getElementById(\'course_teachers\'), document.getElementById(\'platform_teachers\'))" ></td><td>');
 
+$form->addElement('checkbox', 'add_teachers_to_sessions', array(null, null, get_lang('TeachersWillBeAddedAsCoachInAllCourseSessions')));
+
 $categories_select = $form->addElement('select', 'category_code', get_lang('CourseFaculty'), $categories , array('style'=>'width:350px','id'=>'category_code_id', 'class'=>'chzn-select'));
-$categories_select->addOption('-','');
+$categories_select->addOption('-', '');
 CourseManager::select_and_sort_categories($categories_select);
 
 $form->add_textfield('department_name', get_lang('CourseDepartment'), false,array ('size' => '60'));
@@ -215,7 +217,9 @@ if ($form->validate()) {
 			$extras[substr($key,6)] = $value;
 		}
 		if (substr($key,0,7)=='_extra_') {
-			if(!array_key_exists(substr($key,7), $extras)) $extras[substr($key,7)] = $value;
+			if (!array_key_exists(substr($key,7), $extras)) {
+                $extras[substr($key,7)] = $value;
+            }
 		}
     }
 
@@ -260,7 +264,8 @@ if ($form->validate()) {
 		}
 	}
 
-    CourseManager::updateTeachers($course_code, $teachers);
+
+    CourseManager::updateTeachers($course_code, $teachers, $course['add_teachers_to_sessions']);
 
 	$sql = "INSERT IGNORE INTO ".$course_user_table . " SET
 				course_code = '".Database::escape_string($course_code). "',
diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php
index f9020fb692..f33900bcfa 100644
--- a/main/inc/lib/course.lib.php
+++ b/main/inc/lib/course.lib.php
@@ -3964,8 +3964,15 @@ class CourseManager {
         return $options;
     }
 
-    function updateTeachers($course_code, $teachers)
+    /**
+     * @param string $course_code
+     * @param array $teachers
+     * @param bool $editTeacherInSessions
+     * @return bool
+     */
+    public static function updateTeachers($course_code, $teachers, $editTeacherInSessions = false)
     {
+
         if (empty($teachers)) {
             return false;
         }
@@ -3982,6 +3989,7 @@ class CourseManager {
                 $cond.= " AND user_id <> '".$key."'";
             }
         }
+
         $sql = 'DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
         Database::query($sql);
 
@@ -4007,5 +4015,25 @@ class CourseManager {
                 Database::query($sql);
             }
         }
+
+
+        if ($editTeacherInSessions) {
+            $sessions = SessionManager::get_session_by_course($course_code);
+            if (!empty($sessions)) {
+                foreach ($sessions as $session) {
+                    $alreadyAddedTeachers = SessionManager::getCoachByCourseSession($session['id'], $course_code);
+                    foreach ($teachers as $userId) {
+                        SessionManager::set_coach_to_course_session($userId, $session['id'], $course_code);
+                    }
+
+                    $teachersToDelete = array_diff($alreadyAddedTeachers, $teachers);
+                    if (!empty($teachersToDelete)) {
+                        foreach ($teachersToDelete as $userId) {
+                            SessionManager::set_coach_to_course_session($userId, $session['id'], $course_code, true);
+                        }
+                    }
+                }
+            }
+        }
     }
 }
diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index a3fb8982a0..d5c5515aa3 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -1278,7 +1278,7 @@ class SessionManager
 	 * @param bool  	- optional, if is true the user don't be a coach now, otherwise it'll assign a coach
 	 * @return bool true if there are affected rows, otherwise false
 	 */
-	public static function set_coach_to_course_session($user_id, $session_id = 0, $course_code = '',$nocoach = false) {
+	public static function set_coach_to_course_session($user_id, $session_id = 0, $course_code = '', $nocoach = false) {
 
 		// Definition of variables
 		$user_id = intval($user_id);
@@ -2160,4 +2160,22 @@ class SessionManager
             'session_counter' =>  $session_counter
         );
     }
+
+    public static function getCoachByCourseSession($sessionId, $courseCode)
+    {
+        $tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $sessionId = intval($sessionId);
+        $courseCode = Database::escape_string($courseCode);
+
+        $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$sessionId' AND course_code = '$courseCode' AND status = 2";
+        $rs_coachs = Database::query($sql);
+
+        $coachs_course_session = array();
+        if (Database::num_rows($rs_coachs) > 0){
+            while ($row_coachs = Database::fetch_row($rs_coachs)) {
+                $coachs_course_session[] = $row_coachs[0];
+            }
+        }
+        return $coachs_course_session;
+    }
 }

From 764d8c64b4570591f7f27f1c8e6bb4040dd4a392 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 12 Sep 2013 12:21:12 +0200
Subject: [PATCH 19/65] Adding session.description only when importing csv
 files (require DB change) by default this option is disabled. see BT#6674 no
 admin UI was added

---
 main/inc/lib/sessionmanager.lib.php | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index d5c5515aa3..085ac92efc 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -1906,6 +1906,12 @@ class SessionManager
                 $date_end               = $enreg['DateEnd'];
                 $visibility             = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
                 $session_category_id    = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
+                $sessionDescription    = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
+
+                $extraSessionParameters = null;
+                if (!empty($sessionDescription)) {
+                    $extraSessionParameters = ' , description = '.Database::escape_string($sessionDescription);
+                }
 
                 // Searching a general coach.
                 if (!empty($enreg['Coach'])) {
@@ -1947,13 +1953,12 @@ class SessionManager
                             date_end = '$date_end',
                             visibility = '$visibility',
                             session_category_id = '$session_category_id',
-                            session_admin_id=".intval($defaultUserId).$extraParameters;
+                            session_admin_id=".intval($defaultUserId).$extraParameters.$extraSessionParameters;
                     Database::query($sql_session);
                     $session_id = Database::insert_id();
 
                     if ($debug) {
                         if ($session_id) {
-
                             foreach ($enreg as $key => $value) {
                                 if (substr($key, 0, 6) == 'extra_') { //an extra field
                                     self::update_session_extra_field_value($session_id, substr($key, 6), $value);
@@ -1990,7 +1995,7 @@ class SessionManager
                                 date_start = '$date_start',
                                 date_end = '$date_end',
                                 visibility = '$visibility',
-                                session_category_id = '$session_category_id' ".$extraParameters;
+                                session_category_id = '$session_category_id' ".$extraParameters.$extraSessionParameters;
 
                         Database::query($sql_session);
 
@@ -2021,12 +2026,17 @@ class SessionManager
                             'session_category_id' => $session_category_id
                         );
 
+                        if (!empty($sessionDescription)) {
+                            $params['description'] = $sessionDescription;
+                        }
+
                         if (!empty($fieldsToAvoidUpdate)) {
                             foreach ($fieldsToAvoidUpdate as $field) {
                                 unset($params[$field]);
                             }
                         }
 
+
                         if (isset($sessionId) && !empty($sessionId)) {
                             // The session already exists, update it then.
                             Database::update($tbl_session, $params, array('id = ?' => $sessionId));

From 0608bb9386d7d1eb97720d4df54715e3c169722c Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 12 Sep 2013 13:08:57 +0200
Subject: [PATCH 20/65] Adding session.description field in userportal requires
 a DB change. Code is harmless if the field does not exists.

---
 main/inc/lib/course.lib.php     |  3 +++
 main/inc/lib/display.lib.php    | 19 ++++++++++++-------
 main/inc/lib/userportal.lib.php |  7 +++++--
 3 files changed, 20 insertions(+), 9 deletions(-)

diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php
index f33900bcfa..5ce1905689 100644
--- a/main/inc/lib/course.lib.php
+++ b/main/inc/lib/course.lib.php
@@ -2899,6 +2899,9 @@ class CourseManager {
                     $html .= '<div class="span6 '.$param_class.'">';
                         $html .='<h3>'.$params['title'].$notifications.'</h3> ';
 
+                        if (isset($params['description'])) {
+                            $html .= '<p>'.$params['description'].'</p>';
+                        }
                         if (!empty($params['subtitle'])) {
                             $html .= '<small>'.$params['subtitle'].'</small>';
                         }
diff --git a/main/inc/lib/display.lib.php b/main/inc/lib/display.lib.php
index 2a6a0ed50b..3eac1e95ce 100644
--- a/main/inc/lib/display.lib.php
+++ b/main/inc/lib/display.lib.php
@@ -1239,20 +1239,21 @@ class Display {
             $tbl_session            = Database :: get_main_table(TABLE_MAIN_SESSION);
             $active = false;
             // Request for the name of the general coach
-            $sql ='SELECT tu.lastname, tu.firstname, ts.name, ts.date_start, ts.date_end, ts.session_category_id
+            $sql ='SELECT tu.lastname, tu.firstname, ts.*
                     FROM '.$tbl_session.' ts  LEFT JOIN '.$main_user_table .' tu ON ts.id_coach = tu.user_id
-                    WHERE ts.id='.intval($session_id);
+                    WHERE ts.id = '.intval($session_id);
             $rs = Database::query($sql);
-            $session_info = Database::store_result($rs);
+            $session_info = Database::store_result($rs, 'ASSOC');
             $session_info = $session_info[0];
+
             $session = array();
-            $session['title'] = $session_info[2];
+            $session['title'] = $session_info['name'];
             $session['coach'] = '';
             $session['dates'] =  '';
 
             if ($session_info['date_end'] == '0000-00-00' && $session_info['date_start'] == '0000-00-00') {
                 if (api_get_setting('show_session_coach') === 'true') {
-                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info[1], $session_info[0]);
+                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info['firstname'], $session_info['lastname']);
                 }
                 $active = true;
             } else {
@@ -1279,12 +1280,16 @@ class Display {
                 }
 
                 if ( api_get_setting('show_session_coach') === 'true' ) {
-                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info[1], $session_info[0]);
+                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info['firstname'], $session_info['lastname']);
                 }
                 $active = ($date_start <= $now && $date_end >= $now);
             }
             $session['active'] = $active;
-            $session['session_category_id'] = $session_info[5];
+            $session['session_category_id'] = $session_info['session_category_id'];
+
+            if (isset($session_info['description'])) {
+                $session['description'] = $session_info['description'];
+            }
             $output = $session;
         }
         return $output;
diff --git a/main/inc/lib/userportal.lib.php b/main/inc/lib/userportal.lib.php
index 5186682673..5caabf6468 100644
--- a/main/inc/lib/userportal.lib.php
+++ b/main/inc/lib/userportal.lib.php
@@ -1016,8 +1016,10 @@ class IndexManager {
                             }
 
                             if (api_get_setting('hide_courses_in_sessions') == 'false') {
-                            //	$params['extra'] .=  $html_courses_session;
+                                // $params['extra'] .=  $html_courses_session;
                             }
+
+                            $params['description'] =  isset($session_box['description']) ? $session_box['description'] : null;
                             $sessions_with_no_category .= CourseManager::course_item_parent(CourseManager::course_item_html($params, true), $html_courses_session);
                         }
                     }
@@ -1085,12 +1087,12 @@ class IndexManager {
                             }
 
                             $params['title'] .=  $session_link;
-
                             $params['subtitle'] =  (!empty($session_box['coach']) ? $session_box['coach'].' | ' : '').$session_box['dates'];
 
                             if (api_is_platform_admin()) {
                                 $params['right_actions'] .=  '<a href="'.api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session='.$session_id.'">'.Display::return_icon('edit.png', get_lang('Edit'), array('align' => 'absmiddle'), ICON_SIZE_SMALL).'</a>';
                             }
+
                             $html_sessions .= CourseManager::course_item_html($params, true).$html_courses_session;
                         }
                     }
@@ -1122,6 +1124,7 @@ class IndexManager {
                                 $params['subtitle'] = get_lang('Until').' '.$session_category_end_date;
                             }
                         }
+
                         $sessions_with_category .= CourseManager::course_item_parent(CourseManager::course_item_html($params, true), $html_sessions);
                     }
 

From be51a5fb6c0092df963ecf7716f108dc97a59189 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 12 Sep 2013 16:12:22 +0200
Subject: [PATCH 21/65] Allow username update see BT#6369

---
 main/cron/import_csv.php | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/main/cron/import_csv.php b/main/cron/import_csv.php
index dcf99b48aa..9e8d6bce2e 100644
--- a/main/cron/import_csv.php
+++ b/main/cron/import_csv.php
@@ -349,7 +349,7 @@ class ImportCsv
         /*
          * Another users import.
         Unique identifier: official code and username . ok
-        Username and password should never get updated. ok
+        Password should never get updated. ok
         If an update should need to occur (because it changed in the .csv), we’ll want that logged. We will handle this manually in that case.
         All other fields should be updateable, though passwords should of course not get updated. ok
         If a user gets deleted (not there anymore),
@@ -440,7 +440,7 @@ class ImportCsv
                         $userInfo['user_id'],
                         $row['firstname'], // <<-- changed
                         $row['lastname'],  // <<-- changed
-                        $userInfo['username'],
+                        $row['username'],  // <<-- changed
                         null, //$password = null,
                         $auth_source = null,
                         $userInfo['email'],
@@ -460,6 +460,9 @@ class ImportCsv
                     );
 
                     if ($result) {
+                        if ($row['username'] != $userInfo['user_id']) {
+                            $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
+                        }
                         foreach ($row as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') { //an extra field
                                 UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);

From 55ccffd14e659eb90b56bec26f1bd507e2e32b7a Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 13:05:19 +0200
Subject: [PATCH 22/65] Fixing error message

---
 main/cron/import_csv.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/main/cron/import_csv.php b/main/cron/import_csv.php
index 9e8d6bce2e..ac3dbcb40c 100644
--- a/main/cron/import_csv.php
+++ b/main/cron/import_csv.php
@@ -460,7 +460,7 @@ class ImportCsv
                     );
 
                     if ($result) {
-                        if ($row['username'] != $userInfo['user_id']) {
+                        if ($row['username'] != $userInfo['username']) {
                             $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
                         }
                         foreach ($row as $key => $value) {

From 6d7b8a2907589fcad863ff4ef02751e703340e04 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 15:05:10 +0200
Subject: [PATCH 23/65] Fixing session_list search query

---
 main/admin/session_list.php         |  2 +-
 main/inc/lib/sessionmanager.lib.php | 26 +++++++++++++-------------
 2 files changed, 14 insertions(+), 14 deletions(-)

diff --git a/main/admin/session_list.php b/main/admin/session_list.php
index 95e4bb9dfc..d7b9ad92ab 100644
--- a/main/admin/session_list.php
+++ b/main/admin/session_list.php
@@ -59,7 +59,7 @@ $columns        = array(get_lang('Name'), get_lang('NumberOfCourses'), get_lang(
 //$activeurl = '?sidx=session_active';
 //Column config
 $column_model   = array(
-    array('name'=>'name',           'index'=>'name',          'width'=>'160',  'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
+    array('name'=>'name',           'index'=>'s.name',        'width'=>'160',  'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
     array('name'=>'nbr_courses',    'index'=>'nbr_courses',   'width'=>'30',   'align'=>'left', 'search' => 'true'),
     array('name'=>'nbr_users',      'index'=>'nbr_users',     'width'=>'30',   'align'=>'left', 'search' => 'true'),
     array('name'=>'category_name',  'index'=>'category_name', 'width'=>'70',   'align'=>'left', 'search' => 'true'),
diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 085ac92efc..7e4519cb6c 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -229,7 +229,7 @@ class SessionManager
 		$tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 		$tbl_user               = Database::get_main_table(TABLE_MAIN_USER);
 
-		$where = 'WHERE 1=1 ';
+		$where = 'HAVING 1=1 ';
 		$user_id = api_get_user_id();
 
 		if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
@@ -273,10 +273,19 @@ class SessionManager
             $limit = " LIMIT ".$options['limit'];
         }
 
+        if (!empty($options['where'])) {
+		   $where .= ' AND '.$options['where'];
+		}
+
+        $order = null;
+        if (!empty($options['order'])) {
+            $order = " ORDER BY ".$options['order'];
+        }
+
 		$query = "$select FROM $tbl_session s
 				LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
 				LEFT JOIN $tbl_user u ON s.id_coach = u.user_id
-                $where $limit";
+                $where $order $limit";
 
 		global $_configuration;
 		if ($_configuration['multiple_access_urls']) {
@@ -289,27 +298,18 @@ class SessionManager
                                LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                                INNER JOIN $tbl_user u ON s.id_coach = u.user_id
                                INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
-				 $where $limit";
+				 $where $order $limit";
 			}
 		}
 
 		$query .= ") AS session_table";
 
-		if (!empty($options['where'])) {
-		   $query .= ' WHERE '.$options['where'];
-		}
-
-        if (!empty($options['order'])) {
-            $query .= " ORDER BY ".$options['order'];
-        }
-
 		$result = Database::query($query);
 		$formatted_sessions = array();
 		if (Database::num_rows($result)) {
-			$sessions   = Database::store_result($result);
+			$sessions = Database::store_result($result);
 			foreach ($sessions as $session) {
 				$session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
-
 				$session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
 
 				if ($session['date_start'] == '0000-00-00' && $session['date_end'] == '0000-00-00') {

From fb51cb0f1144d2fc93b7746369c3c2f2b87b558a Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 15:18:45 +0200
Subject: [PATCH 24/65] Adding trim when looking for usernames.

---
 main/inc/lib/sessionmanager.lib.php | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 7e4519cb6c..86679d0339 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -2036,7 +2036,6 @@ class SessionManager
                             }
                         }
 
-
                         if (isset($sessionId) && !empty($sessionId)) {
                             // The session already exists, update it then.
                             Database::update($tbl_session, $params, array('id = ?' => $sessionId));
@@ -2112,6 +2111,7 @@ class SessionManager
                         // Adding coaches to session course user
                         if (!empty($course_coaches)) {
                             foreach ($course_coaches as $course_coach) {
+                                $course_coach = trim($course_coach);
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
@@ -2134,6 +2134,7 @@ class SessionManager
                         // Adding the relationship "Session - Course - User".
 
                         foreach ($course_users as $user) {
+                            $user = trim($user);
                             $user_id = UserManager::get_user_id_from_username($user);
 
                             if ($user_id !== false) {

From a475e6301c5a07be062ab7aac5aea920b153d98b Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 15:28:32 +0200
Subject: [PATCH 25/65] Allow multiple teachers when importing csv see BT#6449

---
 main/cron/import_csv.php | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/main/cron/import_csv.php b/main/cron/import_csv.php
index ac3dbcb40c..a8c382f667 100644
--- a/main/cron/import_csv.php
+++ b/main/cron/import_csv.php
@@ -212,9 +212,15 @@ class ImportCsv
 
         $row['teachers'] = array();
         if (isset($row['Teacher']) && !empty($row['Teacher'])) {
-            $userInfo = api_get_user_info_from_username($row['Teacher']);
-            if (!empty($userInfo)) {
-                $row['teachers'] = $userInfo['user_id'];
+            $teachers = explode(',', $row['Teacher']);
+            if (!empty($teachers)) {
+                foreach ($teachers as $teacherUserName) {
+                    $teacherUserName = trim($teacherUserName);
+                    $userInfo = api_get_user_info_from_username($teacherUserName);
+                    if (!empty($userInfo)) {
+                        $row['teachers'][] = $userInfo['user_id'];
+                    }
+                }
             }
         }
 
@@ -506,7 +512,7 @@ class ImportCsv
                     $params['wanted_code']          = $row['course_code'];
                     $params['course_category']      = $row['course_category'];
                     $params['course_language']      = $row['language'];
-                    $params['teachers']             = $row['teachers'];
+                    $params['teachers'] = $row['teachers'];
 
                     $courseInfo = CourseManager::create_course($params);
 
@@ -658,13 +664,13 @@ if (!is_array($emails)) {
 }
 $subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
 $from = api_get_setting('emailAdministrator');
-
+/*
 if (!empty($emails)) {
     foreach ($emails as $email) {
         $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
         $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
     }
-}
+}*/
 
 $stream = new StreamHandler(api_get_path(SYS_ARCHIVE_PATH).'import_csv.log', $minLevel);
 $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));

From b63cd0ff28fa1605b958ac6ea7f65f58cf183129 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 15:54:11 +0200
Subject: [PATCH 26/65] Fixing query

---
 main/inc/lib/sessionmanager.lib.php | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 86679d0339..cf09ba5fde 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -292,12 +292,11 @@ class SessionManager
 			$table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1) {
-				$where.= " AND ar.access_url_id = $access_url_id ";
 				$query = " $select
                            FROM $tbl_session s
                                LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                                INNER JOIN $tbl_user u ON s.id_coach = u.user_id
-                               INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
+                               INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id AND ar.access_url_id = $access_url_id
 				 $where $order $limit";
 			}
 		}

From 3ff954fa55e5429c8c859ed890298bc863c5704e Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 16:18:00 +0200
Subject: [PATCH 27/65] Minor - format code

---
 main/admin/session_edit.php | 19 +++++--------------
 1 file changed, 5 insertions(+), 14 deletions(-)

diff --git a/main/admin/session_edit.php b/main/admin/session_edit.php
index 9023c2f7cd..9ecc33abcb 100644
--- a/main/admin/session_edit.php
+++ b/main/admin/session_edit.php
@@ -16,8 +16,6 @@ require_once '../inc/global.inc.php';
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 
-
-
 $formSent = 0;
 
 // Database Table Definitions
@@ -37,9 +35,7 @@ if (!$infos = Database::fetch_array($result)) {
     exit();
 }
 
-$id_coach   = $infos['id_coach'];
-
-
+$id_coach = $infos['id_coach'];
 
 $tool_name = get_lang('EditSession');
 
@@ -52,7 +48,7 @@ list($year_end,$month_end,$day_end)         = explode('-',$infos['date_end']);
 
 $end_year_disabled = $end_month_disabled = $end_day_disabled = '';
 
-if ($_POST['formSent']) {
+if (isset($_POST['formSent']) && $_POST['formSent']) {
 	$formSent = 1;
 
 	$name                  = $_POST['name'];
@@ -104,11 +100,8 @@ $thisYear   = date('Y');
 // display the header
 Display::display_header($tool_name);
 
-// display the tool title
-// api_display_tool_title($tool_name);
-
 if (!empty($return)) {
-	Display::display_error_message($return,false);
+    Display::display_error_message($return,false);
 }
 ?>
 
@@ -183,8 +176,8 @@ if (!empty($return)) {
                 ;" id="options">
 
             <input type="text" name="nb_days_access_before" value="<?php if($formSent) echo api_htmlentities($nb_days_access_before,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_before_beginning'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?>
-                <br />
-                <br />
+            <br />
+            <br />
             <input type="text" name="nb_days_access_after" value="<?php if($formSent) echo api_htmlentities($nb_days_access_after,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_after_end'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysAfter') ?>
 
             </div>
@@ -379,8 +372,6 @@ function setDisable(select){
 
     var start_div = document.getElementById('start_date');
     start_div.style.display = 'none';
-
-
 }
 
 function disable_endtime(select) {

From 83610d17c8240c6353082aba07d8a759d9220da3 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 16:53:42 +0200
Subject: [PATCH 28/65] Adding 'session.show_description' fields are not showed
 if the DB change does not exits see BT#6674

---
 main/admin/session_edit.php         | 64 +++++++++++++++++++++++------
 main/inc/lib/display.lib.php        | 10 +++--
 main/inc/lib/sessionmanager.lib.php | 52 +++++++++++++++++++----
 3 files changed, 102 insertions(+), 24 deletions(-)

diff --git a/main/admin/session_edit.php b/main/admin/session_edit.php
index 9ecc33abcb..537da48985 100644
--- a/main/admin/session_edit.php
+++ b/main/admin/session_edit.php
@@ -26,25 +26,22 @@ $id = intval($_GET['id']);
 
 SessionManager::protect_session_edit($id);
 
-$sql = "SELECT name,date_start,date_end,id_coach, session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end, session_category_id, visibility
-        FROM $tbl_session WHERE id = $id";
-$result = Database::query($sql);
-
-if (!$infos = Database::fetch_array($result)) {
-    header('Location: session_list.php');
-    exit();
-}
+$infos = SessionManager::fetch($id);
 
 $id_coach = $infos['id_coach'];
-
 $tool_name = get_lang('EditSession');
 
 $interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => "session_list.php","name" => get_lang('SessionList'));
 $interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$id,"name" => get_lang('SessionOverview'));
 
-list($year_start,$month_start,$day_start)   = explode('-',$infos['date_start']);
-list($year_end,$month_end,$day_end)         = explode('-',$infos['date_end']);
+list($year_start,$month_start,$day_start)   = explode('-', $infos['date_start']);
+list($year_end,$month_end,$day_end)         = explode('-', $infos['date_end']);
+
+$showDescriptionChecked = null;
+if (isset($infos['show_description']) && !empty($infos['show_description'])) {
+    $showDescriptionChecked = 'checked';
+}
 
 $end_year_disabled = $end_month_disabled = $end_day_disabled = '';
 
@@ -65,6 +62,9 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 	$id_session_category   = $_POST['session_category'];
 	$id_visibility         = $_POST['session_visibility'];
 
+    $description = isset($_POST['description']) ? $_POST['description'] : null;
+    $showDescription = isset($_POST['show_description']) ? 1 : 0;
+
     $end_limit              = $_POST['end_limit'];
     $start_limit            = $_POST['start_limit'];
 
@@ -74,7 +74,27 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
         $nolimit = null;
     }
 
-	$return = SessionManager::edit_session($id,$name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit, $id_coach, $id_session_category,$id_visibility,$start_limit,$end_limit);
+	$return = SessionManager::edit_session(
+        $id,
+        $name,
+        $year_start,
+        $month_start,
+        $day_start,
+        $year_end,
+        $month_end,
+        $day_end,
+        $nb_days_acess_before,
+        $nb_days_acess_after,
+        $nolimit,
+        $id_coach,
+        $id_session_category,
+        $id_visibility,
+        $start_limit,
+        $end_limit,
+        $description,
+        $showDescription
+    );
+
 	if ($return == strval(intval($return))) {
 		header('Location: resume_session.php?id_session='.$return);
 		exit();
@@ -337,6 +357,26 @@ if (!empty($return)) {
     </div>
   </div>
 
+    <?php if (array_key_exists('show_description', $infos)) { ?>
+
+        <div class="control-group">
+            <div class="controls">
+                <?php echo get_lang('Description') ?> <br />
+                <textarea name="description"><?php  echo $infos['description']; ?></textarea>
+            </div>
+        </div>
+
+        <div class="control-group">
+            <div class="controls">
+                <label>
+                <input id="show_description" type="checkbox" name="show_description" <?php echo $showDescriptionChecked ?> />
+                <?php echo get_lang('ShowDescription') ?>
+                </label>
+            </div>
+        </div>
+
+    <?php } ?>
+
     <div class="control-group">
         <div class="controls">
             <button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
diff --git a/main/inc/lib/display.lib.php b/main/inc/lib/display.lib.php
index 3eac1e95ce..682c9862ab 100644
--- a/main/inc/lib/display.lib.php
+++ b/main/inc/lib/display.lib.php
@@ -1226,7 +1226,8 @@ class Display {
      * @param int       Session ID
      * @return array    Empty array or session array ['title'=>'...','category'=>'','dates'=>'...','coach'=>'...','active'=>true/false,'session_category_id'=>int]
      */
-    public static function get_session_title_box($session_id) {
+    public static function get_session_title_box($session_id)
+    {
         global $nosession;
 
         if (!$nosession) {
@@ -1287,9 +1288,12 @@ class Display {
             $session['active'] = $active;
             $session['session_category_id'] = $session_info['session_category_id'];
 
-            if (isset($session_info['description'])) {
-                $session['description'] = $session_info['description'];
+            if (array_key_exists('show_description', $session_info)) {
+                if (!empty($session_info['show_description'])) {
+                    $session['description'] = $session_info['description'];
+                }
             }
+
             $output = $session;
         }
         return $output;
diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index cf09ba5fde..6dd3740147 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -396,9 +396,28 @@ class SessionManager
 	 * @return $id;
 	 * The parameter id is a primary key
 	**/
-	public static function edit_session ($id,$name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit,$id_coach, $id_session_category, $id_visibility, $start_limit = true, $end_limit = true) {
-		global $_user;
-		$name=trim(stripslashes($name));
+	public static function edit_session (
+        $id,
+        $name,
+        $year_start,
+        $month_start,
+        $day_start,
+        $year_end,
+        $month_end,
+        $day_end,
+        $nb_days_acess_before,
+        $nb_days_acess_after,
+        $nolimit,
+        $id_coach,
+        $id_session_category,
+        $id_visibility,
+        $start_limit = true,
+        $end_limit = true,
+        $description = null,
+        $showDescription = null
+    )
+    {
+		$name = trim(stripslashes($name));
 		$year_start=intval($year_start);
 		$month_start=intval($month_start);
 		$day_start=intval($day_start);
@@ -411,9 +430,7 @@ class SessionManager
 		$id_session_category = intval($id_session_category);
 		$id_visibility = intval($id_visibility);
 
-		$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
 		$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
-		$tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 
 		if (empty($nolimit)) {
 			$date_start  = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
@@ -453,17 +470,32 @@ class SessionManager
 			$msg=get_lang('StartDateShouldBeBeforeEndDate');
 			return $msg;
 		} else {
+
 			$rs = Database::query("SELECT id FROM $tbl_session WHERE name='".Database::escape_string($name)."'");
 			$exists = false;
 			while ($row = Database::fetch_array($rs)) {
-				if($row['id']!=$id)
+				if ($row['id'] != $id)
 					$exists = true;
 			}
+
 			if ($exists) {
-				$msg=get_lang('SessionNameAlreadyExists');
+				$msg = get_lang('SessionNameAlreadyExists');
 				return $msg;
 			} else {
-				$sql="UPDATE $tbl_session " .
+
+                $sessionInfo = SessionManager::fetch($id);
+
+                $descriptionCondition = null;
+                if (array_key_exists('description', $sessionInfo)) {
+                    $descriptionCondition = ' description = "'.Database::escape_string($description).'" ,';
+                }
+
+                $showDescriptionCondition = null;
+                if (array_key_exists('show_description', $sessionInfo)) {
+                    $showDescriptionCondition = ' show_description = "'.Database::escape_string($showDescription).'" ,';
+                }
+
+				$sql = "UPDATE $tbl_session " .
 					"SET name='".Database::escape_string($name)."',
 						date_start='".$date_start."',
 						date_end='".$date_end."',
@@ -471,6 +503,8 @@ class SessionManager
 						nb_days_access_before_beginning = ".$nb_days_acess_before.",
 						nb_days_access_after_end = ".$nb_days_acess_after.",
 						session_category_id = ".$id_session_category." ,
+                        $descriptionCondition
+                        $showDescriptionCondition
 						visibility= ".$id_visibility."
 					  WHERE id='$id'";
 				Database::query($sql);
@@ -1905,7 +1939,7 @@ class SessionManager
                 $date_end               = $enreg['DateEnd'];
                 $visibility             = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
                 $session_category_id    = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
-                $sessionDescription    = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
+                $sessionDescription     = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
 
                 $extraSessionParameters = null;
                 if (!empty($sessionDescription)) {

From 5763ad5e2e96718a3d0dab5e793c613aa5506ca1 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 17:24:28 +0200
Subject: [PATCH 29/65] Minor - format code

---
 main/admin/session_user_import.php | 58 +++++++++++++++---------------
 1 file changed, 28 insertions(+), 30 deletions(-)

diff --git a/main/admin/session_user_import.php b/main/admin/session_user_import.php
index 9ba74d277a..ae8c29bf9c 100644
--- a/main/admin/session_user_import.php
+++ b/main/admin/session_user_import.php
@@ -8,7 +8,9 @@
 $language_file = array('admin', 'registration');
 $cidReset = true;
 
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
+
+set_time_limit(0);
 
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);
@@ -26,39 +28,39 @@ $tool_name = get_lang('ImportUsers');
 $session_id = isset($_GET['id_session']) ? intval($_GET['id_session']) : null;
 
 if (empty($session_id)) {
-    api_not_allowed(true);    
+    api_not_allowed(true);
 }
 
 $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => "session_list.php","name" => get_lang('SessionList'));
-$interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$session_id,"name" => get_lang('SessionOverview'));
-
-set_time_limit(0);
-
-if ($_POST['formSent']) {    
-    if (isset($_FILES['import_file']['tmp_name']) && !empty($_FILES['import_file']['tmp_name'])) {        
-        $form_sent = $_POST['formSent'];        
+$interbreadcrumb[] = array('url' => "session_list.php", "name" => get_lang('SessionList'));
+$interbreadcrumb[] = array('url'  => "resume_session.php?id_session=".$session_id,
+                           "name" => get_lang('SessionOverview')
+);
+
+if (isset($_POST['formSent']) && $_POST['formSent']) {
+    if (isset($_FILES['import_file']['tmp_name']) && !empty($_FILES['import_file']['tmp_name'])) {
+        $form_sent = $_POST['formSent'];
         $send_mail = $_POST['sendMail'] ? 1 : 0;
-        
+
         // CSV
-        $users = Import::csv_to_array($_FILES['import_file']['tmp_name']);
+        $users     = Import::csv_to_array($_FILES['import_file']['tmp_name']);
         $user_list = array();
         foreach ($users as $user_data) {
             $username = $user_data['username'];
-            $user_id = UserManager::get_user_id_from_username($username);
+            $user_id  = UserManager::get_user_id_from_username($username);
             if ($user_id) {
                 $user_list[] = $user_id;
             }
         }
-        
-        if (!empty($user_list)) {            
+
+        if (!empty($user_list)) {
             SessionManager::suscribe_users_to_session($session_id, $user_list, null, false, $send_mail);
             foreach ($user_list as & $user_id) {
                 $user_info = api_get_user_info($user_id);
-                $user_id = $user_info['complete_name'];
+                $user_id   = $user_info['complete_name'];
             }
-            $error_message  = get_lang('UsersAdded').' : '.implode(', ', $user_list);
-        }  
+            $error_message = get_lang('UsersAdded').' : '.implode(', ', $user_list);
+        }
     } else {
         $error_message = get_lang('NoInputFile');
     }
@@ -77,7 +79,9 @@ if (count($inserted_in_course) > 1) {
 }
 
 echo '<div class="actions">';
-echo '<a href="resume_session.php?id_session='.$session_id.'">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '<a href="resume_session.php?id_session='.$session_id.'">'.
+    Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'), '', ICON_SIZE_MEDIUM).
+    '</a>';
 echo '</div>';
 
 if (!empty($error_message)) {
@@ -87,28 +91,22 @@ if (!empty($error_message)) {
 $form = new FormValidator('import_sessions', 'post', api_get_self().'?id_session='.$session_id, null, array('enctype' => 'multipart/form-data'));
 $form->addElement('hidden', 'formSent', 1);
 $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
-
 $form->addElement('checkbox', 'sendMail', null, get_lang('SendMailToUsers'));
 $form->addElement('button', 'submit', get_lang('Import'));
 
-$defaults = array('sendMail' => 'true');
-$form->setDefaults($defaults);
-
+//$defaults = array('sendMail' => 'true');
+//$form->setDefaults($defaults);
 $form->display();
 
 ?>
-<font color="gray">
 <p><?php echo get_lang('CSVMustLookLike'); ?> :</p>
-
 <blockquote>
 <pre>
 username;
-jdoe;
+admin;
+teacher;
 jmontoya;
 </pre>
 </blockquote>
-
 <?php
-
-/* FOOTER */
-Display::display_footer();
\ No newline at end of file
+Display::display_footer();

From b09deb9f9df55b1e0e75a5edc086d22047fa7d94 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 17:41:24 +0200
Subject: [PATCH 30/65] Minor format code.

---
 main/admin/session_category_list.php | 28 +++++++++++++++-------------
 1 file changed, 15 insertions(+), 13 deletions(-)

diff --git a/main/admin/session_category_list.php b/main/admin/session_category_list.php
index 7d92ef8958..aa530e80db 100644
--- a/main/admin/session_category_list.php
+++ b/main/admin/session_category_list.php
@@ -17,18 +17,19 @@ api_protect_admin_script(true);
 
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
-$htmlHeadXtra[] = '<script>
-				function selectAll(idCheck,numRows,action) {
-					for(i=0;i<numRows;i++) {
-						idcheck = document.getElementById(idCheck+"_"+i);
-						if (action == "true"){
-							idcheck.checked = true;
-						} else {
-							idcheck.checked = false;
-						}
-					}
-				}
-				</script>';
+$htmlHeadXtra[] =
+'<script>
+    function selectAll(idCheck,numRows,action) {
+        for(i=0;i<numRows;i++) {
+            idcheck = document.getElementById(idCheck+"_"+i);
+            if (action == "true"){
+                idcheck.checked = true;
+            } else {
+                idcheck.checked = false;
+            }
+        }
+    }
+</script>';
 
 $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
@@ -238,4 +239,5 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     <?php } ?>
     </table>
 
-<?php } Display::display_footer(); ?>
+<?php }
+Display::display_footer();

From b7929565ac3b413bef5eacfe6818bac07ee07086 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 18:41:13 +0200
Subject: [PATCH 31/65] Fixing jqgrid count when searching for sessions, fixing
 category url see BT#6692

---
 main/admin/session_list.php         | 80 ++++++++++++++++++-----------
 main/inc/ajax/model.ajax.php        |  2 +-
 main/inc/lib/sessionmanager.lib.php | 64 +++++++++++++++++++----
 3 files changed, 105 insertions(+), 41 deletions(-)

diff --git a/main/admin/session_list.php b/main/admin/session_list.php
index d7b9ad92ab..75aad5d6bb 100644
--- a/main/admin/session_list.php
+++ b/main/admin/session_list.php
@@ -47,32 +47,44 @@ if (!empty($error_message)) {
 
 //jqgrid will use this URL to do the selects
 $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions';
+
 if (isset($_REQUEST['keyword'])) {
     //Begin with see the searchOper param
     $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&rows=20&page=1&sidx=&sord=asc&filters=&searchField=name&searchString='.Security::remove_XSS($_REQUEST['keyword']).'&searchOper=bw';
 }
 
+if (isset($_REQUEST['id_category'])) {
+    $sessionCategory = SessionManager::get_session_category($_REQUEST['id_category']);
+    if (!empty($sessionCategory)) {
+        //Begin with see the searchOper param
+        $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&rows=20&page=1&sidx=&sord=asc&filters=&searchField=category_name&searchString='.Security::remove_XSS($sessionCategory['name']).'&searchOper=bw';
+    }
+}
+
 //The order is important you need to check the the $column variable in the model.ajax.php file
-$columns        = array(get_lang('Name'), get_lang('NumberOfCourses'), get_lang('NumberOfUsers'), get_lang('SessionCategoryName'),
-                        get_lang('StartDate'), get_lang('EndDate'), get_lang('Coach'),  get_lang('Status'), get_lang('Visibility'), get_lang('Actions'));
+$columns = array(get_lang('Name'), get_lang('NumberOfCourses'), get_lang('NumberOfUsers'), get_lang('SessionCategoryName'),
+                 get_lang('StartDate'), get_lang('EndDate'), get_lang('Coach'),  get_lang('Status'), get_lang('Visibility'), get_lang('Actions'));
 
-//$activeurl = '?sidx=session_active';
 //Column config
 $column_model   = array(
     array('name'=>'name',           'index'=>'s.name',        'width'=>'160',  'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
     array('name'=>'nbr_courses',    'index'=>'nbr_courses',   'width'=>'30',   'align'=>'left', 'search' => 'true'),
     array('name'=>'nbr_users',      'index'=>'nbr_users',     'width'=>'30',   'align'=>'left', 'search' => 'true'),
     array('name'=>'category_name',  'index'=>'category_name', 'width'=>'70',   'align'=>'left', 'search' => 'true'),
-    array('name'=>'date_start',     'index'=>'date_start',    'width'=>'40',   'align'=>'left', 'search' => 'true'),
-    array('name'=>'date_end',       'index'=>'date_end',      'width'=>'40',   'align'=>'left', 'search' => 'true'),
+    array('name'=>'date_start',     'index'=>'s.date_start',    'width'=>'40',   'align'=>'left', 'search' => 'true'),
+    array('name'=>'date_end',       'index'=>'s.date_end',      'width'=>'40',   'align'=>'left', 'search' => 'true'),
     array('name'=>'coach_name',     'index'=>'coach_name',    'width'=>'80',   'align'=>'left', 'search' => 'false'),
     array('name'=>'status',         'index'=>'session_active','width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=>'select',
-      //for the bottom bar
-      'searchoptions' => array(
-                        'defaultValue'  => '1',
-                        'value'         => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
-      //for the top bar
-      'editoptions' => array('value' => ':'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive'))),
+        //for the bottom bar
+        'searchoptions' => array(
+            'defaultValue'  => '1',
+            'value'         => '1:'.get_lang('Active').';0:'.get_lang('Inactive')
+        ),
+        //for the top bar
+        'editoptions' => array(
+            'value' => ':'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive')
+        )
+    ),
     array('name'=>'visibility',     'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),
     array('name'=>'actions',        'index'=>'actions',         'width'=>'100',  'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false')
 );
@@ -81,8 +93,6 @@ $extra_params['autowidth'] = 'true';
 
 //height auto
 $extra_params['height'] = 'auto';
-//$extra_params['excel'] = 'excel';
-//$extra_params['rowList'] = array(10, 20 ,30);
 
 //With this function we can add actions to the jgrid (edit, delete, etc)
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
@@ -96,34 +106,40 @@ $action_links = 'function action_formatter(cellvalue, options, rowObject) {
 ?>
 <script>
 
-    function setSearchSelect(columnName) {
-    $("#sessions").jqGrid('setColProp', columnName,
-    {
-       searchoptions:{
-            dataInit:function(el){
-                $("option[value='2']",el).attr("selected", "selected");
-                setTimeout(function(){
-                    $(el).trigger('change');
-                },1000);
+function setSearchSelect(columnName) {
+    $("#sessions").jqGrid(
+        'setColProp',
+        columnName,
+        {
+            searchoptions: {
+                dataInit:function(el) {
+                    $("option[value='2']",el).attr("selected", "selected");
+                    setTimeout(function() {
+                        $(el).trigger('change');
+                    }, 1000);
+                }
             }
         }
-    });
+    );
 }
 
-
 $(function() {
     <?php
-        echo Display::grid_js('sessions', $url,$columns,$column_model,$extra_params, array(), $action_links,true);
+        echo Display::grid_js('sessions', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
     ?>
 
     setSearchSelect("status");
 
-    $("#sessions").jqGrid('navGrid','#sessions_pager', {edit:false,add:false,del:false},
-        {height:280,reloadAfterSubmit:false}, // edit options
-        {height:280,reloadAfterSubmit:false}, // add options
-        {reloadAfterSubmit:false}, // del options
-        {width:500} // search options
+    $("#sessions").jqGrid(
+        'navGrid',
+        '#sessions_pager',
+        { edit: false, add: false, del: false},
+        { height:280, reloadAfterSubmit:false }, // edit options
+        { height:280, reloadAfterSubmit:false }, // add options
+        { reloadAfterSubmit:false }, // del options
+        { width:500 } // search options
     );
+
     /*
     // add custom button to export the data to excel
     jQuery("#sessions").jqGrid('navButtonAdd','#sessions_pager',{
@@ -150,9 +166,11 @@ $(function() {
         'autosearch' : true,
         'searchOnEnter':false
     }
-    jQuery("#sessions").jqGrid('filterToolbar',options);
+
+    jQuery("#sessions").jqGrid('filterToolbar', options);
     var sgrid = $("#sessions")[0];
     sgrid.triggerToolbar();
+
 });
 </script>
 <div class="actions">
diff --git a/main/inc/ajax/model.ajax.php b/main/inc/ajax/model.ajax.php
index cd7c9afeb7..d151438049 100644
--- a/main/inc/ajax/model.ajax.php
+++ b/main/inc/ajax/model.ajax.php
@@ -177,7 +177,7 @@ switch ($action) {
         $count = get_count_exam_hotpotatoes_results($hotpot_path);
         break;
     case 'get_sessions':
-        $count = SessionManager::get_count_admin();
+        $count = SessionManager::get_count_admin($where_condition);
         break;
     /*case 'get_extra_fields':
         $type = $_REQUEST['type'];
diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 6dd3740147..19d67b4eb7 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -181,7 +181,8 @@ class SessionManager
         return $result['count'] > 0;
 	}
 
-    static function get_count_admin() {
+    static function get_count_admin($where_condition = null) {
+
         $tbl_session            = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
         $tbl_user               = Database::get_main_table(TABLE_MAIN_USER);
@@ -193,11 +194,44 @@ class SessionManager
             $where.=" WHERE s.session_admin_id = $user_id ";
         }
 
-        $query_rows = "SELECT count(*) as total_rows
-         FROM $tbl_session s
-            LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
-            INNER JOIN $tbl_user u ON s.id_coach = u.user_id
-         $where ";
+        $today = api_get_utc_datetime();
+        $today = api_strtotime($today, 'UTC');
+        $today = date('Y-m-d', $today);
+
+        if (!empty($where_condition)) {
+
+            $where_condition = str_replace('category_name', 'sc.name', $where_condition);
+            $where_condition = str_replace(
+                array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
+                array(') HAVING session_active = 1 ', "HAVING session_active = 1 " )
+                , $where_condition
+            );
+            $where_condition = str_replace(
+                array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
+                array(') HAVING session_active = 0 ', " HAVING session_active = '0' "),
+                $where_condition
+            );
+        } else {
+            $where_condition = "1 = 1";
+        }
+
+        $query_rows = "SELECT
+                 IF (
+					(s.date_start <= '$today' AND '$today' < s.date_end) OR
+                    (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start,'".$today."' ".") <= s.nb_days_access_before_beginning) OR
+                    (s.nb_days_access_after_end > 0 AND DATEDIFF('".$today."',s.date_end) <= s.nb_days_access_after_end) OR
+                    (s.date_start  = '0000-00-00' AND s.date_end  = '0000-00-00' ) OR
+					(s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
+					('$today' < s.date_end AND '0000-00-00' = s.date_start)
+				, 1, 0)
+				as session_active,
+				s.name,
+				sc.name,
+                count(*) as total_rows
+                FROM $tbl_session s
+                    LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
+                    INNER JOIN $tbl_user u ON s.id_coach = u.user_id
+                $where AND $where_condition ";
 
         if (api_is_multiple_url_enabled()) {
             $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
@@ -205,16 +239,29 @@ class SessionManager
             if ($access_url_id != -1) {
 				$where.= " AND ar.access_url_id = $access_url_id ";
 
-                $query_rows = "SELECT count(*) as total_rows
+                $query_rows = "SELECT
+                  IF (
+					(s.date_start <= '$today' AND '$today' < s.date_end) OR
+                    (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start,'".$today."' ".") <= s.nb_days_access_before_beginning) OR
+                    (s.nb_days_access_after_end > 0 AND DATEDIFF('".$today."',s.date_end) <= s.nb_days_access_after_end) OR
+                    (s.date_start  = '0000-00-00' AND s.date_end  = '0000-00-00' ) OR
+					(s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
+					('$today' < s.date_end AND '0000-00-00' = s.date_start)
+				, 1, 0)
+				as session_active,
+				s.name,
+                 count(*) as total_rows
                  FROM $tbl_session s
                     LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                     INNER JOIN $tbl_user u ON s.id_coach = u.user_id
                     INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
-                 $where ";
+                 $where AND $where_condition ";
             }
         }
+
         $result_rows = Database::query($query_rows);
         $recorset = Database::fetch_array($result_rows);
+
         $num = $recorset['total_rows'];
         return $num;
     }
@@ -254,7 +301,6 @@ class SessionManager
                     (s.date_start  = '0000-00-00' AND s.date_end  = '0000-00-00' ) OR
 					(s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
 					('$today' < s.date_end AND '0000-00-00' = s.date_start)
-
 				, 1, 0)
 				as session_active,
 				s.name,

From c8e315088b8042e76c9d8af2422050ab404c3d8f Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 19:24:52 +0200
Subject: [PATCH 32/65] Fixing issue with query mysql < 5.5

---
 main/inc/lib/sessionmanager.lib.php | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 19d67b4eb7..89a928185e 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -181,7 +181,8 @@ class SessionManager
         return $result['count'] > 0;
 	}
 
-    static function get_count_admin($where_condition = null) {
+    static function get_count_admin($where_condition = null)
+    {
 
         $tbl_session            = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
@@ -203,12 +204,12 @@ class SessionManager
             $where_condition = str_replace('category_name', 'sc.name', $where_condition);
             $where_condition = str_replace(
                 array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
-                array(') HAVING session_active = 1 ', "HAVING session_active = 1 " )
+                array(') GROUP BY name HAVING session_active = 1 ', " GROUP BY name HAVING session_active = 1 " )
                 , $where_condition
             );
             $where_condition = str_replace(
                 array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
-                array(') HAVING session_active = 0 ', " HAVING session_active = '0' "),
+                array(') GROUP BY name HAVING session_active = 0 ', " GROUP BY name HAVING session_active = '0' "),
                 $where_condition
             );
         } else {
@@ -258,7 +259,7 @@ class SessionManager
                  $where AND $where_condition ";
             }
         }
-
+        echo ($query_rows);
         $result_rows = Database::query($query_rows);
         $recorset = Database::fetch_array($result_rows);
 

From 73a90af5a46c166c4a8adc9eacd06c9b16a840b4 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 19:32:39 +0200
Subject: [PATCH 33/65] Adding prefix

---
 main/inc/lib/sessionmanager.lib.php | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 89a928185e..ecff89200d 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -204,12 +204,12 @@ class SessionManager
             $where_condition = str_replace('category_name', 'sc.name', $where_condition);
             $where_condition = str_replace(
                 array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
-                array(') GROUP BY name HAVING session_active = 1 ', " GROUP BY name HAVING session_active = 1 " )
+                array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
                 , $where_condition
             );
             $where_condition = str_replace(
                 array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
-                array(') GROUP BY name HAVING session_active = 0 ', " GROUP BY name HAVING session_active = '0' "),
+                array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
                 $where_condition
             );
         } else {
@@ -259,7 +259,7 @@ class SessionManager
                  $where AND $where_condition ";
             }
         }
-        echo ($query_rows);
+
         $result_rows = Database::query($query_rows);
         $recorset = Database::fetch_array($result_rows);
 

From c0c4e1e1f718f711578c95d02314c4362d6fdfa0 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Fri, 13 Sep 2013 19:56:15 +0200
Subject: [PATCH 34/65] Adding accces_url_id in query.

---
 main/admin/session_category_list.php | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/main/admin/session_category_list.php b/main/admin/session_category_list.php
index aa530e80db..9a3d797b37 100644
--- a/main/admin/session_category_list.php
+++ b/main/admin/session_category_list.php
@@ -75,13 +75,20 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     } else {
         $where .= (empty($_REQUEST['keyword']) ? "" : " WHERE name LIKE '%".Database::escape_string(trim($_REQUEST['keyword']))."%'");
     }
+
+
+
     if (empty($where)) {
         $where = " WHERE access_url_id = ".api_get_current_access_url_id()." ";
     } else {
         $where .= " AND access_url_id = ".api_get_current_access_url_id()." ";
     }
 
-    $query = "SELECT sc.*, (select count(id) FROM $tbl_session WHERE session_category_id = sc.id) as nbr_session
+    $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+    $query = "SELECT sc.*, (
+                SELECT count(id) FROM $tbl_session s INNER JOIN $table_access_url_rel_session us ON (s.id = us.session_id)
+                WHERE s.session_category_id = sc.id and access_url_id = ".api_get_current_access_url_id()."
+                ) as nbr_session
 	 			FROM $tbl_session_category sc
 	 			$where
 	 			ORDER BY $sort $order
@@ -99,7 +106,6 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     $nbr_results = sizeof($Sessions);
     $tool_name = get_lang('ListSessionCategory');
     Display::display_header($tool_name);
-    //api_display_tool_title($tool_name);
 
     if (!empty($_GET['warn'])) {
         Display::display_warning_message(urldecode($_GET['warn']), false);
@@ -170,7 +176,10 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
                 if ($key == $limit) {
                     break;
                 }
-                $sql = 'SELECT COUNT(session_category_id) FROM '.$tbl_session.' WHERE session_category_id = '.intval($enreg['id']);
+                $sql = 'SELECT COUNT(session_category_id)
+                FROM '.$tbl_session.' s INNER JOIN '.$table_access_url_rel_session.'  us ON (s.id = us.session_id)
+                WHERE s.session_category_id = '.intval($enreg['id']).' AND us.access_url_id = '.api_get_current_access_url_id();
+
                 $rs = Database::query($sql);
                 list($nb_courses) = Database::fetch_array($rs);
                 ?>

From 9223bd2500a11b268a6e4586ba61e778618de786 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 12:06:00 +0200
Subject: [PATCH 35/65] Adding message in the upload work.

---
 main/work/upload.php   | 20 ++++++++++++++-
 main/work/work.lib.php |  4 +--
 main/work/work.php     | 57 ++++--------------------------------------
 3 files changed, 26 insertions(+), 55 deletions(-)

diff --git a/main/work/upload.php b/main/work/upload.php
index 95bdf390fa..1ab7a34c5e 100644
--- a/main/work/upload.php
+++ b/main/work/upload.php
@@ -77,11 +77,15 @@ if (!empty($parent_data) && !empty($parent_data['qualification'])) {
     }
 }*/
 
+$has_expired = false;
+$has_ended   = false;
+$message = null;
+
 if (!empty($my_folder_data)) {
     $homework = get_work_assignment_by_id($my_folder_data['id']);
 
     if ($homework['expires_on'] != '0000-00-00 00:00:00' || $homework['ends_on'] != '0000-00-00 00:00:00') {
-        $time_now		= time();
+        $time_now = time();
 
         if (!empty($homework['expires_on']) && $homework['expires_on'] != '0000-00-00 00:00:00') {
             $time_expires 	= api_strtotime($homework['expires_on'], 'UTC');
@@ -106,6 +110,16 @@ if (!empty($my_folder_data)) {
         $ends_on 	= api_convert_and_format_date($homework['ends_on']);
         $expires_on = api_convert_and_format_date($homework['expires_on']);
     }
+
+    if ($has_ended) {
+        $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
+    } elseif ($has_expired) {
+        $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
+    } else {
+        if ($has_expired) {
+            $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
+        }
+    }
 }
 
 $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq(), 'name' => get_lang('StudentPublications'));
@@ -318,6 +332,9 @@ $htmlHeadXtra[] = to_javascript_work();
 Display :: display_header(null);
 
 if (!empty($work_id)) {
+
+    echo $message;
+
     if ($is_allowed_to_edit) {
         if (api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION)) {
             echo Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
@@ -331,6 +348,7 @@ if (!empty($work_id)) {
             Display::display_error_message(get_lang('ActionNotAllowed'));
         }
     } elseif ($student_can_edit_in_session && $has_ended == false) {
+
         $form->display();
     } else {
         Display::display_error_message(get_lang('ActionNotAllowed'));
diff --git a/main/work/work.lib.php b/main/work/work.lib.php
index f5efc3606a..a194dfe7c6 100644
--- a/main/work/work.lib.php
+++ b/main/work/work.lib.php
@@ -577,7 +577,7 @@ function display_student_publications_list($id, $my_folder_data, $work_parents,
 					list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
 					list($d_hour, $d_minute) = explode(':', $parts[1]);
 
-                    $qualification_input[] = FormValidator :: createElement('text', 'qualification');
+                    $qualification_input[] = $form_folder->createElement('text', 'qualification');
                     $form_folder -> addGroup($qualification_input, 'qualification', get_lang('QualificationNumeric'));
 
                     if (Gradebook::is_active()) {
@@ -593,7 +593,7 @@ function display_student_publications_list($id, $my_folder_data, $work_parents,
                         //Loading gradebook select
                         load_gradebook_select_in_tool($form_folder);
 
-                        $weight_input2[] = FormValidator :: createElement('text', 'weight');
+                        $weight_input2[] = $form_folder->createElement('text', 'weight');
                         $form_folder -> addGroup($weight_input2, 'weight', get_lang('WeightInTheGradebook'), 'size="10"');
 
                         $form_folder -> addElement('html', '</div>');
diff --git a/main/work/work.php b/main/work/work.php
index 30c12ee7e3..3315e6cf2b 100644
--- a/main/work/work.php
+++ b/main/work/work.php
@@ -41,7 +41,7 @@ use ChamiloSession as Session;
  *
  */
 
-/*		INIT SECTION */
+/* INIT SECTION */
 
 $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 
@@ -114,10 +114,6 @@ $title 			        = isset($_REQUEST['title']) ? $_REQUEST['title'] : '';
 $description 	        = isset($_REQUEST['description']) ? $_REQUEST['description'] : '';
 $uploadvisibledisabled  = isset($_REQUEST['uploadvisibledisabled']) ? Database::escape_string($_REQUEST['uploadvisibledisabled']) : $course_info['show_score'];
 
-// get data for publication assignment
-$has_expired = false;
-$has_ended   = false;
-
 //directories management
 $sys_course_path 	= api_get_path(SYS_COURSE_PATH);
 $course_dir 		= $sys_course_path . $_course['path'];
@@ -147,10 +143,10 @@ if (isset ($_POST['cancelForm']) && !empty ($_POST['cancelForm'])) {
 if ($_SERVER['REQUEST_METHOD'] == 'POST' && !sizeof($_POST)) {
     if (strstr($_SERVER['REQUEST_URI'], '?')) {
         header('Location: ' . $_SERVER['REQUEST_URI'] . '&submitWork=1');
-        exit ();
+        exit();
     } else {
         header('Location: ' . $_SERVER['REQUEST_URI'] . '?submitWork=1');
-        exit ();
+        exit();
     }
 }
 
@@ -257,59 +253,16 @@ if (!in_array($action, array('add','create_dir'))) {
     $token = Security::get_token();
 }
 
-if (!empty($my_folder_data)) {
-    $homework = get_work_assignment_by_id($my_folder_data['id']);
-
-    if ($homework['expires_on'] != '0000-00-00 00:00:00' || $homework['ends_on'] != '0000-00-00 00:00:00') {
-        $time_now		= time();
-
-        if (!empty($homework['expires_on']) && $homework['expires_on'] != '0000-00-00 00:00:00') {
-            $time_expires 	= api_strtotime($homework['expires_on'], 'UTC');
-            $difference 	= $time_expires - $time_now;
-            if ($difference < 0) {
-                $has_expired = true;
-            }
-        }
-
-        if (empty($homework['expires_on']) || $homework['expires_on'] == '0000-00-00 00:00:00') {
-            $has_expired = false;
-        }
-
-        if (!empty($homework['ends_on']) && $homework['ends_on'] != '0000-00-00 00:00:00') {
-            $time_ends 		= api_strtotime($homework['ends_on'], 'UTC');
-            $difference2 	= $time_ends - $time_now;
-            if ($difference2 < 0) {
-                $has_ended = true;
-            }
-        }
-
-        $ends_on 	= api_convert_and_format_date($homework['ends_on']);
-        $expires_on = api_convert_and_format_date($homework['expires_on']);
-
-        if ($has_ended) {
-            $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
-        } elseif ($has_expired) {
-            $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
-        } else {
-            if ($has_expired) {
-                $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
-            }
-        }
-    }
-}
-
 display_action_links($work_id, $curdirpath, $action);
 
-echo $message;
-
-//for teachers
+// for teachers
 
 switch ($action) {
     case 'settings':
         //if posts
         if ($is_allowed_to_edit && !empty($_POST['changeProperties'])) {
             // Changing the tool setting: default visibility of an uploaded document
-            // @todo i
+            // @todo
             $query = "UPDATE ".$main_course_table." SET show_score='" . $uploadvisibledisabled . "' WHERE code='" . api_get_course_id() . "'";
             $res = Database::query($query);
 

From 695395f6cc90432386d0eb7dc9c326e636133bc0 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 12:57:01 +0200
Subject: [PATCH 36/65] Minor setting a default value for the session course
 editions see BT#6665

---
 main/admin/course_edit.php | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/main/admin/course_edit.php b/main/admin/course_edit.php
index 554d6d3073..b96efcada7 100644
--- a/main/admin/course_edit.php
+++ b/main/admin/course_edit.php
@@ -186,6 +186,8 @@ $course['disk_quota'] = round(DocumentManager::get_course_quota($course_code) /1
 $course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);
 $course['real_code'] = $course['code'];
 
+$course['add_teachers_to_sessions'] = empty($course_teachers) ||  count($course_teachers) == 1 ? null : '1';
+
 $form->setDefaults($course);
 
 // Validate form
@@ -224,8 +226,7 @@ if ($form->validate()) {
     }
 
 	$tutor_id = $course['tutor_name'];
-	$tutor_name=$platform_teachers[$tutor_id];
-
+	$tutor_name = $platform_teachers[$tutor_id];
 	$teachers = $course['group']['course_teachers'];
 
 	$title = $course['title'];
@@ -264,7 +265,6 @@ if ($form->validate()) {
 		}
 	}
 
-
     CourseManager::updateTeachers($course_code, $teachers, $course['add_teachers_to_sessions']);
 
 	$sql = "INSERT IGNORE INTO ".$course_user_table . " SET

From 5c29dd438498666c9253aa332a42145eca848105 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 15:01:35 +0200
Subject: [PATCH 37/65] Adding a global default_calendar_view setting in the
 agenda. see BT#6695

---
 main/calendar/agenda_js.php            | 11 ++++++++++-
 main/template/default/agenda/month.tpl |  1 +
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/main/calendar/agenda_js.php b/main/calendar/agenda_js.php
index b5a9bee020..2f1ce308d7 100644
--- a/main/calendar/agenda_js.php
+++ b/main/calendar/agenda_js.php
@@ -38,7 +38,6 @@ if (api_is_platform_admin() && $type == 'admin') {
     $type = 'admin';
 }
 
-//if (api_get_course_id() != -1 && $type == 'course') {
 if (isset($_REQUEST['cidReq']) && !empty($_REQUEST['cidReq'])) {
     $type = 'course';
 }
@@ -153,6 +152,16 @@ if ($type == 'course' && !empty($group_id)) {
     $type_label = get_lang('GroupCalendar');
 }
 
+$defaultView = api_get_setting('default_calendar_view');
+
+if (empty($defaultView)) {
+    $defaultView = 'month';
+}
+
+/* month, basicWeek,agendaWeek,agendaDay */
+
+$tpl->assign('default_view', $defaultView);
+
 if ($type == 'course' && !empty($session_id)) {
     $type_event_class = 'session_event';
     $type_label = get_lang('SessionCalendar');
diff --git a/main/template/default/agenda/month.tpl b/main/template/default/agenda/month.tpl
index 5c32d26db7..28e4a5edda 100644
--- a/main/template/default/agenda/month.tpl
+++ b/main/template/default/agenda/month.tpl
@@ -103,6 +103,7 @@ $(document).ready(function() {
             ],
         {% endif %}
 
+        defaultView:    '{{ default_view }}',
 		buttonText: 	{{ button_text }},
 		monthNames: 	{{ month_names }},
 		monthNamesShort:{{ month_names_short }},

From 9f63297b6f5e209955bcbf533594043759247253 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 15:16:46 +0200
Subject: [PATCH 38/65] Minor - format code and fixing typo

---
 main/social/search.php | 7 +------
 1 file changed, 1 insertion(+), 6 deletions(-)

diff --git a/main/social/search.php b/main/social/search.php
index 3887d3061a..bad298bb23 100644
--- a/main/social/search.php
+++ b/main/social/search.php
@@ -125,10 +125,7 @@ $(document).ready(function (){
         width    : 550,
         height    : 300
        });
-
 });
-
-
 </script>';
 
 if (api_get_setting('allow_social_tool') != 'true') {
@@ -231,7 +228,7 @@ if ($query != '') {
         $social_right_content .= Display::page_subheader(get_lang('Groups'));
         foreach ($groups as $group) {
             $group['name']         = Security::remove_XSS($group['name'], STUDENT, true);
-            $$group['description'] = Security::remove_XSS($group['description'], STUDENT, true);
+            $group['description'] = Security::remove_XSS($group['description'], STUDENT, true);
             $id                    = $group['id'];
             $url_open              = '<a href="groups.php?id='.$id.'" >';
             $url_close             = '</a>';
@@ -284,9 +281,7 @@ $social_right_content .= MessageManager::generate_invitation_form('send_invitati
 
 $tpl = new Template($tool_name);
 $tpl->assign('social_left_content', $social_left_content);
-
 $tpl->assign('social_right_content', $social_right_content);
 
-
 $social_layout = $tpl->get_template('layout/social_layout.tpl');
 $tpl->display($social_layout);

From 6145ecbe5e4c5dc1c7bb865187b127beb3e29c20 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 16:38:50 +0200
Subject: [PATCH 39/65] Adding pagination when searching users in the social
 network see BT#6708

---
 main/inc/lib/display.lib.php          | 16 ++++-
 main/inc/lib/sortable_table.class.php | 44 ++++++++-----
 main/inc/lib/usermanager.lib.php      | 91 ++++++++++++---------------
 main/social/search.php                | 27 +++++---
 4 files changed, 101 insertions(+), 77 deletions(-)

diff --git a/main/inc/lib/display.lib.php b/main/inc/lib/display.lib.php
index 682c9862ab..545889ce15 100644
--- a/main/inc/lib/display.lib.php
+++ b/main/inc/lib/display.lib.php
@@ -214,11 +214,23 @@ class Display {
      * @param array grid classes
      * @return 	string   html grid
      */
-    public static function return_sortable_grid($name, $header, $content, $paging_options = array(), $query_vars = null, $form_actions = array(), $visibility_options = true, $sort_data = true, $grid_class = array()) {
-        global $origin;
+    public static function return_sortable_grid(
+        $name,
+        $header,
+        $content,
+        $paging_options = array(),
+        $query_vars = null,
+        $form_actions = array(),
+        $visibility_options = true,
+        $sort_data = true,
+        $grid_class = array(),
+        $elementCount = 0
+    ) {
         $column =  0;
         $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
+
         $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name);
+        $table->total_number_of_items = intval($elementCount);
         if (is_array($query_vars)) {
             $table->set_additional_parameters($query_vars);
         }
diff --git a/main/inc/lib/sortable_table.class.php b/main/inc/lib/sortable_table.class.php
index 8c7da2f8a2..20ba07fc61 100644
--- a/main/inc/lib/sortable_table.class.php
+++ b/main/inc/lib/sortable_table.class.php
@@ -122,7 +122,7 @@ class SortableTable extends HTML_Table {
 
         parent :: __construct (array ('class' => 'data_table', 'id' => $table_id));
         $this->table_name = $table_name;
-        $this->additional_parameters = array ();
+        $this->additional_parameters = array();
         $this->param_prefix = $table_name.'_';
 
         $this->page_nr = isset ($_SESSION[$this->param_prefix.'page_nr']) ? intval($_SESSION[$this->param_prefix.'page_nr']) : 1;
@@ -220,7 +220,8 @@ class SortableTable extends HTML_Table {
         return $this->pager;
     }
 
-    public function display() {
+    public function display()
+    {
         echo $this->return_table();
     }
     /**
@@ -465,6 +466,7 @@ class SortableTable extends HTML_Table {
     public function display_simple_grid($visibility_options, $hide_navigation = true, $per_page = 20, $sort_data = true, $grid_class = array()) {
 
         $empty_table = false;
+        $total = $this->get_total_number_of_items();
         if ($this->get_total_number_of_items() == 0) {
             $cols = $this->getColCount();
             //$this->setCellAttributes(1, 0, 'style="font-style: italic;text-align:center;" colspan='.$cols);
@@ -473,10 +475,12 @@ class SortableTable extends HTML_Table {
             $empty_table = true;
         }
         $html = '';
+
         if (!$empty_table) {
             // If we show the pagination
             if (!$hide_navigation) {
                 $form = '&nbsp;';
+
                 if ($this->get_total_number_of_items() > $per_page) {
                     if ($per_page > 10) {
                         $form = $this->get_page_select_form();
@@ -820,7 +824,8 @@ class SortableTable extends HTML_Table {
      * to their default state when sorting this table.
      * @param array $tablenames An array of table names.
      */
-    public function set_other_tables ($tablenames) {
+    public function set_other_tables($tablenames)
+    {
         $this->other_tables = $tablenames;
     }
 
@@ -831,7 +836,8 @@ class SortableTable extends HTML_Table {
      * converted into a checkbox
      * @param array $row A row from the table.
      */
-    public function filter_data ($row) {
+    public function filter_data($row)
+    {
         $url_params = $this->get_sortable_table_param_string().'&amp;'.$this->get_additional_url_paramstring();
         foreach ($this->column_filters as $column => & $function) {
             $row[$column] = call_user_func($function, $row[$column], $url_params, $row);
@@ -845,10 +851,11 @@ class SortableTable extends HTML_Table {
                 $row[0] .= '/>';
             }
         }
-
-        foreach ($row as $index => & $value) {
-            if (empty($value)) {
-                 $value = '-';
+        if (is_array($row)) {
+            foreach ($row as & $value) {
+                if (empty($value)) {
+                     $value = '-';
+                }
             }
         }
         return $row;
@@ -859,7 +866,8 @@ class SortableTable extends HTML_Table {
      * 2nd argument in the constructor of a SortableTable. Make sure your
      * function has the same parameters as defined here.
      */
-    public function get_total_number_of_items () {
+    public function get_total_number_of_items()
+    {
         if ($this->total_number_of_items == -1 && !is_null($this->get_total_number_function)) {
             $this->total_number_of_items = call_user_func($this->get_total_number_function);
         }
@@ -878,11 +886,12 @@ class SortableTable extends HTML_Table {
      * @param string $direction In which order should the data be sorted (ASC
      * or DESC)
      */
-    public function get_table_data ($from = null, $per_page = null, $column = null, $direction = null, $sort = null) {
+    public function get_table_data ($from = null, $per_page = null, $column = null, $direction = null, $sort = null)
+    {
         if (!is_null($this->get_data_function)) {
             return call_user_func($this->get_data_function, $from, $this->per_page, $this->column, $this->direction);
         }
-        return array ();
+        return array();
     }
 }
 
@@ -902,8 +911,8 @@ class SortableTableFromArray extends SortableTable {
      * @param int $default_column
      * @param int $default_items_per_page
      */
-    public function __construct($table_data, $default_column = 1, $default_items_per_page = 20, $tablename = 'tablename') {
-        parent :: __construct ($tablename, null, null, $default_column, $default_items_per_page);
+    public function __construct($table_data, $default_column = 1, $default_items_per_page = 20, $tablename = 'tablename', $get_total_number_function = null) {
+        parent :: __construct ($tablename, $get_total_number_function, null, $default_column, $default_items_per_page);
         $this->table_data = $table_data;
     }
 
@@ -924,8 +933,13 @@ class SortableTableFromArray extends SortableTable {
      * Get total number of items
      * @see SortableTable#get_total_number_of_items
      */
-    public function get_total_number_of_items() {
-        return count($this->table_data);
+    public function get_total_number_of_items()
+    {
+        if (isset($this->total_number_of_items) && !empty($this->total_number_of_items)) {
+            return $this->total_number_of_items;
+        } else {
+            return count($this->table_data);
+        }
     }
 }
 
diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php
index 4e741aaa4c..c6eeb99b70 100644
--- a/main/inc/lib/usermanager.lib.php
+++ b/main/inc/lib/usermanager.lib.php
@@ -3073,16 +3073,16 @@ class UserManager
     }
 
     /**
-     * Searchs an user (tags, firstname, lastname and email )
+     * Search an user (tags, first name, last name and email )
      * @param string the tag
      * @param int field id of the tag
      * @param int where to start in the query
      * @param int number of items
+     * @param bool get count or not
      * @return array
      */
-    public static function get_all_user_tags($tag, $field_id = 0, $from = 0, $number_of_items = 10)
+    public static function get_all_user_tags($tag, $field_id = 0, $from = 0, $number_of_items = 10, $getCount = false)
     {
-
         $user_table = Database::get_main_table(TABLE_MAIN_USER);
         $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
         $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
@@ -3096,69 +3096,58 @@ class UserManager
         if ($field_id != 0) {
             $where_field = " field_id = $field_id AND ";
         }
-        // all the information of the field
-        $sql = "SELECT u.user_id,u.username,firstname, lastname, email, tag, picture_uri FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.id)
-                INNER JOIN $user_table u ON(uv.user_id =u.user_id)
-                WHERE $where_field tag LIKE '$tag%' ORDER BY tag";
-        $sql .= " LIMIT $from,$number_of_items";
 
-        $result = Database::query($sql);
-        $return = array();
-        if (Database::num_rows($result) > 0) {
-            while ($row = Database::fetch_array($result, 'ASSOC')) {
-                if (isset($return[$row['user_id']]) && !empty($return[$row['user_id']]['tag'])) {
-                    $row['tag'] = $return[$row['user_id']]['tag'].' '.Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
-                } else {
-                    $row['tag'] = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
-                }
-                $return[$row['user_id']] = $row;
-            }
+        $addInnerJoin = null;
+        if (true) {
+            $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+            $addInnerJoin = " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id = url_rel_user.user_id)";
         }
 
-        $keyword = $tag;
-        $sql = "SELECT u.user_id, u.username, firstname, lastname, email, picture_uri FROM $user_table u";
+        // all the information of the field
 
-        if (api_get_multiple_access_url()) {
-            $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-            $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
+        if ($getCount) {
+            $select = "SELECT count(u.user_id) count";
+        } else {
+            $select = "SELECT u.user_id, u.username, firstname, lastname, email, tag, picture_uri";
         }
 
-        if (isset($keyword)) {
-            $keyword = Database::escape_string($keyword);
-            //OR u.official_code LIKE '%".$keyword."%'
-            // OR u.email LIKE '%".$keyword."%'
-            $sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%' OR concat(u.firstname,' ',u.lastname) LIKE '%".$keyword."%' OR concat(u.lastname,' ',u.firstname) LIKE '%".$keyword."%' )";
+        $sql = " $select
+                FROM $user_table u $addInnerJoin
+                LEFT JOIN $table_user_tag_values uv ON (u.user_id AND uv.user_id) LEFT JOIN $table_user_tag ut ON (uv.tag_id = ut.id)
+                WHERE
+                    ($where_field tag LIKE '$tag%') OR
+                    (u.firstname LIKE '%".$tag."%' OR u.lastname LIKE '%".$tag."%' OR
+                     u.username LIKE '%".$tag."%' OR concat(u.firstname,' ',u.lastname) LIKE '%".$tag."%' OR
+                     concat(u.lastname,' ',u.firstname) LIKE '%".$tag."%' )";
+
+        if (api_get_multiple_access_url() && api_get_current_access_url_id() != -1) {
+            $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
         }
+
         $keyword_active = true;
-        //only active users
+        // only active users
         if ($keyword_active) {
             $sql .= " AND u.active='1'";
         }
-        //avoid anonymous
+        // avoid anonymous
         $sql .= " AND u.status <> 6 ";
 
-        // adding the filter to see the user's only of the current access_url
-        if (api_get_multiple_access_url() && api_get_current_access_url_id() != -1) {
-            $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-        }
-        $direction = 'ASC';
-        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 .= "ORDER BY username";
         $sql .= " LIMIT $from,$number_of_items";
-
-        $res = Database::query($sql);
-        if (Database::num_rows($res) > 0) {
-            while ($row = Database::fetch_array($res, 'ASSOC')) {
-                if (!in_array($row['user_id'], array_keys($return))) {
-                    $return[$row['user_id']] = $row;
+        $result = Database::query($sql);
+        $return = array();
+        if (Database::num_rows($result) > 0) {
+            if ($getCount) {
+                $row = Database::fetch_array($result, 'ASSOC');
+                return $row['count'];
+            }
+            while ($row = Database::fetch_array($result, 'ASSOC')) {
+                if (isset($return[$row['user_id']]) && !empty($return[$row['user_id']]['tag'])) {
+                    $row['tag'] = $return[$row['user_id']]['tag'].' '.Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
+                } else {
+                    $row['tag'] = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
                 }
+                $return[$row['user_id']] = $row;
             }
         }
         return $return;
diff --git a/main/social/search.php b/main/social/search.php
index bad298bb23..b93828e97b 100644
--- a/main/social/search.php
+++ b/main/social/search.php
@@ -136,17 +136,23 @@ $this_section      = SECTION_SOCIAL;
 $tool_name         = get_lang('Search');
 $interbreadcrumb[] = array('url' => 'profile.php', 'name' => get_lang('SocialNetwork'));
 
-$query_vars = array();
 $query      = isset($_GET['q']) ? $_GET['q'] : null;
+$query_vars = array('q' => $query);
 
 $social_left_content = SocialManager::show_social_menu('search');
 
 $social_right_content = '<div class="span9">'.UserManager::get_search_form($query).'</div>';
 
-//I'm searching something
+// I'm searching something
 if ($query != '') {
-    //get users from tags
-    $users  = UserManager::get_all_user_tags($_GET['q'], 0, 0, 5);
+
+    $itemPerPage = 5;
+    $page = isset($_GET['groups_page_nr']) ? intval($_GET['groups_page_nr']) : 1;
+    $total = UserManager::get_all_user_tags($_GET['q'], 0, 0, $itemPerPage, true);
+
+    $from = intval(($page - 1) * $itemPerPage);
+    // Get users from tags
+    $users  = UserManager::get_all_user_tags($_GET['q'], 0, $from, $itemPerPage);
     $groups = GroupPortalManager::get_all_group_tags($_GET['q']);
 
     if (empty($users) && empty($groups)) {
@@ -228,7 +234,7 @@ if ($query != '') {
         $social_right_content .= Display::page_subheader(get_lang('Groups'));
         foreach ($groups as $group) {
             $group['name']         = Security::remove_XSS($group['name'], STUDENT, true);
-            $group['description'] = Security::remove_XSS($group['description'], STUDENT, true);
+            $group['description']  = Security::remove_XSS($group['description'], STUDENT, true);
             $id                    = $group['id'];
             $url_open              = '<a href="groups.php?id='.$id.'" >';
             $url_close             = '</a>';
@@ -267,13 +273,16 @@ if ($query != '') {
     }
     $visibility = array(true, true, true, true, true);
     $social_right_content .= Display::return_sortable_grid(
-        'mygroups',
-        array(),
+        'groups',
+        null,
         $grid_groups,
-        array('hide_navigation' => true, 'per_page' => 5),
+        array('hide_navigation' => false, 'per_page' => 5),
         $query_vars,
         false,
-        $visibility
+        $visibility,
+        true,
+        array(),
+        $total
     );
 }
 $social_right_content .= MessageManager::generate_message_form('send_message');

From 5f631064a2d239fb01da3c1584ef0eddedd91c10 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 17:24:07 +0200
Subject: [PATCH 40/65] Fixing search user query. see BT#6708

---
 main/inc/lib/usermanager.lib.php | 43 ++++++++++++++++----------------
 main/social/search.php           |  9 +++----
 2 files changed, 24 insertions(+), 28 deletions(-)

diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php
index c6eeb99b70..52579d6cf6 100644
--- a/main/inc/lib/usermanager.lib.php
+++ b/main/inc/lib/usermanager.lib.php
@@ -3086,6 +3086,7 @@ class UserManager
         $user_table = Database::get_main_table(TABLE_MAIN_USER);
         $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
         $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
+        $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 
         $tag = Database::escape_string($tag);
         $field_id = intval($field_id);
@@ -3097,32 +3098,30 @@ class UserManager
             $where_field = " field_id = $field_id AND ";
         }
 
-        $addInnerJoin = null;
-        if (true) {
-            $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-            $addInnerJoin = " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id = url_rel_user.user_id)";
-        }
-
         // all the information of the field
 
         if ($getCount) {
-            $select = "SELECT count(u.user_id) count";
+            $select = "SELECT count(DISTINCT u.user_id) count";
         } else {
-            $select = "SELECT u.user_id, u.username, firstname, lastname, email, tag, picture_uri";
+            $select = "SELECT DISTINCT u.user_id, u.username, firstname, lastname, email, tag, picture_uri";
         }
 
         $sql = " $select
-                FROM $user_table u $addInnerJoin
-                LEFT JOIN $table_user_tag_values uv ON (u.user_id AND uv.user_id) LEFT JOIN $table_user_tag ut ON (uv.tag_id = ut.id)
+                FROM $user_table u
+                INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id = url_rel_user.user_id)
+                LEFT JOIN $table_user_tag_values uv ON (u.user_id AND uv.user_id AND  uv.user_id = url_rel_user.user_id)
+                LEFT JOIN $table_user_tag ut ON (uv.tag_id = ut.id)
                 WHERE
                     ($where_field tag LIKE '$tag%') OR
-                    (u.firstname LIKE '%".$tag."%' OR u.lastname LIKE '%".$tag."%' OR
-                     u.username LIKE '%".$tag."%' OR concat(u.firstname,' ',u.lastname) LIKE '%".$tag."%' OR
-                     concat(u.lastname,' ',u.firstname) LIKE '%".$tag."%' )";
-
-        if (api_get_multiple_access_url() && api_get_current_access_url_id() != -1) {
-            $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-        }
+                    (
+                        u.firstname LIKE '%".$tag."%' OR
+                        u.lastname LIKE '%".$tag."%' OR
+                        u.username LIKE '%".$tag."%' OR
+                        concat(u.firstname,' ',u.lastname) LIKE '%".$tag."%' OR
+                        concat(u.lastname,' ',u.firstname) LIKE '%".$tag."%'
+                     )
+                     AND
+                     url_rel_user.access_url_id=".api_get_current_access_url_id();
 
         $keyword_active = true;
         // only active users
@@ -3131,11 +3130,12 @@ class UserManager
         }
         // avoid anonymous
         $sql .= " AND u.status <> 6 ";
+        $sql .= " ORDER BY username";
+        $sql .= " LIMIT $from , $number_of_items";
 
-        $sql .= "ORDER BY username";
-        $sql .= " LIMIT $from,$number_of_items";
         $result = Database::query($sql);
         $return = array();
+
         if (Database::num_rows($result) > 0) {
             if ($getCount) {
                 $row = Database::fetch_array($result, 'ASSOC');
@@ -3143,9 +3143,8 @@ class UserManager
             }
             while ($row = Database::fetch_array($result, 'ASSOC')) {
                 if (isset($return[$row['user_id']]) && !empty($return[$row['user_id']]['tag'])) {
-                    $row['tag'] = $return[$row['user_id']]['tag'].' '.Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
-                } else {
-                    $row['tag'] = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
+                    $url = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
+                    $row['tag'] = $url;
                 }
                 $return[$row['user_id']] = $row;
             }
diff --git a/main/social/search.php b/main/social/search.php
index b93828e97b..bfefd8ac03 100644
--- a/main/social/search.php
+++ b/main/social/search.php
@@ -195,12 +195,9 @@ if ($query != '') {
                 $status_icon = Display::span('', array('class' => 'offline_user_in_text'));
             }
 
-            $user['tag'] = isset($user['tag']) ? $user['tag'] : null;
+            $tag = isset($user['tag']) ? ' <br /><br />'.$user['tag'] : null;
 
-            $user_info['complete_name'] = Display::url(
-                    $status_icon.$user_info['complete_name'],
-                    $url
-                ).'<br /><br />'.$user['tag'];
+            $user_info['complete_name'] = Display::url($status_icon.$user_info['complete_name'], $url);
 
             $invitations = $user['tag'].$send_inv.$send_msg;
 
@@ -265,7 +262,7 @@ if ($query != '') {
                 $item_2 = '<div class="box_description_group_title" ><span class="social-groups-text2"></span></div>';
                 $item_3 = '<div class="box_description_group_content" ></div>';
             }
-            $item_4        = '<div class="box_description_group_tags" >'.$tags.'</div>';
+            $item_4        = '<div class="box_description_group_tags">'.$tags.'</div>';
             $item_5        = '<div class="box_description_group_actions" >'.$url_open.get_lang('SeeMore').$url_close.'</div>';
             $grid_item_2   = $item_0.$item_1.$item_2.$item_3.$item_4.$item_5;
             $grid_groups[] = array('', $grid_item_2);

From 62ed0ba28a34d83c16369d46a8adcc2f93fcf064 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 17:47:00 +0200
Subject: [PATCH 41/65] Minor - Changing default value.

---
 main/social/search.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/main/social/search.php b/main/social/search.php
index bfefd8ac03..11e1c27eb8 100644
--- a/main/social/search.php
+++ b/main/social/search.php
@@ -146,7 +146,7 @@ $social_right_content = '<div class="span9">'.UserManager::get_search_form($quer
 // I'm searching something
 if ($query != '') {
 
-    $itemPerPage = 5;
+    $itemPerPage = 9;
     $page = isset($_GET['groups_page_nr']) ? intval($_GET['groups_page_nr']) : 1;
     $total = UserManager::get_all_user_tags($_GET['q'], 0, 0, $itemPerPage, true);
 

From 5e5b576bf7b5fd2dbaa9ec46120b36f62dcd0484 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 17:48:55 +0200
Subject: [PATCH 42/65] Minor - Changing default value. (bis)

---
 main/social/search.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/main/social/search.php b/main/social/search.php
index 11e1c27eb8..5a22974230 100644
--- a/main/social/search.php
+++ b/main/social/search.php
@@ -273,7 +273,7 @@ if ($query != '') {
         'groups',
         null,
         $grid_groups,
-        array('hide_navigation' => false, 'per_page' => 5),
+        array('hide_navigation' => false, 'per_page' => $itemPerPage),
         $query_vars,
         false,
         $visibility,

From 61dbda284cc10255c91b253d541246597aa98799 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 18:57:14 +0200
Subject: [PATCH 43/65] Minor - format code

---
 main/admin/dashboard_add_sessions_to_user.php | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/main/admin/dashboard_add_sessions_to_user.php b/main/admin/dashboard_add_sessions_to_user.php
index 0fecb3cd59..f2dae0ba82 100644
--- a/main/admin/dashboard_add_sessions_to_user.php
+++ b/main/admin/dashboard_add_sessions_to_user.php
@@ -9,7 +9,7 @@
 // name of the language file that needs to be included
 $language_file='admin';
 // resetting the course id
-$cidReset=true;
+$cidReset = true;
 
 // including some necessary dokeos files
 require_once '../inc/global.inc.php';
@@ -36,10 +36,10 @@ $tbl_session_rel_user 	= 	Database::get_main_table(TABLE_MAIN_SESSION_USER);
 $tbl_session_rel_access_url = 	Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 
 // initializing variables
-$id_session=intval($_GET['id_session']);
+$id_session = intval($_GET['id_session']);
 $user_id = intval($_GET['user']);
 $user_info = api_get_user_info($user_id);
-$user_anonymous  = api_get_anonymous_id();
+$user_anonymous = api_get_anonymous_id();
 $current_user_id = api_get_user_id();
 
 // setting the name of the tool
@@ -101,7 +101,6 @@ $xajax->processRequests();
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = '
 <script type="text/javascript">
-<!--
 function moveItem(origin , destination) {
 	for(var i = 0 ; i<origin.options.length ; i++) {
 		if(origin.options[i].selected) {
@@ -149,7 +148,6 @@ function remove_item(origin) {
 		}
 	}
 }
--->
 </script>';
 
 $formSent=0;
@@ -295,4 +293,4 @@ if(!empty($msg)) {
 </form>
 
 <?php
-Display::display_footer();
\ No newline at end of file
+Display::display_footer();

From 8f5b7e0ec48ad99ff06d6390d7c569fa5cbf0c67 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Mon, 16 Sep 2013 18:57:32 +0200
Subject: [PATCH 44/65] Fixing query in order to allow session manager to see
 the sessions.

---
 main/inc/lib/sessionmanager.lib.php | 90 +++++++++++++++++++++--------
 1 file changed, 66 insertions(+), 24 deletions(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index ecff89200d..80d0ffaaa1 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -181,18 +181,34 @@ class SessionManager
         return $result['count'] > 0;
 	}
 
+    /**
+     * @param string $where_condition
+     * @return mixed
+     */
     static function get_count_admin($where_condition = null)
     {
 
         $tbl_session            = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
         $tbl_user               = Database::get_main_table(TABLE_MAIN_USER);
+        $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+        $tbl_session_rel_user 	= Database::get_main_table(TABLE_MAIN_SESSION_USER);
 
         $where = 'WHERE 1=1 ';
         $user_id = api_get_user_id();
 
-        if (api_is_session_admin() && api_get_setting('allow_session_admins_to_see_all_sessions') == 'false') {
-            $where.=" WHERE s.session_admin_id = $user_id ";
+        $extraJoin = null;
+
+        if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
+            $where .= " AND (
+                            s.session_admin_id = $user_id  OR
+                            sru.id_user = '$user_id' AND
+                            sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
+                            )
+                      ";
+
+            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
+                            ON sru.id_session = s.id ";
         }
 
         $today = api_get_utc_datetime();
@@ -216,7 +232,8 @@ class SessionManager
             $where_condition = "1 = 1";
         }
 
-        $query_rows = "SELECT
+        $sql = "SELECT count(id) as total_rows FROM (
+                SELECT
                  IF (
 					(s.date_start <= '$today' AND '$today' < s.date_end) OR
                     (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start,'".$today."' ".") <= s.nb_days_access_before_beginning) OR
@@ -226,21 +243,22 @@ class SessionManager
 					('$today' < s.date_end AND '0000-00-00' = s.date_start)
 				, 1, 0)
 				as session_active,
-				s.name,
-				sc.name,
+				s.id,
                 count(*) as total_rows
                 FROM $tbl_session s
                     LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                     INNER JOIN $tbl_user u ON s.id_coach = u.user_id
-                $where AND $where_condition ";
+                    $extraJoin
+                $where AND $where_condition  ) as session_table";
 
         if (api_is_multiple_url_enabled()) {
-            $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+
             $access_url_id = api_get_current_access_url_id();
             if ($access_url_id != -1) {
 				$where.= " AND ar.access_url_id = $access_url_id ";
 
-                $query_rows = "SELECT
+                $sql = "SELECT count(id) as total_rows FROM (
+                SELECT
                   IF (
 					(s.date_start <= '$today' AND '$today' < s.date_end) OR
                     (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start,'".$today."' ".") <= s.nb_days_access_before_beginning) OR
@@ -250,20 +268,19 @@ class SessionManager
 					('$today' < s.date_end AND '0000-00-00' = s.date_start)
 				, 1, 0)
 				as session_active,
-				s.name,
-                 count(*) as total_rows
+				s.id
                  FROM $tbl_session s
                     LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                     INNER JOIN $tbl_user u ON s.id_coach = u.user_id
                     INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
-                 $where AND $where_condition ";
+                    $extraJoin
+                 $where AND $where_condition) as session_table";
             }
         }
 
-        $result_rows = Database::query($query_rows);
-        $recorset = Database::fetch_array($result_rows);
-
-        $num = $recorset['total_rows'];
+        $result_rows = Database::query($sql);
+        $row = Database::fetch_array($result_rows);
+        $num = $row['total_rows'];
         return $num;
     }
 
@@ -272,16 +289,29 @@ class SessionManager
      * @param array $options order and limit keys
      * @return array
      */
-	public static function get_sessions_admin($options) {
+	public static function get_sessions_admin($options)
+    {
 		$tbl_session            = Database::get_main_table(TABLE_MAIN_SESSION);
 		$tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 		$tbl_user               = Database::get_main_table(TABLE_MAIN_USER);
+        $tbl_session_rel_user 	= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 
-		$where = 'HAVING 1=1 ';
+		$where = ' WHERE 1=1 ';
 		$user_id = api_get_user_id();
 
+        $extraJoin = null;
+
 		if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
-			$where.=" AND s.session_admin_id = $user_id ";
+            $where .= " AND (
+                            s.session_admin_id = $user_id  OR
+                            sru.id_user = '$user_id' AND
+                            sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
+                            )
+                      ";
+
+            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
+                            ON sru.id_session = s.id ";
 		}
 
 		$coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
@@ -290,6 +320,18 @@ class SessionManager
 			$coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
 		}
 
+        $options['where'] = str_replace(
+            array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
+            array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
+            , $options['where']
+        );
+
+        $options['where'] = str_replace(
+            array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
+            array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
+            $options['where']
+        );
+
 		$today = api_get_utc_datetime();
         $today = api_strtotime($today, 'UTC');
         $today = date('Y-m-d', $today);
@@ -330,13 +372,12 @@ class SessionManager
         }
 
 		$query = "$select FROM $tbl_session s
-				LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
+				LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
 				LEFT JOIN $tbl_user u ON s.id_coach = u.user_id
+				$extraJoin
                 $where $order $limit";
 
-		global $_configuration;
-		if ($_configuration['multiple_access_urls']) {
-			$table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+		if (api_is_multiple_url_enabled()) {
 			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1) {
 				$query = " $select
@@ -344,6 +385,7 @@ class SessionManager
                                LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                                INNER JOIN $tbl_user u ON s.id_coach = u.user_id
                                INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id AND ar.access_url_id = $access_url_id
+                               $extraJoin
 				 $where $order $limit";
 			}
 		}
@@ -1488,8 +1530,8 @@ class SessionManager
 	 * @param int		Human resources manager or Session admin id
 	 * @return array 	sessions
 	 */
-	public static function get_sessions_followed_by_drh($hr_manager_id) {
-        global $_configuration;
+	public static function get_sessions_followed_by_drh($hr_manager_id)
+    {
 		// Database Table Definitions
 		$tbl_session 			= 	Database::get_main_table(TABLE_MAIN_SESSION);
 		$tbl_session_rel_user 	= 	Database::get_main_table(TABLE_MAIN_SESSION_USER);

From 105e30e3fb448a1a2ceaeace9c094f916cdb46d3 Mon Sep 17 00:00:00 2001
From: Yannick Warnier <ywarnier@beeznest.org>
Date: Mon, 16 Sep 2013 13:03:23 -0500
Subject: [PATCH 45/65] Minor - Added colouring to SCORM browser console
 logging

---
 main/newscorm/scorm_api.php | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/main/newscorm/scorm_api.php b/main/newscorm/scorm_api.php
index fc8214aa7c..339155b000 100644
--- a/main/newscorm/scorm_api.php
+++ b/main/newscorm/scorm_api.php
@@ -1104,10 +1104,16 @@ function logit_scorm(message, priority) {
     return false;
 }
 
-function log_in_log(message) {
+function log_in_log(message, priority) {
     var ua = $.browser;
-    if (ua.mozilla) {
-        console.log(message);
+    if (ua.mozilla || ua.webkit) {
+        // Colorize a little
+        var color = "color: green";
+        if (priority == 2) { color = "color:blue"; }
+        elseif (priority == 1) { color = "color:orange"; }
+        elseif (priority == 0) { color = "color:red;font-weight:bold"; }
+        // Log in console with syntax colouring
+        console.log("%c"+message, color);
     } else {
         if (window.console) {
             window.console.log(message);

From 55bdb73fd29c0747481dc72f4cefac5a1c3addd6 Mon Sep 17 00:00:00 2001
From: Yannick Warnier <ywarnier@beeznest.org>
Date: Mon, 16 Sep 2013 13:58:29 -0500
Subject: [PATCH 46/65] Minor change of colours for SCORM console logging

---
 main/newscorm/scorm_api.php | 59 ++++++++++++++++++-------------------
 1 file changed, 29 insertions(+), 30 deletions(-)

diff --git a/main/newscorm/scorm_api.php b/main/newscorm/scorm_api.php
index 339155b000..31adfcbf35 100644
--- a/main/newscorm/scorm_api.php
+++ b/main/newscorm/scorm_api.php
@@ -209,7 +209,7 @@ $(document).ready(function() {
         if (olms.lms_item_types['i'+olms.info_lms_item[1]] != 'sco') {
             LMSInitialize();
         } else {
-            logit_lms('Cant execute LMSInitialize() ');
+            logit_lms('Cant execute LMSInitialize() (type is sco)',2);
         }
     });
 });
@@ -804,7 +804,7 @@ function SetValue(param, val) {
  */
 function savedata(origin) {
     //origin can be 'commit', 'finish' or 'terminate' (depending on the calling function)
-    logit_lms('function savedata() with origin: ' + origin);
+    logit_lms('function savedata() with origin: ' + origin, 3);
 
     //Status is NOT modified here see the lp_ajax_save_item.php file
 
@@ -815,15 +815,15 @@ function savedata(origin) {
     old_item_id = olms.info_lms_item[0];
 
     var item_to_save = olms.lms_item_id;
-    logit_lms('item_to_save original: ' + item_to_save);
+    logit_lms('item_to_save original: ' + item_to_save, 3);
 
     //If saving session_time value we asume that is from the old item not the current one
     if (olms.session_time != '' && olms.session_time != '0') {
-        logit_lms('item_to_save changed to: ' + old_item_id);
+        logit_lms('item_to_save changed to: ' + old_item_id, 3);
         item_to_save = old_item_id;
     }
 
-    logit_lms('item_to_save final: ' + item_to_save);
+    logit_lms('item_to_save final: ' + item_to_save, 3);
 
     //Original behaviour
     //xajax_save_item_scorm(olms.lms_lp_id, olms.lms_user_id, olms.lms_view_id, old_item_id);
@@ -1019,24 +1019,24 @@ function addEvent(elm, evType, fn, useCapture){
  */
 function addListeners(){
     //exit if the browser doesn't support ID or tag retrieval
-    logit_lms('Entering addListeners()',2);
+    logit_lms('Entering addListeners()', 3);
     if (!document.getElementsByTagName){
-        logit_lms("getElementsByTagName not available",2);
+        logit_lms("getElementsByTagName not available", 2);
         return;
     }
     if (!document.getElementById){
-        logit_lms("getElementById not available",2);
+        logit_lms("getElementById not available", 2);
         return;
     }
     //assign event handlers to objects
     if (olms.lms_lp_type==1 || olms.lms_item_type=='asset' || olms.lms_item_type == 'document') {
-        logit_lms('Chamilo LP or asset',2);
+        logit_lms('Chamilo LP or asset');
         //if this path is a Chamilo learnpath, then start manual save
         //when something is loaded in there
         addEvent(window, 'unload', lms_save_asset,false);
-        logit_lms('Added event listener lms_save_asset() on window unload',2);
+        logit_lms('Added event listener lms_save_asset() on window unload', 3);
     }
-    logit_lms('Quitting addListeners()',2);
+    logit_lms('Quitting addListeners()');
 }
 
 /**
@@ -1078,7 +1078,7 @@ function lms_save_asset() {
  * Saving the status will be dealt with by the XAJAX function.
  */
 function chamilo_void_save_asset(score, max, min, status) {
-    logit_lms('chamilo_void_save_asset',2);
+    logit_lms('chamilo_void_save_asset', 3);
     olms.score = score;
     if ((max == null) || (max == '')){
         max = 100;
@@ -1099,7 +1099,7 @@ function chamilo_void_save_asset(score, max, min, status) {
  */
 function logit_scorm(message, priority) {
     if (scorm_logs) {
-        log_in_log("SCORM: " + message);
+        log_in_log("SCORM: " + message, priority);
     }
     return false;
 }
@@ -1108,8 +1108,9 @@ function log_in_log(message, priority) {
     var ua = $.browser;
     if (ua.mozilla || ua.webkit) {
         // Colorize a little
-        var color = "color: green";
-        if (priority == 2) { color = "color:blue"; }
+        var color = "color: black";
+        if (priority == 3) { color = "color:blue"; }
+        elseif (priority == 2) { color = "color:green"; }
         elseif (priority == 1) { color = "color:orange"; }
         elseif (priority == 0) { color = "color:red;font-weight:bold"; }
         // Log in console with syntax colouring
@@ -1128,7 +1129,7 @@ function log_in_log(message, priority) {
  */
 function logit_lms(message, priority){
     if (scorm_logs) {
-        log_in_log("LMS: " + message);
+        log_in_log("LMS: " + message, priority);
     }
     return false;
 }
@@ -1199,7 +1200,7 @@ function update_toc(update_action, update_id, change_ids) {
                 }
                 break;
             default:
-                logit_lms('Update action unknown',2);
+                logit_lms('Update action unknown',1);
                 break;
         }
     }
@@ -1227,7 +1228,7 @@ function update_stats() {
  * Update the stats frame using a reload of the frame to avoid unsynched data
  */
 function update_stats_page() {
-    logit_lms('update_stats_page');
+    logit_lms('update_stats_page',3);
     var myframe = document.getElementById('content_id');
     var mysrc = myframe.location.href;
     if(mysrc == 'lp_controller.php?action=stats'){
@@ -1247,8 +1248,8 @@ function update_stats_page() {
  * @param	string  Display mode (absolute 'abs' or percentage '%').Defaults to %
  */
 function update_progress_bar(nbr_complete, nbr_total, mode) {
-    logit_lms('update_progress_bar('+nbr_complete+', '+nbr_total+', '+mode+')',2);
-    logit_lms('update_progress_bar with params: lms_lp_id= '+olms.lms_lp_id+', lms_view_id= '+olms.lms_view_id+' lms_user_id= '+olms.lms_user_id,2);
+    logit_lms('update_progress_bar('+nbr_complete+', '+nbr_total+', '+mode+')',3);
+    logit_lms('update_progress_bar with params: lms_lp_id= '+olms.lms_lp_id+', lms_view_id= '+olms.lms_view_id+' lms_user_id= '+olms.lms_user_id,3);
 
     if (mode == '') {
         mode='%';
@@ -1330,7 +1331,7 @@ function switch_item(current_item, next_item){
     var orig_item_type      = olms.lms_item_types['i'+current_item];
     var next_item_type      = olms.lms_item_types['i'+next_item];
 
-    logit_lms('switch_item() called with params '+olms.lms_item_id+' and '+next_item+'',0);
+    logit_lms('switch_item() called with params '+olms.lms_item_id+' and '+next_item+'',2);
 
     /*
      There are four "cases" for switching items:
@@ -1526,7 +1527,7 @@ function xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score
     params += '&core_exit='+lms_item_core_exit;
     //console.info(session_time);
     if (olms.lms_lp_type == 1 || item_type == 'document') {
-        logit_lms('xajax_save_item with params:' + params);
+        logit_lms('xajax_save_item with params:' + params,3);
         $.ajax({
             type:"POST",
             data: params,
@@ -1610,7 +1611,7 @@ function xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, lms_item_id)
         is_interactions='false';
     }
 
-    logit_lms('xajax_save_item_scorm with params:' + params);
+    logit_lms('xajax_save_item_scorm with params:' + params,3);
 
     $.ajax({
         type:"POST",
@@ -1630,7 +1631,7 @@ function xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, lms_item_id)
  * @uses    lp_ajax_start_timer.php
  */
 function xajax_start_timer() {
-    logit_lms('xajax_start_timer() called');
+    logit_lms('xajax_start_timer() called',3);
     $.ajax({
         type: "GET",
         url: "lp_ajax_start_timer.php",
@@ -1639,10 +1640,10 @@ function xajax_start_timer() {
         success: function(time) {
             olms.asset_timer = time;
             olms.asset_timer_total = 0;
-            logit_lms('xajax_start_timer result: ' + time);
+            logit_lms('xajax_start_timer result: ' + time,3);
 
             var date = new Date(time * 1000);
-            logit_lms('xajax_start_timer result: ' + date.toString());
+            logit_lms('xajax_start_timer result: ' + date.toString(),3);
         }
     });
 }
@@ -1662,7 +1663,7 @@ function xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,ite
     params += '&iid='+lms_item_id;
     obj_string = '';
 
-    logit_lms('xajax_save_objectives with params:' + params);
+    logit_lms('xajax_save_objectives with params:' + params, 3);
 
     for (i in item_objectives){
         obj_string += '&objectives['+i+']=';
@@ -1702,7 +1703,7 @@ function xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id
         'next': next_item
     };
 
-    logit_lms('xajax_switch_item_details with params:' + params);
+    logit_lms('xajax_switch_item_details with params:' + params, 3);
 
     $.ajax({
         type: "POST",
@@ -1755,7 +1756,6 @@ function attach_glossary_into_scorm(type) {
         logit_lms('attach_glossary_into_scorm failed', 0);
         return false;
     }
-    //logit_lms('attach_glossary_into_scorm', 0);
 
     try {
         var doc = f.contentWindow ? f.contentWindow.document : f.contentDocument ? f.contentDocument : f.document;
@@ -1811,7 +1811,6 @@ function attach_glossary_into_scorm(type) {
                         }
                         //alert(n + ' ' + my_index);
                         $("iframe").contents().find('body').removeHighlight().highlight(n,my_index)
-                        //logit_lms(n+ ' - '+my_index, 0);
                     }
                 }
 

From e2b1827ea2263a157fdd8cf821dd9f19f37fe308 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 12:35:25 +0200
Subject: [PATCH 47/65] Email and passwords can be changed.

---
 main/cron/import_csv.php | 28 +++++++++++++++++++---------
 1 file changed, 19 insertions(+), 9 deletions(-)

diff --git a/main/cron/import_csv.php b/main/cron/import_csv.php
index a8c382f667..cdc5d82191 100644
--- a/main/cron/import_csv.php
+++ b/main/cron/import_csv.php
@@ -412,29 +412,39 @@ class ImportCsv
                         $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
                     }
                 } else {
+
                     if (empty($userInfo)) {
                         $this->logger->addError("Students - Can't update user :".$row['username']);
                         continue;
                     }
 
                     if ($row['action'] == 'delete') {
-                        // INactive one year later
+                        // Inactive one year later
                         $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + 365*24*60*60));
                     }
 
+                    $password = $row['password']; // change password
+                    $email = $row['email']; // change email
+                    $resetPassword = 2; // allow password change
+
+                    // Conditions that disables the update of password and email:
+
                     if (isset($this->conditions['importStudents'])) {
                         if (isset($this->conditions['importStudents']['update']) && isset($this->conditions['importStudents']['update']['avoid'])) {
+                            // Blocking email update
                             $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
                             if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
-                                $this->logger->addInfo("Students - User skipped: ".$row['username']." because the avoid conditions (email).");
-                                continue;
+                                $this->logger->addInfo("Students - User email is not updated : ".$row['username']." because the avoid conditions (email).");
+                                // Do not change email keep the old email.
+                                $email = $userInfo['email'];
                             }
 
+                            // Blocking password update
                             $avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
-
                             if ($userInfo['password'] != api_get_encrypted_password($row['password']) && in_array($row['password'], $avoidUsersWithPassword)) {
-                                $this->logger->addInfo("Students - User skipped: ".$row['username']." because the avoid conditions (password).");
-                                continue;
+                                $this->logger->addInfo("Students - User password is not updated: ".$row['username']." because the avoid conditions (password).");
+                                $password = null;
+                                $resetPassword = 0; // disallow password change
                             }
                         }
                     }
@@ -447,9 +457,9 @@ class ImportCsv
                         $row['firstname'], // <<-- changed
                         $row['lastname'],  // <<-- changed
                         $row['username'],  // <<-- changed
-                        null, //$password = null,
+                        $password, //$password = null,
                         $auth_source = null,
-                        $userInfo['email'],
+                        $email,
                         STUDENT,
                         $userInfo['official_code'],
                         $userInfo['phone'],
@@ -462,7 +472,7 @@ class ImportCsv
                         null, //$language = 'english',
                         null, //$encrypt_method = '',
                         false, //$send_email = false,
-                        0 //$reset_password = 0
+                        $resetPassword //$reset_password = 0
                     );
 
                     if ($result) {

From 717b16fa16d9e76f221d081ac869bc2c2b244fe0 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 14:17:28 +0200
Subject: [PATCH 48/65] Fixing bad condition, if course visibility is hidden
 then return array().

---
 main/inc/lib/course.lib.php | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php
index 5ce1905689..8ce47da246 100644
--- a/main/inc/lib/course.lib.php
+++ b/main/inc/lib/course.lib.php
@@ -3923,8 +3923,12 @@ class CourseManager {
      * @param array  List of courses to which the user is subscribed (if not provided, will be generated)
      * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
      */
-    static function get_access_link_by_user($uid, $course, $user_courses = array()) {
-        if (empty($uid) or empty($course)) { return false; }
+    static function get_access_link_by_user($uid, $course, $user_courses = array())
+    {
+        if (empty($uid) or empty($course)) {
+            return false;
+        }
+
         if (empty($user_courses)) {
             // get the array of courses to which the user is subscribed
             $user_courses = CourseManager::get_courses_list_by_user_id($uid);
@@ -3936,13 +3940,13 @@ class CourseManager {
         if (!isset($course['real_id']) && empty($course['real_id'])) {
             $course = api_get_course_info($course['code']);
         }
-        if ($course['visibility'] != COURSE_VISIBILITY_HIDDEN) {
+
+        if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
             return array();
         }
 
         $is_admin = api_is_platform_admin_by_id($uid);
         $options = array();
-
         // Register button
         if (!api_is_anonymous($uid) &&
             !$is_admin &&
@@ -3964,6 +3968,7 @@ class CourseManager {
         ) {
             $options[]=  'enter';
         }
+
         return $options;
     }
 

From c6b00d7eb6bba6dacac6c4c6090c33b9a928079e Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 14:19:06 +0200
Subject: [PATCH 49/65] Fixing missing real_id and point_info keys, while
 searching the catalog.

---
 main/inc/lib/auth.lib.php | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/main/inc/lib/auth.lib.php b/main/inc/lib/auth.lib.php
index 4ffe6316b6..f7ba4f2a23 100644
--- a/main/inc/lib/auth.lib.php
+++ b/main/inc/lib/auth.lib.php
@@ -555,7 +555,8 @@ class Auth {
      * @param string $search_term: the string that the user submitted, what we are looking for
      * @return array an array containing a list of all the courses (the code, directory, dabase, visual_code, title, ... ) matching the the search term.
      */
-    public function search_courses($search_term) {
+    public function search_courses($search_term)
+    {
         $TABLECOURS = 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);
@@ -595,7 +596,12 @@ class Auth {
             $row['registration_code'] = !empty($row['registration_code']);
             $count_users = count(CourseManager::get_user_list_from_course_code($row['code']));
             $count_connections_last_month = Tracking::get_course_connections_count($row['code'], 0, api_get_utc_datetime(time() - (30 * 86400)));
+
+            $point_info = CourseManager::get_course_ranking($row['id'], 0);
+
             $courses[] = array(
+                'real_id' => $row['id'],
+                'point_info' => $point_info,
                 'code' => $row['code'],
                 'directory' => $row['directory'],
                 'db' => $row['db_name'],

From 7e34cb922b497a9a4eb3dcea09666f79cd933f4f Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 14:41:57 +0200
Subject: [PATCH 50/65] Minor - format code

---
 main/auth/courses.php                             | 5 ++---
 main/inc/lib/auth.lib.php                         | 3 ++-
 main/template/default/auth/courses_categories.php | 1 +
 main/template/default/auth/courses_list.php       | 2 +-
 4 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/main/auth/courses.php b/main/auth/courses.php
index b1778154a5..5363731a85 100644
--- a/main/auth/courses.php
+++ b/main/auth/courses.php
@@ -76,7 +76,7 @@ if (api_is_platform_admin() || api_is_course_admin() || api_is_allowed_to_create
 }
 
 // filter actions
-$actions = array('sortmycourses', 'createcoursecategory', 'subscribe', 'deletecoursecategory', 'display_courses', 'display_random_courses' , 'subscribe_user_with_password');
+$actions = array('sortmycourses', 'createcoursecategory', 'subscribe', 'deletecoursecategory', 'display_courses', 'display_random_courses', 'subscribe_user_with_password');
 $action = 'display_random_courses';
 $nameTools = get_lang('SortMyCourses');
 
@@ -118,8 +118,6 @@ if (empty($nameTools)) {
 // course description controller object
 $courses_controller = new CoursesController();
 
-
-
 // We are moving a course or category of the user up/down the list (=Sort My Courses).
 if (isset($_GET['move'])) {
 	if (isset($_GET['course'])) {
@@ -191,6 +189,7 @@ if (isset($_POST['unsubscribe'])) {
             //$message = remove_user_from_course($_user['user_id'], $_POST['unsubscribe']);
 	}
 }
+
 switch ($action) {
     case 'subscribe_user_with_password':
         $courses_controller->subscribe_user($_POST['subscribe_user_with_password'], $_POST['search_term'], $_POST['category_code']);
diff --git a/main/inc/lib/auth.lib.php b/main/inc/lib/auth.lib.php
index f7ba4f2a23..541f084992 100644
--- a/main/inc/lib/auth.lib.php
+++ b/main/inc/lib/auth.lib.php
@@ -625,7 +625,8 @@ class Auth {
      * @param string Course code
      * @return string  Message about results
      */
-    public function subscribe_user($course_code) {
+    public function subscribe_user($course_code)
+    {
         $user_id = api_get_user_id();
         $all_course_information = CourseManager::get_course_information($course_code);
 
diff --git a/main/template/default/auth/courses_categories.php b/main/template/default/auth/courses_categories.php
index e0c6273691..5a6f29f93d 100644
--- a/main/template/default/auth/courses_categories.php
+++ b/main/template/default/auth/courses_categories.php
@@ -146,6 +146,7 @@ $stok = Security::get_token();
         if (!empty($browse_courses_in_category)) {
 
             foreach ($browse_courses_in_category as $course) {
+
                 // if course is closed, don't show it.
                 if ($course['visibility'] == COURSE_VISIBILITY_CLOSED || $course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
                     continue;
diff --git a/main/template/default/auth/courses_list.php b/main/template/default/auth/courses_list.php
index fd01cac3e3..d748eebe06 100644
--- a/main/template/default/auth/courses_list.php
+++ b/main/template/default/auth/courses_list.php
@@ -7,7 +7,7 @@
 * @package chamilo.auth
 */
 
-// Acces rights: anonymous users can't do anything usefull here.
+// Access rights: anonymous users can't do anything usefull here.
 api_block_anonymous_users();
 $stok = Security::get_token();
 $courses_without_category = $courses_in_category[0];

From 9f5e8046761bdf930256ba3e347336bdae0b0d37 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 14:43:08 +0200
Subject: [PATCH 51/65] Fixing password protected course.

---
 main/auth/courses_controller.php | 26 +++++++++++++++-----------
 1 file changed, 15 insertions(+), 11 deletions(-)

diff --git a/main/auth/courses_controller.php b/main/auth/courses_controller.php
index 33d2bde955..37faf660a1 100644
--- a/main/auth/courses_controller.php
+++ b/main/auth/courses_controller.php
@@ -128,9 +128,13 @@ class CoursesController { // extends Controller {
     }
 
     /**
-     * Search courses
+     *
+     * @param string $search_term
+     * @param string $message
+     * @param string $error
+     * @param string $content
      */
-    public function search_courses($search_term, $message = '', $error = '') {
+    public function search_courses($search_term, $message = '', $error = '', $content = null) {
 
         $data = array();
 
@@ -148,13 +152,14 @@ class CoursesController { // extends Controller {
 
         // we need only the course codes as these will be used to match against the courses of the category
         if ($user_courses != '') {
-            foreach ($user_courses as $key => $value) {
-                    $user_coursecodes[] = $value['code'];
+            foreach ($user_courses as $value) {
+                $user_coursecodes[] = $value['code'];
             }
         }
 
         $data['user_coursecodes'] = $user_coursecodes;
         $data['message']    = $message;
+        $data['content']    = $content;
         $data['error']      = $error;
         $data['action']     = 'display_courses';
 
@@ -163,14 +168,13 @@ class CoursesController { // extends Controller {
         $this->view->set_layout('layout');
         $this->view->set_template('courses_categories');
         $this->view->render();
-
     }
 
     /**
-     * Auto user subcription to a course
+     * Auto user subscription to a course
      */
-    public function subscribe_user($course_code, $search_term, $category_code) {
-        $data = array();
+    public function subscribe_user($course_code, $search_term, $category_code)
+    {
         $courseInfo = api_get_course_info($course_code);
         // The course must be open in order to access the auto subscription
         if (in_array($courseInfo['visibility'], array(COURSE_VISIBILITY_CLOSED, COURSE_VISIBILITY_REGISTERED, COURSE_VISIBILITY_HIDDEN))) {
@@ -181,16 +185,16 @@ class CoursesController { // extends Controller {
             if (!$result) {
                 $error = get_lang('CourseRegistrationCodeIncorrect');
             } else {
-                //Redirect directly to the course after subscription
+                // Redirect directly to the course after subscription
                 $message = $result['message'];
                 $content = $result['content'];
             }
         }
 
         if (!empty($search_term)) {
-            $this->search_courses($search_term, $message, $error);
+            $this->search_courses($search_term, $message, $error, $content);
         } else {
-            $this->courses_categories('subcribe', $category_code, $message, $error, $content);
+            $this->courses_categories('subscribe', $category_code, $message, $error, $content);
         }
         return $result;
     }

From dde291e3abf09788cc16b0b2eac8011bfd78f7f9 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 15:42:53 +0200
Subject: [PATCH 52/65] Fixing coaches assignation when updating the course
 session using the course_edit.php or a import via a CSV file see BT#6665

---
 main/admin/course_edit.php          |  2 +-
 main/inc/lib/course.lib.php         | 12 ++++----
 main/inc/lib/sessionmanager.lib.php | 45 ++++++++++++++++++++++-------
 3 files changed, 42 insertions(+), 17 deletions(-)

diff --git a/main/admin/course_edit.php b/main/admin/course_edit.php
index b96efcada7..26f1c42906 100644
--- a/main/admin/course_edit.php
+++ b/main/admin/course_edit.php
@@ -126,7 +126,7 @@ $form->addGroup($group,'group',get_lang('CourseTeachers'),'</td><td width="80" a
 		'<input class="arrowr" style="width:30px;height:30px;padding-right:12px" type="button" onclick="moveItem(document.getElementById(\'platform_teachers\'), document.getElementById(\'course_teachers\'))" ><br><br>' .
 		'<input class="arrowl" style="width:30px;height:30px;padding-left:13px" type="button" onclick="moveItem(document.getElementById(\'course_teachers\'), document.getElementById(\'platform_teachers\'))" ></td><td>');
 
-$form->addElement('checkbox', 'add_teachers_to_sessions', array(null, null, get_lang('TeachersWillBeAddedAsCoachInAllCourseSessions')));
+$form->addElement('checkbox', 'add_teachers_to_sessions', null, get_lang('TeachersWillBeAddedAsCoachInAllCourseSessions'));
 
 $categories_select = $form->addElement('select', 'category_code', get_lang('CourseFaculty'), $categories , array('style'=>'width:350px','id'=>'category_code_id', 'class'=>'chzn-select'));
 $categories_select->addOption('-', '');
diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php
index 8ce47da246..fcb467ffb8 100644
--- a/main/inc/lib/course.lib.php
+++ b/main/inc/lib/course.lib.php
@@ -3988,6 +3988,8 @@ class CourseManager {
             $teachers = array($teachers);
         }
 
+        $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code($course_code);
+
         $course_user_table  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
         // Delete only teacher relations that doesn't match the selected teachers
@@ -4003,8 +4005,7 @@ class CourseManager {
 
         if (count($teachers) > 0) {
             foreach ($teachers as $key) {
-
-                //We check if the teacher is already subscribed in this course
+                // We check if the teacher is already subscribed in this course
                 $sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'" ';
                 $result = Database::query($sql_select_teacher);
 
@@ -4024,17 +4025,18 @@ class CourseManager {
             }
         }
 
-
         if ($editTeacherInSessions) {
             $sessions = SessionManager::get_session_by_course($course_code);
             if (!empty($sessions)) {
                 foreach ($sessions as $session) {
-                    $alreadyAddedTeachers = SessionManager::getCoachByCourseSession($session['id'], $course_code);
                     foreach ($teachers as $userId) {
                         SessionManager::set_coach_to_course_session($userId, $session['id'], $course_code);
                     }
+                    $teachersToDelete = array();
+                    if (!empty($alreadyAddedTeachers)) {
+                        $teachersToDelete = array_diff(array_keys($alreadyAddedTeachers), $teachers);
+                    }
 
-                    $teachersToDelete = array_diff($alreadyAddedTeachers, $teachers);
                     if (!empty($teachersToDelete)) {
                         foreach ($teachersToDelete as $userId) {
                             SessionManager::set_coach_to_course_session($userId, $session['id'], $course_code, true);
diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 80d0ffaaa1..26ff600d2e 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -1602,10 +1602,11 @@ class SessionManager
     /**
      * Get users by session
      * @param  int session id
-     * @param	int	filter by status
+     * @param	int	filter by status coach = 2
      * @return  array a list with an user list
      */
-    public static function get_users_by_session($id, $with_status = null) {
+    public static function get_users_by_session($id, $with_status = null)
+    {
         if (empty($id)) {
             return array();
         }
@@ -2232,23 +2233,40 @@ class SessionManager
 
                         // Adding coaches to session course user
                         if (!empty($course_coaches)) {
+
+                            $savedCoaches = array();
+                            // Adding course teachers as course session teachers
+                            $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code($course_code);
+
+                            if (!empty($alreadyAddedTeachers)) {
+                                $teachersToAdd = array();
+                                foreach ($alreadyAddedTeachers as $user) {
+                                    $teachersToAdd[] = $user['username'];
+                                }
+                                $course_coaches = array_merge($course_coaches, $teachersToAdd);
+                            }
+
                             foreach ($course_coaches as $course_coach) {
                                 $course_coach = trim($course_coach);
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-                                            id_user='$coach_id',
-                                            course_code='$course_code',
+                                            id_user = '$coach_id',
+                                            course_code = '$course_code',
                                             id_session = '$session_id',
                                             status = 2 ";
                                     Database::query($sql);
                                     if ($debug) {
                                         $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
                                     }
+                                    $savedCoaches[] = $coach_id;
                                 } else {
                                     $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
                                 }
                             }
+
+
+
                         }
 
                         $users_in_course_counter = 0;
@@ -2294,21 +2312,26 @@ class SessionManager
         );
     }
 
-    public static function getCoachByCourseSession($sessionId, $courseCode)
+    /**
+     * @param int $sessionId
+     * @param string $courseCode
+     * @return array
+     */
+    public static function getCoachesByCourseSession($sessionId, $courseCode)
     {
         $tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $sessionId = intval($sessionId);
         $courseCode = Database::escape_string($courseCode);
 
         $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$sessionId' AND course_code = '$courseCode' AND status = 2";
-        $rs_coachs = Database::query($sql);
+        $result = Database::query($sql);
 
-        $coachs_course_session = array();
-        if (Database::num_rows($rs_coachs) > 0){
-            while ($row_coachs = Database::fetch_row($rs_coachs)) {
-                $coachs_course_session[] = $row_coachs[0];
+        $coaches = array();
+        if (Database::num_rows($result) > 0){
+            while ($row = Database::fetch_row($result)) {
+                $coaches[] = $row[0];
             }
         }
-        return $coachs_course_session;
+        return $coaches;
     }
 }

From d7275b1cb9af92fb2c248da3c9decc5101074692 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 16:14:47 +0200
Subject: [PATCH 53/65] Minor - adding edit button

---
 main/admin/user_information.php | 55 ++++++++++-----------------------
 1 file changed, 16 insertions(+), 39 deletions(-)

diff --git a/main/admin/user_information.php b/main/admin/user_information.php
index 946e51bcc8..6295734d4d 100644
--- a/main/admin/user_information.php
+++ b/main/admin/user_information.php
@@ -25,9 +25,9 @@ Display::display_header($tool_name);
 $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 if ( isset($_GET['action']) ) {
-    switch($_GET['action']) {
+    switch ($_GET['action']) {
         case 'unsubscribe':
-            if ( CourseManager::get_user_in_course_status($_GET['user_id'],$_GET['course_code']) == STUDENT) {
+            if (CourseManager::get_user_in_course_status($_GET['user_id'],$_GET['course_code']) == STUDENT) {
                 CourseManager::unsubscribe_user($_GET['user_id'],$_GET['course_code']);
                 Display::display_normal_message(get_lang('UserUnsubscribed'));
             } else {
@@ -36,22 +36,29 @@ if ( isset($_GET['action']) ) {
             break;
     }
 }
-//only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
+// only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
 $statusname = api_get_status_langvars();
-$login_as_icon = '';
+$login_as_icon = null;
+$editUser = null;
 if (api_is_platform_admin() || (api_is_session_admin() && $row['6'] == $statusname[STUDENT])) {
-        $login_as_icon = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&amp;user_id='.$user['user_id'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>';
+    $login_as_icon = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&amp;user_id='.$user['user_id'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>';
+    $editUser = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array()), api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user['user_id']);
 }
-echo '<div class="actions"><a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.intval($_GET['user_id']).'" title="'.get_lang('Reporting').'">'.Display::return_icon('statistics.png',get_lang('Reporting'),'',  ICON_SIZE_MEDIUM).'</a>'.$login_as_icon.'</div>';
+echo '<div class="actions">
+        <a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.intval($_GET['user_id']).'" title="'.get_lang('Reporting').'">'.Display::return_icon('statistics.png',get_lang('Reporting'),'',  ICON_SIZE_MEDIUM).'
+        </a>
+        '.$login_as_icon.'
+        '.$editUser.'
+    </div>';
 
 echo Display::page_header($tool_name);
 
-//getting the user image
+// Getting the user image
 $sysdir_array = UserManager::get_user_picture_path_by_id($user['user_id'],'system',false,true);
 $sysdir = $sysdir_array['dir'];
 $webdir_array = UserManager::get_user_picture_path_by_id($user['user_id'],'web',false,true);
 $webdir = $webdir_array['dir'];
-$fullurl=$webdir.$webdir_array['file'];
+$fullurl = $webdir.$webdir_array['file'];
 $system_image_path=$sysdir.$webdir_array['file'];
 list($width, $height, $type, $attr) = @getimagesize($system_image_path);
 $resizing = (($height > 200) ? 'height="200"' : '');
@@ -64,7 +71,7 @@ echo '<p>'. ($user['status'] == 1 ? get_lang('Teacher') : get_lang('Student')).'
 echo '<p>'.Display :: encrypted_mailto_link($user['mail'], $user['mail']).'</p>';
 
 /**
- * Show the sessions and the courses in wich this user is subscribed
+ * Show the sessions and the courses in which this user is subscribed
  */
 
 echo Display::page_subheader(get_lang('SessionList'));
@@ -152,35 +159,6 @@ if (Database::num_rows($res) > 0) {
 } else {
     echo '<p>'.get_lang('NoCoursesForThisUser').'</p>';
 }
-
-/**
- * Show the classes in which this user is subscribed
- */
-/*
-$table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
-$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-$sql = 'SELECT * FROM '.$table_class_user.' cu, '.$table_class.' c '.
-    ' WHERE cu.user_id = '.$user['user_id'].' AND cu.class_id = c.id';
-$res = Database::query($sql);
-if (Database::num_rows($res) > 0) {
-    $header = array();
-    $header[] = array (get_lang('ClassName'), true);
-    $header[] = array ('', false);
-    $data = array ();
-    while ($class = Database::fetch_object($res)) {
-        $row = array();
-        $row[] = $class->name;
-        $row[] = '<a href="class_information.php?id='.$class->id.'">'.Display::return_icon('synthese_view.gif', get_lang('Overview')).'</a>';
-        $data[] = $row;
-    }
-    echo '<p><b>'.get_lang('Classes').'</b></p>';
-    echo '<blockquote>';
-    Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));
-    echo '</blockquote>';
-} else {
-    echo '<p>'.get_lang('NoClassesForThisUser').'</p>';
-}*/
-
 /**
  * Show the URL in which this user is subscribed
  */
@@ -203,5 +181,4 @@ if ($_configuration['multiple_access_urls']) {
     }
 }
 
-/* FOOTER */
 Display::display_footer();

From 45ee32f7db3ce138eaddf2c6860d8afb996c9273 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 16:17:04 +0200
Subject: [PATCH 54/65] If a coach user is deleted, the admin is assigned as
 coach and session_admin_id see BT#6692

---
 main/inc/lib/usermanager.lib.php | 29 ++++++++++++++++++++---------
 1 file changed, 20 insertions(+), 9 deletions(-)

diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php
index 52579d6cf6..a5c4c7a505 100644
--- a/main/inc/lib/usermanager.lib.php
+++ b/main/inc/lib/usermanager.lib.php
@@ -256,20 +256,23 @@ class UserManager
      */
     public static function delete_user($user_id)
     {
-
-        if ($user_id != strval(intval($user_id)))
+        if ($user_id != strval(intval($user_id))) {
             return false;
-        if ($user_id === false)
+        }
+
+        if ($user_id === false) {
             return false;
+        }
 
         if (!self::can_delete_user($user_id)) {
             return false;
         }
+
         $table_user = Database :: get_main_table(TABLE_MAIN_USER);
         $usergroup_rel_user = Database :: get_main_table(TABLE_USERGROUP_REL_USER);
         $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-        //$table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
         $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $table_session = Database :: get_main_table(TABLE_MAIN_SESSION);
         $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
         $table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
         $table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
@@ -302,6 +305,14 @@ class UserManager
         $sql = "DELETE FROM $table_session_course_user WHERE id_user = '".$user_id."'";
         Database::query($sql);
 
+        // If the user was added as a id_coach then set the current admin as coach see BT#
+        $currentUserId = api_get_user_id();
+        $sql = "UPDATE $table_session SET id_coach = $currentUserId  WHERE id_coach = '".$user_id."'";
+        Database::query($sql);
+
+        $sql = "UPDATE $table_session SET id_coach = $currentUserId  WHERE session_admin_id = '".$user_id."'";
+        Database::query($sql);
+
         // Unsubscribe user from all sessions
         $sql = "DELETE FROM $table_session_user WHERE id_user = '".$user_id."'";
         Database::query($sql);
@@ -361,17 +372,17 @@ class UserManager
                 }
             }
 
-            //Delete user from friend lists
+            // Delete user from friend lists
             SocialManager::remove_user_rel_user($user_id, true);
         }
 
-        //Removing survey invitation
+        // Removing survey invitation
         survey_manager::delete_all_survey_invitations_by_user($user_id);
 
         // Delete students works
-        $sqlw = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0";
-        Database::query($sqlw);
-        unset($sqlw);
+        $sql = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0";
+        Database::query($sql);
+
         // Add event to system log
         $user_id_manager = api_get_user_id();
         event_system(LOG_USER_DELETE, LOG_USER_ID, $user_id, api_get_utc_datetime(), $user_id_manager, null, $user_info);

From d27ae31b8aa4f696bfc2e47ed4a63b6e2abd4b90 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 17:01:30 +0200
Subject: [PATCH 55/65] Fixing query

---
 main/inc/lib/sessionmanager.lib.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php
index 26ff600d2e..a91774dec6 100644
--- a/main/inc/lib/sessionmanager.lib.php
+++ b/main/inc/lib/sessionmanager.lib.php
@@ -2033,7 +2033,7 @@ class SessionManager
 
                 $extraSessionParameters = null;
                 if (!empty($sessionDescription)) {
-                    $extraSessionParameters = ' , description = '.Database::escape_string($sessionDescription);
+                    $extraSessionParameters = " , description = '".Database::escape_string($sessionDescription)."'";
                 }
 
                 // Searching a general coach.

From 9e045b85cfb0fbffb504d6827c4288e2d2a729e9 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 17:27:00 +0200
Subject: [PATCH 56/65] Comment code that deletes the attempt of the user see
 BT#6524 and #6708

---
 main/exercice/exercise_result.php | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/main/exercice/exercise_result.php b/main/exercice/exercise_result.php
index 985a0ea8b4..33f62707ab 100644
--- a/main/exercice/exercise_result.php
+++ b/main/exercice/exercise_result.php
@@ -138,12 +138,13 @@ display_question_list_by_attempt($objExercise, $exe_id, true);
 
 //If is not valid
 
+/*
 $session_control_key = get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id);
 if (isset($session_control_key) && !exercise_time_control_is_valid($objExercise->id, $learnpath_id, $learnpath_item_id)) {
 	$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 	$sql_fraud = "UPDATE $TBL_TRACK_ATTEMPT SET answer = 0, marks = 0, position = 0 WHERE exe_id = $exe_id ";
 	Database::query($sql_fraud);
-}
+}*/
 
 //Unset session for clock time
 exercise_time_control_delete($objExercise->id, $learnpath_id, $learnpath_item_id);

From a58bd1c7e4402196b4060a8be4f84339dd3c5acc Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 18:08:57 +0200
Subject: [PATCH 57/65] Minor - format code + adding exit after a header call.

---
 main/exercice/exercise_submit.php | 4 ++--
 main/newscorm/lp_content.php      | 1 +
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/main/exercice/exercise_submit.php b/main/exercice/exercise_submit.php
index 2c081ba4e1..f7cd888c57 100644
--- a/main/exercice/exercise_submit.php
+++ b/main/exercice/exercise_submit.php
@@ -326,14 +326,14 @@ if ($time_control) {
     if ($debug) { error_log("7 No time control"); };
 }
 
-// Get time left for exipiring time
+// Get time left for expiring time
 $time_left = api_strtotime($clock_expired_time,'UTC') - time();
 
 /*
  * The time control feature is enable here - this feature is enable for a jquery plugin called epiclock
  * for more details of how it works see this link : http://eric.garside.name/docs.html?p=epiclock
  */
-if ($time_control) { //Sends the exercice form when the expired time is finished
+if ($time_control) { //Sends the exercise form when the expired time is finished
 	$htmlHeadXtra[] = $objExercise->show_time_control_js($time_left);
 }
 
diff --git a/main/newscorm/lp_content.php b/main/newscorm/lp_content.php
index a573bcf6fb..3c8e7b8197 100644
--- a/main/newscorm/lp_content.php
+++ b/main/newscorm/lp_content.php
@@ -22,6 +22,7 @@ if (empty($lp_controller_touched)) {
         error_log('New lp - In lp_content.php - Redirecting to lp_controller', 0);
     }
     header('location: lp_controller.php?action=content&lp_id='.Security::remove_XSS($_REQUEST['lp_id']).'&item_id='.Security::remove_XSS($_REQUEST['item_id']));
+    exit;
 }
 $_SESSION['oLP']->error = '';
 $lp_type = $_SESSION['oLP']->get_type();

From e584cddffda2b8e3db6f78e11d30b67cc8805d2c Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Tue, 17 Sep 2013 19:17:35 +0200
Subject: [PATCH 58/65] Fixing PHP import errors see BT#6719

---
 main/admin/user_import.php | 30 ++++++++++--------------------
 main/admin/user_list.php   | 11 ++++++-----
 2 files changed, 16 insertions(+), 25 deletions(-)

diff --git a/main/admin/user_import.php b/main/admin/user_import.php
index ce4c6a02cf..c625953474 100644
--- a/main/admin/user_import.php
+++ b/main/admin/user_import.php
@@ -123,7 +123,7 @@ function save_data($users) {
     require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
     $send_mail = $_POST['sendMail'] ? 1 : 0;
     if (is_array($users)) {
-        foreach ($users as $index => $user)	{
+        foreach ($users as $user) {
             $user = complete_missing_data($user);
             $user['Status'] = api_status_key($user['Status']);
             $user_id = UserManager :: create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], $user['language'], $user['PhoneNumber'], '', $user['AuthSource'], null, 1, 0, null, null, $send_mail);
@@ -276,12 +276,13 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
     $file_type = $_POST['file_type'];
     Security::clear_token();
     $tok = Security::get_token();
-    $allowed_file_mimetype = array('csv','xml');
+    $allowed_file_mimetype = array('csv', 'xml');
     $error_kind_file = false;
 
-    $ext_import_file = substr($_FILES['import_file']['name'],(strrpos($_FILES['import_file']['name'],'.')+1));
+    $uploadInfo = pathinfo($_FILES['import_file']['name']);
+    $ext_import_file = $uploadInfo['extension'];
 
-    if (in_array($ext_import_file,$allowed_file_mimetype)) {
+    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);
@@ -297,8 +298,9 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
         $error_kind_file = true;
     }
 
-    // List user id whith error.
+    // 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'];
@@ -327,17 +329,6 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
     } else {
         $see_message_import = get_lang('FileImported');
     }
-    /*
-    $msg2 = '';
-    if (count($inserted_in_course) > 1) {
-        $msg2 .= '<br>'.get_lang('UsersSubscribedToSeveralCoursesBecauseOfVirtualCourses').':';
-        foreach ($inserted_in_course as $course) {
-            $msg2 .= ' '.$course.',';
-        }
-        $msg2 = substr($msg2, 0, -1);
-        $msg2 .= '</br>';
-    }
-    */
 
     if (count($errors) != 0) {
         $warning_message = '<ul>';
@@ -350,10 +341,9 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
     }
 
     // if the warning message is too long then we display the warning message trough a session
-    if (api_strlen($warning_message) > 150) {
-        $_SESSION['session_message_import_users'] = $warning_message;
-        $warning_message = 'session_message';
-    }
+
+    $_SESSION['session_message_import_users'] = $warning_message;
+    $warning_message = 'session_message';
 
     if ($error_kind_file) {
         $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
diff --git a/main/admin/user_list.php b/main/admin/user_list.php
index bbff1ed611..9da1cf55d9 100644
--- a/main/admin/user_list.php
+++ b/main/admin/user_list.php
@@ -706,16 +706,18 @@ if (!empty($action)) {
                 }
                 break;
 			case 'show_message' :
+                if (!empty($_GET['message'])) {
+                    $message = Display :: return_message(stripslashes($_GET['message']), 'confirmation');
+                }
+
                 if (!empty($_GET['warn'])) {
                 	// to prevent too long messages
                 	if ($_GET['warn'] == 'session_message'){
-                		$_GET['warn'] = $_SESSION['session_message_import_users'];
+                        $_GET['warn'] = $_SESSION['session_message_import_users'];
                 	}
                 	$message = Display::return_message(urldecode($_GET['warn']),'warning', false);
                 }
-                if (!empty($_GET['message'])) {
-                    $message = Display :: return_message(stripslashes($_GET['message']), 'confirmation');
-                }
+
 				break;
 			case 'delete_user' :
 				if (api_is_platform_admin()) {
@@ -969,7 +971,6 @@ if ($table->get_total_number_of_items() == 0) {
 }
 
 $tpl = new Template($tool_name);
-
 $tpl->assign('actions', $actions);
 $tpl->assign('message', $message);
 $tpl->assign('content', $form.$table_result.$extra_search_options);

From c08cbc0481eb7b54530d9cf61d4401689196fd6d Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Wed, 18 Sep 2013 11:36:25 +0200
Subject: [PATCH 59/65] Fixing class import see BT#6722

---
 main/admin/usergroup_user_import.php | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)

diff --git a/main/admin/usergroup_user_import.php b/main/admin/usergroup_user_import.php
index 4081f1528c..4899976bd5 100644
--- a/main/admin/usergroup_user_import.php
+++ b/main/admin/usergroup_user_import.php
@@ -6,7 +6,7 @@
 /**
  * Code
  * This tool allows platform admins to update class-user relations by uploading
- * a CSVfile
+ * a CSV file
  */
 
 /**
@@ -23,16 +23,16 @@ function validate_data($user_classes) {
         // 1. Check whether mandatory fields are set.
         $mandatory_fields = array('UserName', 'ClassName');
 
-        foreach ($mandatory_fields as $key => $field) {
+        foreach ($mandatory_fields as $field) {
             if (!isset($user_class[$field]) || strlen($user_class[$field]) == 0) {
                 $user_class['error'] = get_lang($field . 'Mandatory');
                 $errors[] = $user_class;
             }
         }
 
-        // 2. Check whether classcode exists.
+        // 2. Check whether class code exists.
         if (isset($user_class['ClassName']) && strlen($user_class['ClassName']) != 0) {
-            // 2.1 Check whether code has been allready used in this CVS-file.
+            // 2.1 Check whether code has been already used in this CVS-file.
             if (!isset($classcodes[$user_class['ClassName']])) {
                 // 2.1.1 Check whether code exists in DB
                 $exists = $usergroup->usergroup_exists($user_class['ClassName']);
@@ -67,7 +67,7 @@ function validate_data($user_classes) {
 /**
  * Saves imported data.
  */
-function save_data($users_classes) {
+function save_data($users_classes, $deleteUsersNotInList = false) {
 
     global $purification_option_for_usernames;
 
@@ -81,7 +81,8 @@ function save_data($users_classes) {
     if (!empty($users_classes)) {
 
         foreach ($users_classes as $user_class) {
-            $sql1 = "SELECT user_id FROM $user_table WHERE username = '" . Database::escape_string(UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames)) . "'";
+            $sql1 = "SELECT user_id FROM $user_table
+                     WHERE username = '".Database::escape_string(UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames))."'";
             $res1 = Database::query($sql1);
             $obj1 = Database::fetch_object($res1);
 
@@ -103,7 +104,7 @@ function save_data($users_classes) {
             $user_list = $user_data['user_list'];
             $class_name = $user_data['class_name'];
             $user_list_name = $user_data['user_list_name'];
-            $usergroup->subscribe_users_to_usergroup($class_id, $user_list, false);
+            $usergroup->subscribe_users_to_usergroup($class_id, $user_list, $deleteUsersNotInList);
             $message .= Display::return_message(get_lang('Class') . ': ' . $class_name . '<br />', 'normal', false);
             $message .= Display::return_message(get_lang('Users') . ': ' . implode(', ', $user_list_name));
         }
@@ -146,14 +147,15 @@ $form = new FormValidator('class_user_import');
 $form->addElement('header', $tool_name);
 $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
 //$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
-//$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
+$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
 $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
 
 if ($form->validate()) {
     $users_classes = parse_csv_data($_FILES['import_file']['tmp_name']);
     $errors = validate_data($users_classes);
     if (count($errors) == 0) {
-        $return = save_data($users_classes);
+        $deleteUsersNotInList = isset($_REQUEST['unsubscribe']) && !empty($_REQUEST['unsubscribe']) ? true : false;
+        $return = save_data($users_classes, $deleteUsersNotInList);
     }
 }
 

From adfe4f5f05adb594a8c86ab4327004b788243dc5 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Wed, 18 Sep 2013 13:13:44 +0200
Subject: [PATCH 60/65] Minor - format code

---
 main/admin/add_courses_to_session.php | 57 +++++++--------------------
 1 file changed, 15 insertions(+), 42 deletions(-)

diff --git a/main/admin/add_courses_to_session.php b/main/admin/add_courses_to_session.php
index f09736e276..eb5487fc5d 100644
--- a/main/admin/add_courses_to_session.php
+++ b/main/admin/add_courses_to_session.php
@@ -81,7 +81,6 @@ function remove_item(origin)
 }
 </script>';
 
-
 $formSent=0;
 $errorMsg=$firstLetterCourse=$firstLetterSession='';
 $CourseList=$SessionList=array();
@@ -89,13 +88,12 @@ $courses=$sessions=array();
 $noPHP_SELF=true;
 
 if (isset($_POST['formSent']) && $_POST['formSent']) {
-
 	$formSent              = $_POST['formSent'];
 	$firstLetterCourse     = $_POST['firstLetterCourse'];
 	$firstLetterSession    = $_POST['firstLetterSession'];
 	$CourseList            = $_POST['SessionCoursesList'];
 	if (!is_array($CourseList)) {
-		$CourseList=array();
+		$CourseList = array();
 	}
 	$nbr_courses=0;
 
@@ -141,10 +139,9 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 			}
 			Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'");
 		}
-
 	}
 
-	foreach($existingCourses as $existingCourse) {
+	foreach ($existingCourses as $existingCourse) {
 		if(!in_array($existingCourse['course_code'], $CourseList)) {
 		    $course_info = api_get_course_info($existingCourse['course_code']);
             CourseManager::remove_course_ranking($course_info['real_id'], $id_session);
@@ -156,20 +153,17 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 	$nbr_courses=count($CourseList);
 	Database::query("UPDATE $tbl_session SET nbr_courses=$nbr_courses WHERE id='$id_session'");
 
-	if(isset($_GET['add']))
+	if (isset($_GET['add']))
 		header('Location: add_users_to_session.php?id_session='.$id_session.'&add=true');
 	else
 		header('Location: resume_session.php?id_session='.$id_session);
-		//header('Location: '.$_GET['page'].'?id_session='.$id_session);
+    exit;
 }
 
-// display the dokeos header
+// display the header
 Display::display_header($tool_name);
 
-// display the tool title
-// api_display_tool_title($tool_name);
-
-if($add_type == 'multiple') {
+if ($add_type == 'multiple') {
 	$link_add_type_unique = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=unique">'.Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'</a>';
 	$link_add_type_multiple = Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').' ';
 } else {
@@ -177,17 +171,12 @@ if($add_type == 'multiple') {
 	$link_add_type_multiple = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=multiple">'.Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').'</a>';
 }
 
-
 // the form header
 $session_info = SessionManager::fetch($id_session);
 echo '<div class="actions">';
 echo $link_add_type_unique.$link_add_type_multiple;
 echo '</div>';
 
-/*$sql = 'SELECT COUNT(1) FROM '.$tbl_course;
-$rs = Database::query($sql);
-$count_courses = Database::result($rs, 0, 0);*/
-
 $ajax_search = $add_type == 'unique' ? true : false;
 $nosessionCourses = $sessionCourses = array();
 if ($ajax_search) {
@@ -215,14 +204,14 @@ if ($ajax_search) {
 		}
 	}
 
-	$result=Database::query($sql);
-	$Courses=Database::store_result($result);
+	$result = Database::query($sql);
+	$Courses = Database::store_result($result);
 
-	foreach($Courses as $course) {
+	foreach ($Courses as $course) {
 		$sessionCourses[$course['code']] = $course ;
 	}
 } else {
-	$sql="SELECT code, title, visual_code, id_session
+	$sql = "SELECT code, title, visual_code, id_session
 			FROM $tbl_course course
 			LEFT JOIN $tbl_session_rel_course session_rel_course
 				ON course.code = session_rel_course.course_code
@@ -243,9 +232,8 @@ if ($ajax_search) {
 				ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
 		}
 	}
-
-	$result=Database::query($sql);
-	$Courses=Database::store_result($result);
+	$result = Database::query($sql);
+	$Courses = Database::store_result($result);
 	foreach($Courses as $course) {
 		if ($course['id_session'] == $id_session) {
 			$sessionCourses[$course['code']] = $course ;
@@ -293,14 +281,12 @@ if(!empty($errorMsg))
   <td width="45%" align="center">
 
 <?php
-if(!($add_type == 'multiple')){
+if (!($add_type == 'multiple')) {
 	?>
 	<input type="text" id="course_to_add" onkeyup="xajax_search_courses(this.value,'single')" />
 	<div id="ajax_list_courses_single"></div>
 	<?php
-}
-else
-{
+} else {
 	?>
 	<div id="ajax_list_courses_multiple">
 	<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:360px;"> <?php
@@ -352,16 +338,12 @@ foreach($sessionCourses as $enreg)
 }
 unset($sessionCourses);
 ?>
-
   </select></td>
 </tr>
 </table>
-
 </form>
 <script type="text/javascript">
-<!--
-function moveItem(origin , destination){
-
+function moveItem(origin , destination) {
 	for(var i = 0 ; i<origin.options.length ; i++) {
 		if(origin.options[i].selected) {
 			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
@@ -371,14 +353,10 @@ function moveItem(origin , destination){
 	}
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
-
-
 }
 
 function sortOptions(options) {
-
 	newOptions = new Array();
-
 	for (i = 0 ; i<options.length ; i++) {
 		newOptions[i] = options[i];
 	}
@@ -389,7 +367,6 @@ function sortOptions(options) {
 	for(i = 0 ; i < newOptions.length ; i++){
 		options[i] = newOptions[i];
 	}
-
 }
 
 function mysort(a, b){
@@ -409,10 +386,6 @@ function valide(){
 
 	document.forms.formulaire.submit();
 }
--->
-
 </script>
 <?php
-/*		FOOTER 	*/
 Display::display_footer();
-?>

From 97e4b00c49eea68d3039e991f95e0916ff3217e4 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 19 Sep 2013 11:55:49 +0200
Subject: [PATCH 61/65] Minor - format code

---
 main/auth/external_login/ldap.inc.php | 164 +++++++++++++++++---------
 1 file changed, 108 insertions(+), 56 deletions(-)

diff --git a/main/auth/external_login/ldap.inc.php b/main/auth/external_login/ldap.inc.php
index 4af028b872..173b13da3b 100644
--- a/main/auth/external_login/ldap.inc.php
+++ b/main/auth/external_login/ldap.inc.php
@@ -6,17 +6,18 @@
  * It implements the functions nedded by both files
  * */
 //Includes the configuration file
-require_once dirname(__FILE__) . '/../../inc/global.inc.php';
-require_once dirname(__FILE__) . '/../../inc/conf/auth.conf.php';
+require_once dirname(__FILE__).'/../../inc/global.inc.php';
+require_once dirname(__FILE__).'/../../inc/conf/auth.conf.php';
 
 /**
  * Returns a transcoded and trimmed string
  *
- * @param string 
- * @return string 
+ * @param string
+ * @return string
  * @author ndiechburg <noel@cblue.be>
  * */
-function extldap_purify_string($string) {
+function extldap_purify_string($string)
+{
     global $extldap_config;
     if (isset($extldap_config['encoding'])) {
         return trim(api_to_system_encoding($string, $extldap_config['encoding']));
@@ -31,11 +32,13 @@ function extldap_purify_string($string) {
  * @return resource ldap link identifier or false
  * @author ndiechburg <noel@cblue.be>
  * */
-function extldap_connect() {
+function extldap_connect()
+{
     global $extldap_config;
 
-    if (!is_array($extldap_config['host']))
+    if (!is_array($extldap_config['host'])) {
         $extldap_config['host'] = array($extldap_config['host']);
+    }
 
     foreach ($extldap_config['host'] as $host) {
         //Trying to connect
@@ -46,9 +49,10 @@ function extldap_connect() {
         }
         if (!$ds) {
             $port = isset($extldap_config['port']) ? $ldap_config['port'] : 389;
-            error_log('EXTLDAP ERROR : cannot connect to ' . $extldap_config['host'] . ':' . $port);
-        } else
+            error_log('EXTLDAP ERROR : cannot connect to '.$extldap_config['host'].':'.$port);
+        } else {
             break;
+        }
     }
     if (!$ds) {
         error_log('EXTLDAP ERROR : no valid server found');
@@ -76,11 +80,12 @@ function extldap_connect() {
  *
  * @return mixed false if user cannot authenticate on ldap, user ldap entry if tha succeeds
  * @author ndiechburg <noel@cblue.be>
- * Modified by hubert.borderiou@grenet.fr 
+ * Modified by hubert.borderiou@grenet.fr
  * Add possibility to get user info from LDAP without check password (if CAS auth and LDAP profil update)
- * 
+ *
  * */
-function extldap_authenticate($username, $password, $in_auth_with_no_password = false) {
+function extldap_authenticate($username, $password, $in_auth_with_no_password = false)
+{
     global $extldap_config;
 
     if (empty($username) or empty($password)) {
@@ -102,21 +107,25 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password =
     //Search distinguish name of user
     $sr = ldap_search($ds, $extldap_config['base_dn'], $user_search);
     if (!$sr) {
-        error_log('EXTLDAP ERROR : ldap_search(' . $ds . ', ' . $extldap_config['base_dn'] . ", $user_search) failed");
+        error_log('EXTLDAP ERROR : ldap_search('.$ds.', '.$extldap_config['base_dn'].", $user_search) failed");
         return false;
     }
     $entries_count = ldap_count_entries($ds, $sr);
 
     if ($entries_count > 1) {
-        error_log('EXTLDAP ERROR : more than one entry for that user ( ldap_search(ds, ' . $extldap_config['base_dn'] . ", $user_search) )");
+        error_log(
+            'EXTLDAP ERROR : more than one entry for that user ( ldap_search(ds, '.$extldap_config['base_dn'].", $user_search) )"
+        );
         return false;
     }
     if ($entries_count < 1) {
-        error_log('EXTLDAP ERROR :  No entry for that user ( ldap_search(ds, ' . $extldap_config['base_dn'] . ", $user_search) )");
+        error_log(
+            'EXTLDAP ERROR :  No entry for that user ( ldap_search(ds, '.$extldap_config['base_dn'].", $user_search) )"
+        );
         return false;
     }
     $users = ldap_get_entries($ds, $sr);
-    $user = $users[0];
+    $user  = $users[0];
 
     // If we just want to have user info from LDAP and not to check password
     if ($in_auth_with_no_password) {
@@ -127,7 +136,7 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password =
     if ($ubind !== false) {
         return $user;
     } else {
-        error_log('EXTLDAP : Wrong password for ' . $user['dn']);
+        error_log('EXTLDAP : Wrong password for '.$user['dn']);
         return false;
     }
 }
@@ -141,7 +150,8 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password =
  * @return array userinfo array
  * @author ndiechburg <noel@cblue.be>
  * */
-function extldap_get_chamilo_user($ldap_user, $cor = null) {
+function extldap_get_chamilo_user($ldap_user, $cor = null)
+{
     global $extldap_user_correspondance;
     if (is_null($cor)) {
         $cor = $extldap_user_correspondance;
@@ -172,7 +182,7 @@ function extldap_get_chamilo_user($ldap_user, $cor = null) {
                 if (isset($ldap_user[$ldap_field][0])) {
                     $chamilo_user[$chamilo_field] = extldap_purify_string($ldap_user[$ldap_field][0]);
                 } else {
-                    error_log('EXTLDAP WARNING : ' . $ldap_field . '[0] field is not set in ldap array');
+                    error_log('EXTLDAP WARNING : '.$ldap_field.'[0] field is not set in ldap array');
                 }
                 break;
         }
@@ -182,7 +192,7 @@ function extldap_get_chamilo_user($ldap_user, $cor = null) {
 
 /**
  * Please declare here all the function you use in extldap_user_correspondance
- * All these functions must have an $ldap_user parameter. This parameter is the 
+ * All these functions must have an $ldap_user parameter. This parameter is the
  * array returned by the ldap for the user
  * */
 
@@ -194,11 +204,13 @@ function extldap_get_chamilo_user($ldap_user, $cor = null) {
   return $ldap_user['cn'].$ldap['sn'].'@gmail.com';
   }
  */
-function extldap_get_status($ldap_user) {
+function extldap_get_status($ldap_user)
+{
     return STUDENT;
 }
 
-function extldap_get_admin($ldap_user) {
+function extldap_get_admin($ldap_user)
+{
     return false;
 }
 
@@ -209,23 +221,27 @@ function extldap_get_admin($ldap_user) {
  * @return string the serach string
  * @author ndiechburg <noel@cblue.be>
  * */
-function extldap_get_user_search_string($username) {
+function extldap_get_user_search_string($username)
+{
     global $extldap_config;
     // init
-    $filter = '(' . $extldap_config['user_search'] . ')';
+    $filter = '('.$extldap_config['user_search'].')';
     // replacing %username% by the actual username
     $filter = str_replace('%username%', $username, $filter);
     // append a global filter if needed
-    if (isset($extldap_config['filter']) && $extldap_config['filter'] != "")
-        $filter = '(&' . $filter . '(' . $extldap_config['filter'] . '))';
+    if (isset($extldap_config['filter']) && $extldap_config['filter'] != "") {
+        $filter = '(&'.$filter.'('.$extldap_config['filter'].'))';
+    }
 
     return $filter;
 }
+
 /**
  * Imports all LDAP users into Chamilo
  * @return bool false on error, true otherwise
  */
-function extldap_import_all_users() {
+function extldap_import_all_users()
+{
     global $extldap_config;
     //echo "Connecting...\n";
     $ds = extldap_connect();
@@ -241,9 +257,9 @@ function extldap_import_all_users() {
         return false;
     }
     //browse ASCII values from a to z to avoid 1000 results limit of LDAP
-    $count = 0;
-    $alphanum = array('0','1','2','3','4','5','6','7','8','9');
-    for ($a=97;$a<=122;$a++) {
+    $count    = 0;
+    $alphanum = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
+    for ($a = 97; $a <= 122; $a++) {
         $alphanum[] = chr($a);
     }
     foreach ($alphanum as $char1) {
@@ -253,15 +269,15 @@ function extldap_import_all_users() {
             //Search distinguish name of user
             $sr = ldap_search($ds, $extldap_config['base_dn'], $user_search);
             if (!$sr) {
-                error_log('EXTLDAP ERROR : ldap_search(' . $ds . ', ' . $extldap_config['base_dn'] . ", $user_search) failed");
+                error_log('EXTLDAP ERROR : ldap_search('.$ds.', '.$extldap_config['base_dn'].", $user_search) failed");
                 return false;
             }
             //echo "Getting entries\n";
             $users = ldap_get_entries($ds, $sr);
             //echo "Entries: ".$users['count']."\n";
-            for ($key = 0; $key < $users['count']; $key ++) {
+            for ($key = 0; $key < $users['count']; $key++) {
                 $user_id = extldap_add_user_by_array($users[$key], true);
-                $count ++;
+                $count++;
                 if ($user_id) {
                     // echo "User #$user_id created or updated\n";
                 } else {
@@ -273,48 +289,84 @@ function extldap_import_all_users() {
     //echo "Found $count users in total\n";
     @ldap_close($ds);
 }
+
 /**
  * Insert users from an array of user fields
  */
-function extldap_add_user_by_array($data, $update_if_exists = true) {
-    $lastname = api_convert_encoding($data['sn'][0], api_get_system_encoding(), 'UTF-8');
+function extldap_add_user_by_array($data, $update_if_exists = true)
+{
+    $lastname  = api_convert_encoding($data['sn'][0], api_get_system_encoding(), 'UTF-8');
     $firstname = api_convert_encoding($data['cn'][0], api_get_system_encoding(), 'UTF-8');
-    $email = $data['mail'][0];
+    $email     = $data['mail'][0];
     // Get uid from dn
-    $dn_array=ldap_explode_dn($data['dn'],1);
+    $dn_array = ldap_explode_dn($data['dn'], 1);
     $username = $dn_array[0]; // uid is first key
-    $outab[] = $data['edupersonprimaryaffiliation'][0]; // Here, "student"
+    $outab[]  = $data['edupersonprimaryaffiliation'][0]; // Here, "student"
     //$val = ldap_get_values_len($ds, $entry, "userPassword");
     //$val = ldap_get_values_len($ds, $data, "userPassword");
     //$password = $val[0];
     // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
-    $password = $data['userPassword'][0];
-    $structure=$data['edupersonprimaryorgunitdn'][0];
-    $array_structure=explode(",", $structure);
-    $array_val=explode("=", $array_structure[0]);
-    $etape=$array_val[1];
-    $array_val=explode("=", $array_structure[1]);
-    $annee=$array_val[1];
+    $password        = $data['userPassword'][0];
+    $structure       = $data['edupersonprimaryorgunitdn'][0];
+    $array_structure = explode(",", $structure);
+    $array_val       = explode("=", $array_structure[0]);
+    $etape           = $array_val[1];
+    $array_val       = explode("=", $array_structure[1]);
+    $annee           = $array_val[1];
     // To ease management, we add the step-year (etape-annee) code
-    $official_code=$etape."-".$annee;
-    $auth_source='ldap';
+    $official_code = $etape."-".$annee;
+    $auth_source   = 'ldap';
     // No expiration date for students (recover from LDAP's shadow expiry)
-    $expiration_date='0000-00-00 00:00:00';
-    $active=1;
-    if(empty($status)){$status = 5;}
-    if(empty($phone)){$phone = '';}
-    if(empty($picture_uri)){$picture_uri = '';}
+    $expiration_date = '0000-00-00 00:00:00';
+    $active          = 1;
+    if (empty($status)) {
+        $status = 5;
+    }
+    if (empty($phone)) {
+        $phone = '';
+    }
+    if (empty($picture_uri)) {
+        $picture_uri = '';
+    }
     // Adding user
     $user_id = 0;
     if (UserManager::is_username_available($username)) {
         //echo "$username\n";
-        $user_id = UserManager::create_user($firstname,$lastname,$status,$email,$username,$password,$official_code,api_get_setting('platformLanguage'),$phone,$picture_uri,$auth_source,$expiration_date,$active);
+        $user_id = UserManager::create_user(
+            $firstname,
+            $lastname,
+            $status,
+            $email,
+            $username,
+            $password,
+            $official_code,
+            api_get_setting('platformLanguage'),
+            $phone,
+            $picture_uri,
+            $auth_source,
+            $expiration_date,
+            $active
+        );
     } else {
         if ($update_if_exists) {
-            $user = UserManager::get_user_info($username);
-            $user_id=$user['user_id'];
+            $user    = UserManager::get_user_info($username);
+            $user_id = $user['user_id'];
             //echo "$username\n";
-            UserManager::update_user($user_id, $firstname, $lastname, $username, null, null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active);
+            UserManager::update_user(
+                $user_id,
+                $firstname,
+                $lastname,
+                $username,
+                null,
+                null,
+                $email,
+                $status,
+                $official_code,
+                $phone,
+                $picture_uri,
+                $expiration_date,
+                $active
+            );
         }
     }
     return $user_id;

From b1144dad137a73bfa52bd416ecb78203bd204992 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 19 Sep 2013 12:15:11 +0200
Subject: [PATCH 62/65] Fixing array key association see BT#6410

---
 main/auth/external_login/ldap.inc.php | 24 +++++++++++++-----------
 1 file changed, 13 insertions(+), 11 deletions(-)

diff --git a/main/auth/external_login/ldap.inc.php b/main/auth/external_login/ldap.inc.php
index 173b13da3b..118907f28f 100644
--- a/main/auth/external_login/ldap.inc.php
+++ b/main/auth/external_login/ldap.inc.php
@@ -295,27 +295,29 @@ function extldap_import_all_users()
  */
 function extldap_add_user_by_array($data, $update_if_exists = true)
 {
-    $lastname  = api_convert_encoding($data['sn'][0], api_get_system_encoding(), 'UTF-8');
-    $firstname = api_convert_encoding($data['cn'][0], api_get_system_encoding(), 'UTF-8');
-    $email     = $data['mail'][0];
-    // Get uid from dn
-    $dn_array = ldap_explode_dn($data['dn'], 1);
-    $username = $dn_array[0]; // uid is first key
-    $outab[]  = $data['edupersonprimaryaffiliation'][0]; // Here, "student"
-    //$val = ldap_get_values_len($ds, $entry, "userPassword");
-    //$val = ldap_get_values_len($ds, $data, "userPassword");
-    //$password = $val[0];
+    global $extldap_user_correspondance;
+
+    $lastname  = api_convert_encoding($data[$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8');
+    $firstname = api_convert_encoding($data[$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8');
+    $email     = $data[$extldap_user_correspondance['email']][0];
+    $username  = $data[$extldap_user_correspondance['username']][0];
+
     // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
-    $password        = $data['userPassword'][0];
+    $passwordKey = isset($extldap_user_correspondance['password']) ? $extldap_user_correspondance['password'] : 'userPassword';
+    $password        = $data[$passwordKey][0];
+
+    // Structure
     $structure       = $data['edupersonprimaryorgunitdn'][0];
     $array_structure = explode(",", $structure);
     $array_val       = explode("=", $array_structure[0]);
     $etape           = $array_val[1];
     $array_val       = explode("=", $array_structure[1]);
     $annee           = $array_val[1];
+
     // To ease management, we add the step-year (etape-annee) code
     $official_code = $etape."-".$annee;
     $auth_source   = 'ldap';
+
     // No expiration date for students (recover from LDAP's shadow expiry)
     $expiration_date = '0000-00-00 00:00:00';
     $active          = 1;

From 4c7a86154f041f61bec5338f992a009f214b8143 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 19 Sep 2013 14:23:44 +0200
Subject: [PATCH 63/65] Adding setVisible/setInvisible actions in the document
 list see BT#6682

---
 main/document/document.php | 99 ++++++++++++++++++++++++++++----------
 1 file changed, 74 insertions(+), 25 deletions(-)

diff --git a/main/document/document.php b/main/document/document.php
index aabffc29ad..828a7f29d4 100644
--- a/main/document/document.php
+++ b/main/document/document.php
@@ -374,10 +374,11 @@ if ($tool_visibility == '0' && $to_group_id == '0' && !($is_allowed_to_edit || $
 
 $htmlHeadXtra[] = "<script>
 function confirmation (name) {
-    if (confirm(\" ".get_lang("AreYouSureToDelete")." \"+ name + \" ?\"))
-        {return true;}
-    else
-        {return false;}
+    if (confirm(\" ".get_lang("AreYouSureToDelete")." \"+ name + \" ?\")) {
+        return true;
+    } else {
+        return false;
+    }
 }
 </script>";
 
@@ -681,30 +682,76 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         }
     }
 
-    if (isset($_POST['action'])) {
-        switch ($_POST['action']) {
-            case 'delete':
-                foreach ($_POST['path'] as $index => & $path) {
-                    if (!$is_allowed_to_edit) {
-                        if (DocumentManager::check_readonly($_course, api_get_user_id(), $path)) {
-                            Display::display_error_message(get_lang('CantDeleteReadonlyFiles'));
-                            break 2;
+    if (isset($_POST['action']) && isset($_POST['path'])) {
+        $files = $_POST['path'];
+
+        foreach ($files as $path) {
+            $items = array('/audio', '/flash', '/images', '/shared_folder', '/video', '/chat_files', '/certificates');
+            if (in_array($path, $items)) {
+                continue;
+            } else {
+
+                $documentId = DocumentManager::get_document_id($_course, $path);
+                $data = DocumentManager::get_document_data_by_id($documentId, $_course['code']);
+
+                switch ($_POST['action']) {
+                    case 'set_invisible':
+                        $visibilityCommand = 'invisible';
+
+                        if (api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $documentId,
+                            $visibilityCommand,
+                            api_get_user_id(),
+                            null,
+                            null,
+                            null,
+                            null,
+                            $session_id
+                        )) {
+                            Display::display_confirmation_message(get_lang('VisibilityChanged').': '.$data['path']);
+                        } else {
+                            Display::display_error_message(get_lang('ViModProb'));
+                        }
+                        break;
+                    case 'set_visible':
+                        $visibilityCommand = 'visible';
+                        if (api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $documentId,
+                            $visibilityCommand,
+                            api_get_user_id(),
+                            null,
+                            null,
+                            null,
+                            null,
+                            $session_id
+                        )) {
+                            Display::display_confirmation_message(get_lang('VisibilityChanged').': '.$data['path']);
+                        } else {
+                            Display::display_error_message(get_lang('ViModProb'));
+                        }
+                        break;
+                    case 'delete':
+
+                        foreach ($files as $path) {
+                            if (!$is_allowed_to_edit) {
+                                if (DocumentManager::check_readonly($_course, api_get_user_id(), $path)) {
+                                    Display::display_error_message(get_lang('CantDeleteReadonlyFiles'));
+                                    break 2;
+                                }
+                            }
                         }
-                    }
-                }
 
-                foreach ($_POST['path'] as $index => & $path) {
-                    $items = array('/audio', '/flash', '/images', '/shared_folder', '/video', '/chat_files', '/certificates');
-                    if (in_array($path, $items)) {
-                        continue;
-                    } else {
                         $delete_document = DocumentManager::delete_document($_course, $path, $base_work_dir);
-                    }
-                }
-                if (!empty($delete_document)) {
-                    Display::display_confirmation_message(get_lang('DocDeleted'));
+                        if (!empty($delete_document)) {
+                            Display::display_confirmation_message(get_lang('DocDeleted').': '.$data['path']);
+                        }
+                        break;
                 }
-                break;
+            }
         }
     }
 }
@@ -1149,7 +1196,6 @@ if ($image_present && !isset($_GET['keyword'])) {
 if (api_is_allowed_to_edit(null, true)) {
     echo '<a href="document_quota.php?'.api_get_cidreq().'">'.Display::return_icon('percentage.png', get_lang('DocumentQuota'), '', ICON_SIZE_MEDIUM).'</a>';
 }
-
 echo '</div>'; //end actions
 
 
@@ -1234,7 +1280,10 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
 if (count($docs_and_folders) > 1) {
     if ($is_allowed_to_edit || $group_member_with_upload_rights) {
         $form_actions = array();
+        $form_action['set_invisible'] = get_lang('SetInvisible');
+        $form_action['set_visible'] = get_lang('SetVisible');
         $form_action['delete'] = get_lang('Delete');
+
         $portfolio_actions = Portfolio::actions();
         foreach ($portfolio_actions as $action) {
             $form_action[$action->get_name()] = $action->get_title();

From d52502795d97f464c41cac86edf0f6395715c013 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 19 Sep 2013 16:58:39 +0200
Subject: [PATCH 64/65] Adding user_name_order setting does not work in 1.9 +
 fixing the user list order see BT#6535

---
 main/admin/access_url_edit_users_to_url.php | 119 ++++++++------------
 main/inc/lib/internationalization.lib.php   |  35 +++++-
 2 files changed, 80 insertions(+), 74 deletions(-)

diff --git a/main/admin/access_url_edit_users_to_url.php b/main/admin/access_url_edit_users_to_url.php
index 826d08a061..b2b298c200 100644
--- a/main/admin/access_url_edit_users_to_url.php
+++ b/main/admin/access_url_edit_users_to_url.php
@@ -116,7 +116,7 @@ if ($_POST['form_sent']) {
                 foreach ($result['users_added'] as $user) {
                     $user_info = api_get_user_info($user);
                     if (!empty($user_info)) {
-                        $user_added_list[] = $i . '. ' . api_get_person_name($user_info['firstname'], $user_info['lastname']);
+                        $user_added_list[] = $i . '. ' . api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, null, null, $user_info['username']);
                         $i++;
                     }
                 }
@@ -174,7 +174,7 @@ if ($ajax_search) {
             $sessionUsersList[$user['user_id']] = $user;
         }
     }
-    $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+    $order_clause = api_sort_by_first_name() ? ' ORDER BY username, firstname, lastname' : ' ORDER BY username, lastname, firstname';
     $sql = "SELECT u.user_id, lastname, firstname, username
 	  	  	FROM $tbl_user u WHERE status <> " . ANONYMOUS . " " .
             $order_clause;
@@ -188,7 +188,6 @@ if ($ajax_search) {
     }
 }
 
-
 if ($add_type == 'multiple') {
     $link_add_type_unique = '<a href="' . api_get_self() . '?add_type=unique&access_url_id=' . $access_url_id . '">' . get_lang('SessionAddTypeUnique') . '</a>';
     $link_add_type_multiple = get_lang('SessionAddTypeMultiple');
@@ -196,7 +195,6 @@ if ($add_type == 'multiple') {
     $link_add_type_unique = get_lang('SessionAddTypeUnique');
     $link_add_type_multiple = '<a href="' . api_get_self() . '?add_type=multiple&access_url_id=' . $access_url_id . '">' . get_lang('SessionAddTypeMultiple') . '</a>';
 }
-
 $url_list = UrlManager::get_url_data();
 ?>
 
@@ -232,19 +230,19 @@ $url_list = UrlManager::get_url_data();
 <input type="hidden" name="form_sent" value="1" />
 <input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
 
-    <?php
-    if (!empty($errorMsg)) {
-        Display::display_normal_message($errorMsg); //main API
-    }
-    ?>
+<?php
+if (!empty($errorMsg)) {
+    Display::display_normal_message($errorMsg); //main API
+}
+?>
 
 <table border="0" cellpadding="5" cellspacing="0" width="100%">
 <tr>
     <td>
     <h3>
     <?php 
-            $total_users = count($nosessionUsersList) +  count($sessionUsersList); 
-            echo get_lang('TotalAvailableUsers').' '.$total_users;
+        $total_users = count($nosessionUsersList) +  count($sessionUsersList);
+        echo get_lang('TotalAvailableUsers').' '.$total_users;
     ?>
     </h3>
     </td>
@@ -259,77 +257,61 @@ $url_list = UrlManager::get_url_data();
 <tr>
   <td align="center">
   <div id="content_source">
-                    <?php
-                    if ($ajax_search) {
-                        ?>
-    		<input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
-    		<div id="ajax_list_users"></div>
-                        <?php
-                    } else {
-                        ?>
-    	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
-                            <?php
-                            foreach ($nosessionUsersList as $enreg) {
-                                ?>
-        			<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']) . ' (' . $enreg['username'] . ')'; ?></option>
-                                <?php
-                            }
-                            unset($nosessionUsersList);
-                            ?>
-
-    	  </select>
-                        <?php
-                    }
-                    ?>
+    <?php if ($ajax_search) { ?>
+    <input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
+    <div id="ajax_list_users"></div>
+    <?php } else { ?>
+    <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
+    <?php
+        foreach ($nosessionUsersList as $enreg) {
+    ?>
+    <option value="<?php echo $enreg['user_id']; ?>"><?php echo $enreg['username'].' - '.api_get_person_name($enreg['firstname'], $enreg['lastname']); ?></option>
+    <?php
+     }
+    unset($nosessionUsersList);
+    ?>
+    </select>
+        <?php
+    }
+    ?>
   </div>
   </td>
   <td width="10%" valign="middle" align="center">
-                <?php
-                if ($ajax_search) {
-                    ?>
-    	<button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination_users'))"> </button>
-                    <?php
-                } else {
-                    ?>
-    	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" ></button>
-    	<br /><br />
-    	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" ></button>
-                    <?php
-                }
-                ?>
+    <?php if ($ajax_search) { ?>
+        <button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination_users'))"> </button>
+    <?php } else { ?>
+        <button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" ></button>
+        <br /><br />
+        <button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" ></button>
+    <?php } ?>
 	<br /><br /><br /><br /><br /><br />
   </td>
   <td align="center">
   <select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
-
-                    <?php
-                    foreach ($sessionUsersList as $enreg) {
-                        ?>
-    	<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']) . ' (' . $enreg['username'] . ')'; ?></option>
-
-                        <?php
-                    }
-                    unset($sessionUsersList);
-                    ?>
-
+    <?php
+    foreach ($sessionUsersList as $enreg) {
+        ?>
+        <option value="<?php echo $enreg['user_id']; ?>">
+            <?php echo $enreg['username'].' - '.api_get_person_name($enreg['firstname'], $enreg['lastname']); ?>
+        </option>
+    <?php
+    }
+    unset($sessionUsersList);
+    ?>
   </select></td>
 </tr>
-
 <tr>
 	<td colspan="3" align="center">
 		<br />
-                <?php
-                if (isset($_GET['add']))
-                    echo '<button class="save" type="button" onclick="valide()" >' . get_lang('AddUsersToURL') . '</button>';
-                else
-                    echo '<button class="save" type="button" onclick="valide()" >' . get_lang('EditUsersToURL') . '</button>';
-                ?>
+        <?php
+        if (isset($_GET['add'])) {
+            echo '<button class="save" type="button" onclick="valide()" >' . get_lang('AddUsersToURL') . '</button>';
+        } else {
+            echo '<button class="save" type="button" onclick="valide()" >' . get_lang('EditUsersToURL') . '</button>';
+        }
+        ?>
 	</td>
 </tr>
-
-
-
-
 </table>
 
 </form>
@@ -422,7 +404,6 @@ function makepost(select){
 
 }
 -->
-
 </script>
 <?php
 Display::display_footer();
\ No newline at end of file
diff --git a/main/inc/lib/internationalization.lib.php b/main/inc/lib/internationalization.lib.php
index 9e87f6d11e..0e1a05113b 100644
--- a/main/inc/lib/internationalization.lib.php
+++ b/main/inc/lib/internationalization.lib.php
@@ -1032,7 +1032,7 @@ function api_get_months_long($language = null) {
  * @author Carlos Vargas <carlos.vargas@dokeos.com> - initial implementation.
  * @author Ivan Tcholakov
  */
-function api_get_person_name($first_name, $last_name, $title = null, $format = null, $language = null, $encoding = null) {
+function api_get_person_name($first_name, $last_name, $title = null, $format = null, $language = null, $encoding = null, $username = null) {
     static $valid = array();
     if (empty($format)) {
         $format = PERSON_NAME_COMMON_CONVENTION;
@@ -1051,6 +1051,10 @@ function api_get_person_name($first_name, $last_name, $title = null, $format = n
             switch ($format) {
                 case PERSON_NAME_COMMON_CONVENTION:
                     $valid[$format][$language] = _api_get_person_name_convention($language, 'format');
+                    $usernameOrderFromDatabase = api_get_setting('user_name_order');
+                    if (isset($usernameOrderFromDatabase) && !empty($usernameOrderFromDatabase)) {
+                        $valid[$format][$language] = $usernameOrderFromDatabase;
+                    }
                     break;
                 case PERSON_NAME_WESTERN_ORDER:
                     $valid[$format][$language] = '%t %f %l';
@@ -1069,11 +1073,26 @@ function api_get_person_name($first_name, $last_name, $title = null, $format = n
             $valid[$format][$language] = _api_validate_person_name_format($format);
         }
     }
+
     $format = $valid[$format][$language];
-    $person_name = str_replace(array('%f', '%l', '%t'), array($first_name, $last_name, $title), $format);
-    if (strpos($format, '%F') !== false || strpos($format, '%L') !== false || strpos($format, '%T') !== false) {
-        $person_name = str_replace(array('%F', '%L', '%T'), array(api_strtoupper($first_name, $encoding), api_strtoupper($last_name, $encoding), api_strtoupper($title, $encoding)), $person_name);
-    }
+
+    $keywords = array('%firstname', '%f', '%F', '%lastname', '%l', '%L', '%title', '%t', '%T', '%username', '%u', '%U');
+
+    $values = array(
+        $first_name,
+        $first_name,
+        api_strtoupper($first_name, $encoding),
+        $last_name,
+        $last_name,
+        api_strtoupper($last_name, $encoding),
+        $title,
+        $title,
+        api_strtoupper($title, $encoding),
+        $username,
+        $username,
+        api_strtoupper($username, $encoding),
+    );
+    $person_name = str_replace($keywords, $values, $format);
     return _api_clean_person_name($person_name);
 }
 
@@ -1112,6 +1131,11 @@ function api_is_western_name_order($format = null, $language = null) {
  * @author Ivan Tcholakov
  */
 function api_sort_by_first_name($language = null) {
+    $userNameSortBy = api_get_setting('user_name_sort_by');
+    if (!empty($userNameSortBy) && in_array($userNameSortBy, array('firstname', 'lastname'))) {
+        return $userNameSortBy == 'firstname' ? true : false;
+    }
+
     static $sort_by_first_name = array();
 
     $language_is_supported = api_is_language_supported($language);
@@ -1121,6 +1145,7 @@ function api_sort_by_first_name($language = null) {
     if (!isset($sort_by_first_name[$language])) {
         $sort_by_first_name[$language] = _api_get_person_name_convention($language, 'sort_by');
     }
+
     return $sort_by_first_name[$language];
 }
 

From 311823bb93342c19b12b4bebae3cefa8c47d4fd8 Mon Sep 17 00:00:00 2001
From: Julio Montoya <gugli100@gmail.com>
Date: Thu, 19 Sep 2013 17:05:58 +0200
Subject: [PATCH 65/65] Fixing order.

---
 main/admin/access_url_edit_users_to_url.php | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/main/admin/access_url_edit_users_to_url.php b/main/admin/access_url_edit_users_to_url.php
index b2b298c200..8fe5c9e9ef 100644
--- a/main/admin/access_url_edit_users_to_url.php
+++ b/main/admin/access_url_edit_users_to_url.php
@@ -168,13 +168,15 @@ if ($ajax_search) {
         $sessionUsersList[$user['user_id']] = $user;
     }
 } else {
-    $Users = UrlManager::get_url_rel_user_data();
+    $order_clause = api_sort_by_first_name() ? ' ORDER BY username, firstname, lastname' : ' ORDER BY username, lastname, firstname';
+
+    $Users = UrlManager::get_url_rel_user_data(null, $order_clause);
     foreach ($Users as $user) {
         if ($user['access_url_id'] == $access_url_id) {
             $sessionUsersList[$user['user_id']] = $user;
         }
     }
-    $order_clause = api_sort_by_first_name() ? ' ORDER BY username, firstname, lastname' : ' ORDER BY username, lastname, firstname';
+
     $sql = "SELECT u.user_id, lastname, firstname, username
 	  	  	FROM $tbl_user u WHERE status <> " . ANONYMOUS . " " .
             $order_clause;