Browse Source

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

Yannick Warnier 11 years ago
parent
commit
d63c236205

+ 36 - 45
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;"');
@@ -130,25 +121,25 @@ $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'));
+$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 +154,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 +184,19 @@ $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'];
 
+$course['add_teachers_to_sessions'] = empty($course_teachers) ||  count($course_teachers) == 1 ? null : '1';
+
 $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;
@@ -228,13 +219,14 @@ 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;
+            }
 		}
     }
 
 	$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'];
@@ -273,7 +265,7 @@ 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). "',
@@ -346,8 +338,7 @@ function valide() {
 	document.update_course.submit();
 }
 </script>";
-//api_display_tool_title($tool_name);
 // Display the form
 $form->display();
-/* FOOTER */
+
 Display :: display_footer();

+ 4 - 6
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();
+Display::display_footer();

+ 27 - 16
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);
@@ -74,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
@@ -98,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);
@@ -169,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);
                 ?>
@@ -238,4 +248,5 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     <?php } ?>
     </table>
 
-<?php } Display::display_footer(); ?>
+<?php }
+Display::display_footer();

+ 57 - 26
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
@@ -28,31 +26,26 @@ $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();
-}
-
-$id_coach   = $infos['id_coach'];
-
-
+$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 = '';
 
-if ($_POST['formSent']) {
+if (isset($_POST['formSent']) && $_POST['formSent']) {
 	$formSent = 1;
 
 	$name                  = $_POST['name'];
@@ -69,6 +62,9 @@ if ($_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'];
 
@@ -78,7 +74,27 @@ if ($_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();
@@ -104,11 +120,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 +196,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>
@@ -344,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>
@@ -379,8 +412,6 @@ function setDisable(select){
 
     var start_div = document.getElementById('start_date');
     start_div.style.display = 'none';
-
-
 }
 
 function disable_endtime(select) {

+ 50 - 32
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'=>'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'),
-    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">

+ 28 - 30
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();
+Display::display_footer();

+ 10 - 1
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');

+ 17 - 8
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'];
+                    }
+                }
             }
         }
 
@@ -349,7 +355,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 +446,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 +466,9 @@ class ImportCsv
                     );
 
                     if ($result) {
+                        if ($row['username'] != $userInfo['username']) {
+                            $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);
@@ -503,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);
 
@@ -655,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));

+ 97 - 18
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;
+    }
+
+}

+ 1 - 1
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'];

+ 32 - 1
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>';
                         }
@@ -3964,8 +3967,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 +3992,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 +4018,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);
+                        }
+                    }
+                }
+            }
+        }
     }
 }

+ 31 - 10
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);
         }
@@ -1226,7 +1238,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) {
@@ -1239,20 +1252,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 +1293,19 @@ 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 (array_key_exists('show_description', $session_info)) {
+                if (!empty($session_info['show_description'])) {
+                    $session['description'] = $session_info['description'];
+                }
+            }
+
             $output = $session;
         }
         return $output;

+ 201 - 50
main/inc/lib/sessionmanager.lib.php

@@ -181,41 +181,106 @@ class SessionManager
         return $result['count'] > 0;
 	}
 
-    static function get_count_admin() {
+    /**
+     * @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();
+        $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(') 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 s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
+                $where_condition
+            );
+        } else {
+            $where_condition = "1 = 1";
         }
 
-        $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 ";
+        $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
+                    (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.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
+                    $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 count(*) as total_rows
+                $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
+                    (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.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 ";
+                    $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;
     }
 
@@ -224,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 = 'WHERE 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 ";
@@ -242,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);
@@ -254,7 +344,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,
@@ -273,43 +362,42 @@ 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_session_category sc ON s.session_category_id = sc.id
 				LEFT JOIN $tbl_user u ON s.id_coach = u.user_id
-                $where $limit";
+				$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) {
-				$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
-				 $where $limit";
+                               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";
 			}
 		}
 
 		$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') {
@@ -397,9 +485,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);
@@ -412,9 +519,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);
@@ -454,17 +559,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."',
@@ -472,6 +592,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);
@@ -1278,7 +1400,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);
@@ -1408,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);
@@ -1906,6 +2028,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 +2075,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 +2117,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,6 +2148,10 @@ class SessionManager
                             'session_category_id' => $session_category_id
                         );
 
+                        if (!empty($sessionDescription)) {
+                            $params['description'] = $sessionDescription;
+                        }
+
                         if (!empty($fieldsToAvoidUpdate)) {
                             foreach ($fieldsToAvoidUpdate as $field) {
                                 unset($params[$field]);
@@ -2102,6 +2233,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
@@ -2124,6 +2256,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) {
@@ -2160,4 +2293,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;
+    }
 }

+ 29 - 15
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);
+        }
     }
 }
 

+ 43 - 55
main/inc/lib/usermanager.lib.php

@@ -3073,19 +3073,20 @@ 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);
+        $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);
@@ -3096,69 +3097,56 @@ 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;
-            }
-        }
-
-        $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(DISTINCT u.user_id) count";
+        } else {
+            $select = "SELECT DISTINCT u.user_id, u.username, firstname, lastname, email, tag, picture_uri";
+        }
+
+        $sql = " $select
+                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."%'
+                     )
+                     AND
+                     url_rel_user.access_url_id=".api_get_current_access_url_id();
 
-        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."%' )";
-        }
         $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 ";
+        $sql .= " ORDER BY username";
+        $sql .= " LIMIT $from , $number_of_items";
 
-        // 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 .= " LIMIT $from,$number_of_items";
+        $result = Database::query($sql);
+        $return = array();
 
-        $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;
+        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'])) {
+                    $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;
             }
         }
         return $return;

+ 5 - 2
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);
                     }
 

+ 1 - 139
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);
 

+ 9 - 5
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) {

+ 24 - 19
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']:''));
+    (!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']:'')
+);

+ 159 - 0
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;

+ 25 - 16
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';
 

+ 21 - 20
main/social/search.php

@@ -125,10 +125,7 @@ $(document).ready(function (){
         width    : 550,
         height    : 300
        });
-
 });
-
-
 </script>';
 
 if (api_get_setting('allow_social_tool') != 'true') {
@@ -139,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 = 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 = 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)) {
@@ -192,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;
 
@@ -231,7 +231,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>';
@@ -262,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);
@@ -270,13 +270,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' => $itemPerPage),
         $query_vars,
         false,
-        $visibility
+        $visibility,
+        true,
+        array(),
+        $total
     );
 }
 $social_right_content .= MessageManager::generate_message_form('send_message');
@@ -284,9 +287,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);

+ 1 - 0
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 }},

+ 19 - 1
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'));

+ 2 - 2
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>');

+ 5 - 52
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);