Browse Source

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

Yannick Warnier 11 years ago
parent
commit
ce2302b3f4
46 changed files with 1737 additions and 2632 deletions
  1. 42 14
      main/admin/system_announcements.php
  2. 2 2
      main/admin/usergroups.php
  3. 1 1
      main/attendance/attendance_list.php
  4. 0 0
      main/css/default_scorm.css
  5. 2 2
      main/exercice/aiken.php
  6. 34 30
      main/exercice/answer.class.php
  7. 13 3
      main/exercice/exercice.php
  8. 74 57
      main/exercice/exercise.class.php
  9. 19 15
      main/exercice/exercise_report.php
  10. 13 4
      main/exercice/exercise_result.php
  11. 3 2
      main/inc/ajax/model.ajax.php
  12. 43 11
      main/inc/lib/display.lib.php
  13. 7 2
      main/inc/lib/document.lib.php
  14. 42 56
      main/inc/lib/fileManage.lib.php
  15. 20 21
      main/inc/lib/formvalidator/Element/datepicker.php
  16. 8 12
      main/inc/lib/formvalidator/Element/datepickerdate.php
  17. 35 30
      main/inc/lib/lp_item.lib.php
  18. 23 3
      main/inc/lib/main_api.lib.php
  19. 7 1
      main/inc/lib/message.lib.php
  20. 2 2
      main/inc/lib/pdf.lib.php
  21. 1 1
      main/inc/lib/pear/HTML/Common.php
  22. 11 3
      main/inc/lib/pear/HTML/QuickForm.php
  23. 88 96
      main/inc/lib/pear/HTML/QuickForm/date.php
  24. 4 4
      main/inc/lib/pear/HTML/QuickForm/element.php
  25. 10 8
      main/inc/lib/pear/Text/Diff.php
  26. 70 67
      main/inc/lib/sessionmanager.lib.php
  27. 30 18
      main/inc/lib/system_announcements.lib.php
  28. 3 3
      main/inc/lib/template.lib.php
  29. 74 0
      main/inc/lib/tracking.lib.php
  30. 33 5
      main/inc/lib/usergroup.lib.php
  31. 68 15
      main/inc/lib/usermanager.lib.php
  32. 1 1
      main/inc/lib/userportal.lib.php
  33. 4 0
      main/lang/english/trad4all.inc.php
  34. 5 0
      main/lang/spanish/exercice.inc.php
  35. 2 0
      main/lang/spanish/help.inc.php
  36. 8 0
      main/lang/spanish/trad4all.inc.php
  37. 166 203
      main/mySpace/index.php
  38. 9 7
      main/mySpace/student.php
  39. 10 10
      main/mySpace/teachers.php
  40. 295 0
      main/mySpace/users.php
  41. 36 23
      main/newscorm/learnpath.class.php
  42. 3 4
      main/newscorm/lp_edit_item_prereq.php
  43. 43 25
      main/survey/fillsurvey.php
  44. 17 1
      main/survey/preview.php
  45. 43 1528
      main/wiki/index.php
  46. 313 342
      main/wiki/wiki.inc.php

+ 42 - 14
main/admin/system_announcements.php

@@ -40,10 +40,10 @@ if (isset($_GET['action'])) {
     $interbreadcrumb[] = array ("url" => "system_announcements.php", "name" => get_lang('SystemAnnouncements'));
     if ($_GET['action'] == 'add') {
         $interbreadcrumb[] = array ("url" => '#', "name" => get_lang('AddAnnouncement'));
-    } 
+    }
     if ($_GET['action'] == 'edit') {
         $interbreadcrumb[] = array ("url" => '#', "name" => get_lang('Edit'));
-    } 
+    }
 } else {
     $tool_name = get_lang('SystemAnnouncements');
 }
@@ -82,7 +82,7 @@ switch($action) {
         SystemAnnouncementManager :: delete_announcement($_GET['id']);
         Display :: display_confirmation_message(get_lang('AnnouncementDeleted'));
         break;
-    
+
     case 'delete_selected':
         foreach($_POST['id'] as $index => $id) {
             SystemAnnouncementManager :: delete_announcement($id);
@@ -141,13 +141,13 @@ if ($action_todo) {
     }
     $form->add_timewindow('start','end',get_lang('StartTimeWindow'),get_lang('EndTimeWindow'));
     $group = array();
-    
+
     $group[]= $form->createElement('checkbox', 'visible_teacher', null, get_lang('Teacher'));
     $group[]= $form->createElement('checkbox', 'visible_student', null, get_lang('Student'));
     $group[]= $form->createElement('checkbox', 'visible_guest', null, get_lang('Guest'));
-    
+
     $form->addGroup($group, null, get_lang('Visible'), '');
-    
+
     $form->addElement('hidden', 'id');
 
     $group_list = GroupPortalManager::get_groups_list();
@@ -155,7 +155,7 @@ if ($action_todo) {
 	$form->addElement('select', 'group',get_lang('AnnouncementForGroup'),$group_list);
     $values['group'] = isset($values['group']) ? $values['group'] : '0';
 
-    $form->addElement('checkbox', 'send_mail', null, get_lang('SendMail'));    
+    $form->addElement('checkbox', 'send_mail', null, get_lang('SendMail'));
 
     if (isset($_REQUEST['action']) && $_REQUEST['action']=='add') {
         $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar'));
@@ -169,6 +169,8 @@ if ($action_todo) {
         $form->addElement('hidden', 'action','edit');
     }
 
+    $form->addElement('checkbox', 'send_email_test', null, get_lang('SendOnlyAnEmailToMySelfToTest'));
+
     $form->addElement('style_submit_button', 'submit', $text,'class="'.$class.'"');
     if (api_get_setting('wcag_anysurfer_public_pages') == 'true') {
         $values['content'] = WCAG_Rendering::HTML_to_text($values['content']);
@@ -189,12 +191,25 @@ if ($action_todo) {
             $values['lang'] = null;
         }
         if (api_get_setting('wcag_anysurfer_public_pages') == 'true') {
-            $values['content'] = WCAG_Rendering::text_to_HTML($values['content']);
+            //$values['content'] = WCAG_Rendering::text_to_HTML($values['content']);
         }
         switch ($values['action']) {
             case 'add':
-                $announcement_id = SystemAnnouncementManager::add_announcement($values['title'],$values['content'],$values['start'],$values['end'],$values['visible_teacher'],$values['visible_student'],$values['visible_guest'], $values['lang'],$values['send_mail'],  $values['add_to_calendar']);
-                if ($announcement_id !== false )  {
+                $announcement_id = SystemAnnouncementManager::add_announcement(
+                    $values['title'],
+                    $values['content'],
+                    $values['start'],
+                    $values['end'],
+                    $values['visible_teacher'],
+                    $values['visible_student'],
+                    $values['visible_guest'],
+                    $values['lang'],
+                    $values['send_mail'],
+                    $values['add_to_calendar'],
+                    $values['send_email_test']
+                );
+
+                if ($announcement_id !== false)  {
                     SystemAnnouncementManager::announcement_for_groups($announcement_id, array($values['group']));
                     Display :: display_confirmation_message(get_lang('AnnouncementAdded'));
                 } else {
@@ -203,7 +218,20 @@ if ($action_todo) {
                 }
                 break;
             case 'edit':
-                if (SystemAnnouncementManager::update_announcement($values['id'], $values['title'], $values['content'], $values['start'], $values['end'], $values['visible_teacher'], $values['visible_student'], $values['visible_guest'], $values['lang'], $values['send_mail'])) {
+                if (SystemAnnouncementManager::update_announcement(
+                    $values['id'],
+                    $values['title'],
+                    $values['content'],
+                    $values['start'],
+                    $values['end'],
+                    $values['visible_teacher'],
+                    $values['visible_student'],
+                    $values['visible_guest'],
+                    $values['lang'],
+                    $values['send_mail'],
+                    $values['send_email_test']
+                )
+                ) {
                     SystemAnnouncementManager::announcement_for_groups($values['id'], array($values['group']));
                     Display :: display_confirmation_message(get_lang('AnnouncementUpdated'));
                 } else {
@@ -234,13 +262,13 @@ if ($show_announcement_list) {
         $row = array();
         $row[] = $announcement->id;
         $row[] = Display::return_icon(($announcement->visible ? 'accept.png' : 'exclamation.png'), ($announcement->visible ? get_lang('AnnouncementAvailable') : get_lang('AnnouncementNotAvailable')));
-        $row[] = $announcement->title;        
+        $row[] = $announcement->title;
         $row[] = api_convert_and_format_date($announcement->date_start);
         $row[] = api_convert_and_format_date($announcement->date_end);
         $row[] = "<a href=\"?id=".$announcement->id."&amp;person=".SystemAnnouncementManager::VISIBLE_TEACHER."&amp;action=". ($announcement->visible_teacher ? 'make_invisible' : 'make_visible')."\">".Display::return_icon(($announcement->visible_teacher  ? 'visible.gif' : 'invisible.gif'), get_lang('ShowOrHide'))."</a>";
         $row[] = "<a href=\"?id=".$announcement->id."&amp;person=".SystemAnnouncementManager::VISIBLE_STUDENT."&amp;action=". ($announcement->visible_student  ? 'make_invisible' : 'make_visible')."\">".Display::return_icon(($announcement->visible_student  ? 'visible.gif' : 'invisible.gif'), get_lang('ShowOrHide'))."</a>";
         $row[] = "<a href=\"?id=".$announcement->id."&amp;person=".SystemAnnouncementManager::VISIBLE_GUEST."&amp;action=". ($announcement->visible_guest ? 'make_invisible' : 'make_visible')."\">".Display::return_icon(($announcement->visible_guest  ? 'visible.gif' : 'invisible.gif'), get_lang('ShowOrHide'))."</a>";
-        
+
         $row[] = $announcement->lang;
         $row[] = "<a href=\"?action=edit&id=".$announcement->id."\">".Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL)."</a> <a href=\"?action=delete&id=".$announcement->id."\"  onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES))."')) return false;\">".Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL)."</a>";
         $announcement_data[] = $row;
@@ -254,7 +282,7 @@ if ($show_announcement_list) {
     $table->set_header(5, get_lang('Teacher'));
     $table->set_header(6, get_lang('Student'));
     $table->set_header(7, get_lang('Guest'));
-    
+
     $table->set_header(8, get_lang('Language'));
     $table->set_header(9, get_lang('Modify'), false, 'width="50px"');
     $form_actions = array();

+ 2 - 2
main/admin/usergroups.php

@@ -18,7 +18,7 @@ api_protect_admin_script(true);
 $htmlHeadXtra[] = api_get_jqgrid_js();
 // setting breadcrumbs
 $interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
-$action = $_GET['action'];
+$action = isset($_GET['action']) ? $_GET['action'] : null;
 if ($action == 'add') {
     $interbreadcrumb[] = array('url' => 'usergroups.php','name' => get_lang('Classes'));
     $interbreadcrumb[] = array('url' => '#','name' => get_lang('Add'));
@@ -30,7 +30,7 @@ if ($action == 'add') {
 }
 
 // The header.
-Display::display_header($tool_name);
+Display::display_header();
 
 // Tool name
 if (isset($_GET['action']) && $_GET['action'] == 'add') {

+ 1 - 1
main/attendance/attendance_list.php

@@ -34,7 +34,7 @@ $table->set_header(3, get_lang('CountDoneAttendance'), true, array('style'=>'wid
 
 if (api_is_allowed_to_edit(null, true)) {
 	$table->set_header(4, get_lang('Actions'), false, array('style'=>'text-align:center'));
-	$table->set_form_actions(array ('attendance_delete_select' => get_lang('DeleteAllAttendances')));	
+	$table->set_form_actions(array ('attendance_delete_select' => get_lang('DeleteAllSelectedAttendances')));	
 }
 
 if ($table->get_total_number_of_items() > 0) {

+ 0 - 0
main/css/default_scorm.css


+ 2 - 2
main/exercice/aiken.php

@@ -10,7 +10,7 @@
  * Code
  */
 // name of the language file that needs to be included
-$language_file = 'exercice';
+$language_file = array('exercice', 'gradebook');
 
 // including the global Chamilo file
 require_once '../inc/global.inc.php';
@@ -55,4 +55,4 @@ if ((api_is_allowed_to_edit(null, true))) {
 aiken_display_form($msg);
 
 // display the footer
-Display::display_footer();
+Display::display_footer();

+ 34 - 30
main/exercice/answer.class.php

@@ -99,35 +99,39 @@ class Answer
     }
 
     /**
-     * Reads answer informations from the data base
+     * Reads answer information from the database
      *
      * @author - Olivier Brouckaert
      */
-    function read() {
+    public function read()
+    {
         $TBL_ANSWER = Database::get_course_table(TABLE_QUIZ_ANSWER);
         $questionId = $this->questionId;
 
-        $sql="SELECT id, id_auto, answer,correct,comment,ponderation, position, hotspot_coordinates, hotspot_type, destination  FROM
-              $TBL_ANSWER WHERE c_id = {$this->course_id} AND question_id ='".$questionId."' ORDER BY position";
+        $sql = "SELECT * FROM $TBL_ANSWER
+                WHERE
+                    c_id = {$this->course_id} AND
+                    question_id ='".$questionId."'
+                ORDER BY position";
 
         $result = Database::query($sql);
         $i=1;
 
 		// while a record is found
-		while ($object=Database::fetch_object($result)) {
-			$this->id[$i]					= $object->id;
-			$this->answer[$i]				= $object->answer;
-			$this->correct[$i]				= $object->correct;
-			$this->comment[$i]				= $object->comment;
-			$this->weighting[$i]			= $object->ponderation;
-			$this->position[$i]				= $object->position;
-			$this->hotspot_coordinates[$i]	= $object->hotspot_coordinates;
-			$this->hotspot_type[$i]			= $object->hotspot_type;
-			$this->destination[$i]			= $object->destination;
-			$this->autoId[$i]				= $object->id_auto;
+		while ($object = Database::fetch_object($result)) {
+			$this->id[$i] = $object->id;
+			$this->answer[$i] = $object->answer;
+			$this->correct[$i] = $object->correct;
+			$this->comment[$i] = $object->comment;
+			$this->weighting[$i] = $object->ponderation;
+			$this->position[$i] = $object->position;
+			$this->hotspot_coordinates[$i] = $object->hotspot_coordinates;
+			$this->hotspot_type[$i] = $object->hotspot_type;
+			$this->destination[$i] = $object->destination;
+			$this->autoId[$i] = $object->id_auto;
 			$i++;
 		}
-		$this->nbrAnswers=$i-1;
+		$this->nbrAnswers = $i-1;
 	}
 
      /**
@@ -136,27 +140,27 @@ class Answer
      * @author - Yoselyn Castillo
      * @return - array - $id (answer ids)
      */
-    function selectAnswerId()
+    public function selectAnswerId()
     {
-		    $TBL_ANSWER = Database::get_course_table(TABLE_QUIZ_ANSWER);
-		    $questionId = $this->questionId;
+        $TBL_ANSWER = Database::get_course_table(TABLE_QUIZ_ANSWER);
+        $questionId = $this->questionId;
 
-		    $sql="SELECT id FROM
-		          $TBL_ANSWER WHERE c_id = {$this->course_id} AND question_id ='".$questionId."'";
+        $sql="SELECT id FROM
+              $TBL_ANSWER WHERE c_id = {$this->course_id} AND question_id ='".$questionId."'";
 
-		    $result = Database::query($sql);
-		    $id = array();
-		    // while a record is found
+        $result = Database::query($sql);
+        $id = array();
+        // while a record is found
         if (Database::num_rows($result) > 0) {
             while ($object = Database::fetch_array($result)) {
-    			      $id[] = $object['id'];
-    		    }
+                  $id[] = $object['id'];
+            }
         }
-		    return $id;
+        return $id;
 	}
 
     /**
-     * reads answer informations from the data base ordered by parameter
+     * Reads answer information from the data base ordered by parameter
      * @param	string	Field we want to order by
      * @param	string	DESC or ASC
      * @author 	Frederic Vauthier
@@ -185,10 +189,10 @@ class Answer
                "ORDER BY $field $order";
 		$result=Database::query($sql);
 
-		$i=1;
+		$i = 1;
 		// while a record is found
 		$doubt_data = null;
-		while($object=Database::fetch_object($result)) {
+		while($object = Database::fetch_object($result)) {
 		    if ($question_type['type'] == UNIQUE_ANSWER_NO_OPTION && $object->position == 666) {
 		        $doubt_data = $object;
                 continue;

+ 13 - 3
main/exercice/exercice.php

@@ -290,23 +290,33 @@ if ($is_allowedToEdit) {
 
     if (!empty($hpchoice)) {
         switch ($hpchoice) {
-            case 'delete' : // deletes an exercise
+            case 'delete' :
+                // deletes an exercise
                 $imgparams = array();
                 $imgcount = 0;
                 GetImgParams($file, $documentPath, $imgparams, $imgcount);
                 $fld = GetFolderName($file);
+
                 for ($i = 0; $i < $imgcount; $i++) {
                     my_delete($documentPath.$uploadPath."/".$fld."/".$imgparams[$i]);
                     update_db_info("delete", $uploadPath."/".$fld."/".$imgparams[$i]);
                 }
 
-                if (my_delete($documentPath.$file)) {
+                if (!is_dir($documentPath.$uploadPath."/".$fld."/")) {
+                    my_delete($documentPath.$file);
                     update_db_info("delete", $file);
+                } else {
+                    if (my_delete($documentPath.$file)) {
+                        update_db_info("delete", $file);
+                    }
                 }
+
                 // hotpotatoes folder may contains several tests so don't delete folder if not empty : http://support.chamilo.org/issues/2165
+
                 if (!(strstr($uploadPath, DIR_HOTPOTATOES) && !folder_is_empty($documentPath.$uploadPath."/".$fld."/"))) {
                     my_delete($documentPath.$uploadPath."/".$fld."/");
-                } break;
+                }
+                break;
             case 'enable' : // enables an exercise
                 $newVisibilityStatus = "1"; //"visible"
                 $query = "SELECT id FROM $TBL_DOCUMENT WHERE c_id = $course_id AND path='".Database :: escape_string($file)."'";

+ 74 - 57
main/exercice/exercise.class.php

@@ -1955,27 +1955,40 @@ class Exercise {
      * @todo    reduce parameters of this function
      * @return  string  html code
      */
-    public function manage_answer($exeId, $questionId, $choice, $from = 'exercise_show', $exerciseResultCoordinates = array(), $saved_results = true, $from_database = false, $show_result = true, $propagate_neg = 0, $hotspot_delineation_result = array())
-    {
+    public function manage_answer(
+        $exeId,
+        $questionId,
+        $choice,
+        $from = 'exercise_show',
+        $exerciseResultCoordinates = array(),
+        $saved_results = true,
+        $from_database = false,
+        $show_result = true,
+        $propagate_neg = 0,
+        $hotspot_delineation_result = array()
+    ) {
         global $debug;
-        global $learnpath_id, $learnpath_item_id; //needed in order to use in the exercise_attempt() for the time
+        //needed in order to use in the exercise_attempt() for the time
+        global $learnpath_id, $learnpath_item_id;
+        require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
 
         $feedback_type = $this->selectFeedbackType();
         $results_disabled = $this->selectResultsDisabled();
 
-        require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
-
-        if ($debug) error_log("<------ manage_answer ------> ");
-        if ($debug) error_log('manage_answer called exe_id: '.$exeId);
-        if ($debug) error_log('manage_answer $from:  '.$from);
-        if ($debug) error_log('manage_answer $saved_results: '.$saved_results);
-        if ($debug) error_log('manage_answer $from_database: '.$from_database);
-        if ($debug) error_log('manage_answer $show_result: '.$show_result);
-        if ($debug) error_log('manage_answer $propagate_neg: '.$propagate_neg);
-        if ($debug) error_log('manage_answer $exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
-        if ($debug) error_log('manage_answer $hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
-        if ($debug) error_log('manage_answer $learnpath_id: '.$learnpath_id);
-        if ($debug) error_log('manage_answer $learnpath_item_id: '.$learnpath_item_id);
+        if ($debug) {
+            error_log("<------ manage_answer ------> ");
+            error_log('exe_id: '.$exeId);
+            error_log('$from:  '.$from);
+            error_log('$saved_results: '.intval($saved_results));
+            error_log('$from_database: '.intval($from_database));
+            error_log('$show_result: '.$show_result);
+            error_log('$propagate_neg: '.$propagate_neg);
+            error_log('$exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
+            error_log('$hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
+            error_log('$learnpath_id: '.$learnpath_id);
+            error_log('$learnpath_item_id: '.$learnpath_item_id);
+            error_log('$choice: '.print_r($choice, 1));
+        }
 
         $extra_data = array();
         $final_overlap = 0;
@@ -1993,8 +2006,8 @@ class Exercise {
 
         $questionId   = intval($questionId);
         $exeId        = intval($exeId);
-        $TBL_TRACK_ATTEMPT      = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-        $table_ans              = Database::get_course_table(TABLE_QUIZ_ANSWER);
+        $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
 
         // Creates a temporary Question object
         $course_id              = api_get_course_int_id();
@@ -2012,28 +2025,30 @@ class Exercise {
 
         $next = 1; //not for now
 
-        //Extra information of the question
+        // Extra information of the question
         if (!empty($extra)) {
-            $extra          = explode(':', $extra);
+            $extra = explode(':', $extra);
             if ($debug) error_log(print_r($extra, 1));
-            //Fixes problems with negatives values using intval
-            $true_score     = intval($extra[0]);
-            $false_score    = intval($extra[1]);
-            $doubt_score    = intval($extra[2]);
+            // Fixes problems with negatives values using intval
+            $true_score     = floatval(trim($extra[0]));
+            $false_score    = floatval(trim($extra[1]));
+            $doubt_score    = floatval(trim($extra[2]));
         }
 
         $totalWeighting 		= 0;
         $totalScore				= 0;
 
         // Destruction of the Question object
-        unset ($objQuestionTmp);
+        unset($objQuestionTmp);
 
         // Construction of the Answer object
         $objAnswerTmp = new Answer($questionId);
         $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
 
-        if ($debug) error_log('Count of answers: '.$nbrAnswers);
-        if ($debug) error_log('$answerType: '.$answerType);
+        if ($debug) {
+            error_log('Count of answers: '.$nbrAnswers);
+            error_log('$answerType: '.$answerType);
+        }
 
         if ($answerType == FREE_ANSWER || $answerType == ORAL_EXPRESSION) {
             $nbrAnswers = 1;
@@ -2065,7 +2080,8 @@ class Exercise {
         $user_answer = '';
 
         // Get answer list for matching
-        $sql_answer = 'SELECT id, answer FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id = "'.$questionId.'" ';
+        $sql_answer = 'SELECT id, answer FROM '.$table_ans.'
+                       WHERE c_id = '.$course_id.' AND question_id = "'.$questionId.'"';
         $res_answer = Database::query($sql_answer);
 
         $answer_matching =array();
@@ -2077,7 +2093,6 @@ class Exercise {
         $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
 
         $organs_at_risk_hit = 0;
-
         $questionScore = 0;
 
         if ($debug) error_log('Start answer loop ');
@@ -2085,20 +2100,20 @@ class Exercise {
         $answer_correct_array = array();
 
         for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
-            $answer             = $objAnswerTmp->selectAnswer($answerId);
-            $answerComment      = $objAnswerTmp->selectComment($answerId);
-            $answerCorrect      = $objAnswerTmp->isCorrect($answerId);
-            $answerWeighting    = (float)$objAnswerTmp->selectWeighting($answerId);
-
-            $numAnswer          = $objAnswerTmp->selectAutoId($answerId);
-
+            $answer = $objAnswerTmp->selectAnswer($answerId);
+            $answerComment = $objAnswerTmp->selectComment($answerId);
+            $answerCorrect = $objAnswerTmp->isCorrect($answerId);
+            $answerWeighting = (float)$objAnswerTmp->selectWeighting($answerId);
+            $numAnswer = $objAnswerTmp->selectAutoId($answerId);
             $answer_correct_array[$answerId] = (bool)$answerCorrect;
 
-            if ($debug) error_log("answer auto id: $numAnswer ");
-            if ($debug) error_log("answer correct : $answerCorrect ");
+            if ($debug) {
+                error_log("answer auto id: $numAnswer ");
+                error_log("answer correct: $answerCorrect ");
+            }
 
-            //delineation
-            $delineation_cord   = $objAnswerTmp->selectHotspotCoordinates(1);
+            // Delineation
+            $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
             $answer_delineation_destination=$objAnswerTmp->selectDestination(1);
 
             switch ($answerType) {
@@ -2106,7 +2121,8 @@ class Exercise {
                 case UNIQUE_ANSWER :
                 case UNIQUE_ANSWER_NO_OPTION :
                     if ($from_database) {
-                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' and question_id= '".$questionId."'";
+                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
+                        WHERE exe_id = '".$exeId."' and question_id= '".$questionId."'";
                         $resultans = Database::query($queryans);
                         $choice = Database::result($resultans,0,"answer");
 
@@ -2116,7 +2132,7 @@ class Exercise {
                             $totalScore+=$answerWeighting;
                         }
                     } else {
-                        $studentChoice = ($choice == $numAnswer)?1:0;
+                        $studentChoice = ($choice == $numAnswer) ? 1 : 0;
                         if ($studentChoice) {
                             $questionScore+=$answerWeighting;
                             $totalScore+=$answerWeighting;
@@ -2127,32 +2143,33 @@ class Exercise {
                 case MULTIPLE_ANSWER_TRUE_FALSE:
                     if ($from_database) {
                         $choice = array();
-                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = ".$exeId." and question_id = ".$questionId;
-                        $resultans = Database::query($queryans);
+                        $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
+                                WHERE
+                                    exe_id = ".$exeId." AND
+                                    question_id = ".$questionId;
+                        $resultans = Database::query($sql);
                         while ($row = Database::fetch_array($resultans)) {
-                            $ind          = $row['answer'];
-                            $result       = explode(':',$ind);
+                            $ind = $row['answer'];
+                            $result = explode(':', $ind);
                             $my_answer_id = $result[0];
-                            $option       = $result[1];
+                            $option = $result[1];
                             $choice[$my_answer_id] = $option;
                         }
-                        $studentChoice  =$choice[$numAnswer];
-                    } else {
-                        $studentChoice  =$choice[$numAnswer];
                     }
+                    $studentChoice = isset($choice[$numAnswer]) ? $choice[$numAnswer] : null;
 
                     if (!empty($studentChoice)) {
-                        if ($studentChoice == $answerCorrect ) {
+                        if ($studentChoice == $answerCorrect) {
                             $questionScore  += $true_score;
                         } else {
                             if ($quiz_question_options[$studentChoice]['name'] != "Don't know") {
-                                $questionScore   +=  $false_score;
+                                $questionScore += $false_score;
                             } else {
-                                $questionScore  +=  $doubt_score;
+                                $questionScore += $doubt_score;
                             }
                         }
                     } else {
-                        //if no result then the user just hit don't know
+                        // If no result then the user just hit don't know
                         $studentChoice = 3;
                         $questionScore  +=  $doubt_score;
                     }
@@ -2161,7 +2178,8 @@ class Exercise {
                 case MULTIPLE_ANSWER: //2
                     if ($from_database) {
                         $choice = array();
-                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
+                        $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
+                                     WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
                         $resultans = Database::query($queryans);
                         while ($row = Database::fetch_array($resultans)) {
                             $ind = $row['answer'];
@@ -2182,7 +2200,7 @@ class Exercise {
                             $questionScore  += $answerWeighting;
                         }
                     }
-                    $totalScore     += $answerWeighting;
+                    $totalScore += $answerWeighting;
 
                     if ($debug) error_log("studentChoice: $studentChoice");
                     break;
@@ -2285,7 +2303,6 @@ class Exercise {
                     break;
                 // for fill in the blanks
                 case FILL_IN_BLANKS:
-
                     // the question is encoded like this
                     // [A] B [C] D [E] F::10,10,10@1
                     // number 1 before the "@" means that is a switchable fill in blank question

+ 19 - 15
main/exercice/exercise_report.php

@@ -43,6 +43,9 @@ require_once api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php';
 
 // document path
 $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
+$origin = isset($origin) ? $origin : null;
+$gradebook = isset($gradebook) ? $gradebook : null;
+$path = isset($_GET['path']) ? Security::remove_XSS($_GET['path']) : null;
 
 /* 	Constants and variables */
 $is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_drh();
@@ -102,7 +105,9 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
 }
 
 //Send student email @todo move this code in a class, library
-if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid'] == strval(intval($_GET['exeid']))) {
+if (isset($_REQUEST['comments']) &&
+    $_REQUEST['comments'] == 'update' &&
+    ($is_allowedToEdit || $is_tutor) && $_GET['exeid'] == strval(intval($_GET['exeid']))) {
     $id = intval($_GET['exeid']); //filtered by post-condition
     $track_exercise_info = get_exercise_track_exercise_info($id);
     if (empty($track_exercise_info)) {
@@ -213,18 +218,20 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G
     }
 }
 
-
+$actions = null;
 if ($is_allowedToEdit && $origin != 'learnpath') {
     // the form
     if (api_is_platform_admin() || api_is_course_admin() || api_is_course_tutor() || api_is_course_coach()) {
         $actions .= '<a href="admin.php?exerciseId='.intval($_GET['exerciseId']).'">'.Display :: return_icon('back.png', get_lang('GoBackToQuestionList'), '', ICON_SIZE_MEDIUM).'</a>';
         $actions .='<a href="live_stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.Display :: return_icon('activity_monitor.png', get_lang('LiveResults'), '', ICON_SIZE_MEDIUM).'</a>';
         $actions .='<a href="stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.Display :: return_icon('statistics.png', get_lang('ReportByQuestion'), '', ICON_SIZE_MEDIUM).'</a>';
-        $actions .= '<a id="export_opener" href="'.api_get_self().'?export_report=1&hotpotato_name='.Security::remove_XSS($_GET['path']).'&exerciseId='.intval($_GET['exerciseId']).'" >'.
+        $actions .= '<a id="export_opener" href="'.api_get_self().'?export_report=1&hotpotato_name='.$path.'&exerciseId='.intval($_GET['exerciseId']).'" >'.
         Display::return_icon('save.png', get_lang('Export'), '', ICON_SIZE_MEDIUM).'</a>';
         // clean result before a selected date icon
         $actions .= Display::url(
-            Display::return_icon('clean_before_date.png', get_lang('CleanStudentsResultsBeforeDate'), '', ICON_SIZE_MEDIUM), '', array('onclick' => "javascript:display_date_picker()", 'href' => '#')
+            Display::return_icon('clean_before_date.png', get_lang('CleanStudentsResultsBeforeDate'), '', ICON_SIZE_MEDIUM),
+            '#',
+            array('onclick' => "javascript:display_date_picker()")
         );
         // clean result before a selected date datepicker popup
         $actions .= Display::span(
@@ -241,7 +248,7 @@ if ($is_allowedToEdit && $origin != 'learnpath') {
 }
 
 //Deleting an attempt
-if (($is_allowedToEdit || $is_tutor || api_is_coach()) && $_GET['delete'] == 'delete' && !empty($_GET['did']) && $locked == false) {
+if (($is_allowedToEdit || $is_tutor || api_is_coach()) && isset($_GET['delete']) && $_GET['delete'] == 'delete' && !empty($_GET['did']) && $locked == false) {
     $exe_id = intval($_GET['did']);
     if (!empty($exe_id)) {
         $sql = 'DELETE FROM '.$TBL_TRACK_EXERCICES.' WHERE exe_id = '.$exe_id;
@@ -272,7 +279,6 @@ if ($is_allowedToEdit || $is_tutor) {
 Display :: display_header($nameTools);
 
 // Clean all results for this test before the selected date
-$datepicker_language = get_datepicker_langage_code();
 if (($is_allowedToEdit || $is_tutor || api_is_coach()) && isset($_GET['delete_before_date']) && $locked == false) {
     // ask for the date
     $check = Security::check_token('get');
@@ -548,14 +554,10 @@ $extra_params['height'] = 'auto';
             if (datapickerInputModified) {
                 var dateTypeVar = $('#datepicker_start').datepicker('getDate');
                 var dateForBDD = $.datepicker.formatDate('yy-mm-dd', dateTypeVar);
-                // format the date for confirm box
-                var selectedDate = $.datepicker.formatDate( "DD, MM d, yy", dateTypeVar, {
-                    dayNamesShort: $.datepicker.regional[ "<?php echo $datepicker_language; ?>" ].dayNamesShort,
-                    dayNames: $.datepicker.regional[ "<?php echo $datepicker_language; ?>" ].dayNames,
-                    monthNamesShort: $.datepicker.regional[ "<?php echo $datepicker_language; ?>" ].monthNamesShort,
-                    monthNames: $.datepicker.regional[ "<?php echo $datepicker_language; ?>" ].monthNames
-                });
-                if (confirm("<?php echo convert_double_quote_to_single(get_lang('AreYouSureDeleteTestResultBeforeDateD')) ?>"+" "+selectedDate)) {
+                // Format the date for confirm box
+                var dateFormat = $( "#datepicker_start" ).datepicker( "option", "dateFormat" );
+                var selectedDate = $.datepicker.formatDate(dateFormat, dateTypeVar);
+                if (confirm("<?php echo convert_double_quote_to_single(get_lang('AreYouSureDeleteTestResultBeforeDateD')); ?>" + selectedDate)) {
                     self.location.href = "exercise_report.php?<?php echo api_get_cidreq(); ?>&exerciseId=<?php echo $exercise_id; ?>&delete_before_date="+dateForBDD+"&sec_token=<?php echo $token; ?>";
                 }
             }
@@ -564,12 +566,14 @@ $extra_params['height'] = 'auto';
         /**
         * initiate datepicker
         */
-        $(function(){
+        $(function() {
+
             $( "#datepicker_start" ).datepicker({
                 defaultDate: "",
                 changeMonth: false,
                 numberOfMonths: 1
             });
+
         });
 
 </script>

+ 13 - 4
main/exercice/exercise_result.php

@@ -45,12 +45,21 @@ $this_section = SECTION_COURSES;
 /* 	ACCESS RIGHTS  */
 api_protect_course_script(true);
 
-if ($debug){ error_log('Entering exercise_result.php: '.print_r($_POST,1));}
+if ($debug) {
+    error_log('Entering exercise_result.php: '.print_r($_POST, 1));
+}
 
 // general parameters passed via POST/GET
-if ( empty ( $origin ) ) {                  $origin                 = Security::remove_XSS($_REQUEST['origin']);}
-if ( empty ( $objExercise ) ) {             $objExercise            = $_SESSION['objExercise'];}
-if ( empty ( $remind_list ) ) {             $remind_list            = $_REQUEST['remind_list'];}
+// general parameters passed via POST/GET
+if (empty($origin)) {
+    $origin = Security::remove_XSS($_REQUEST['origin']);
+}
+if (empty($objExercise)) {
+    $objExercise = $_SESSION['objExercise'];
+}
+if (empty($remind_list)) {
+    $remind_list = isset($_REQUEST['remind_list']) ? $_REQUEST['remind_list'] : null;
+}
 
 $exe_id = isset($_REQUEST['exe_id']) ? intval($_REQUEST['exe_id']) : 0;
 

+ 3 - 2
main/inc/ajax/model.ajax.php

@@ -996,6 +996,7 @@ switch ($action) {
         $columns = array('name', 'users', 'actions');
         $options = array('order'=>"name $sord", 'LIMIT'=> "$start , $limit");
         $options['course_id'] = $course_id;
+
         switch ($type) {
             case 'not_registered':
                 $options['where'] = array(" (course_id IS NULL OR course_id != ?) " => $course_id);
@@ -1017,8 +1018,8 @@ switch ($action) {
                     $url  = 'class.php?action=add_class_to_course&id='.$group['id'];
                     $icon = Display::return_icon('add.png', get_lang('Add'));
                 }
-                $group['actions']    = Display::url($icon, $url);
-                $new_result[]        = $group;
+                $group['actions'] = Display::url($icon, $url);
+                $new_result[] = $group;
             }
             $result = $new_result;
         }

+ 43 - 11
main/inc/lib/display.lib.php

@@ -342,8 +342,13 @@ class Display
      * @param bool	Filter (true) or not (false)
      * @return void
      */
-    public static function display_normal_message($message, $filter = true) {
-    	echo self::return_message($message, 'normal', $filter);
+    public static function display_normal_message($message, $filter = true, $returnValue = false) {
+    	$message = self::return_message($message, 'normal', $filter);
+        if ($returnValue) {
+            return $message;
+        } else {
+            echo $message;
+        }
     }
 
     /**
@@ -351,8 +356,14 @@ class Display
      * This can also be used for instance with the hint in the exercises
      *
      */
-    public static function display_warning_message($message, $filter = true) {
-    	echo self::return_message($message, 'warning', $filter);
+    public static function display_warning_message($message, $filter = true, $returnValue = false)
+    {
+        $message = self::return_message($message, 'warning', $filter);
+        if ($returnValue) {
+            return $message;
+        } else {
+            echo $message;
+        }
     }
 
     /**
@@ -360,8 +371,14 @@ class Display
      * @param bool	Filter (true) or not (false)
      * @return void
      */
-    public static function display_confirmation_message ($message, $filter = true) {
-        echo self::return_message($message, 'confirm', $filter);
+    public static function display_confirmation_message ($message, $filter = true, $returnValue = false)
+    {
+        $message = self::return_message($message, 'confirm', $filter);
+        if ($returnValue) {
+            return $message;
+        } else {
+            echo $message;
+        }
     }
 
     /**
@@ -371,11 +388,23 @@ class Display
      * @param bool	Filter (true) or not (false)
      * @return void
      */
-    public static function display_error_message ($message, $filter = true) {
-        echo self::return_message($message, 'error', $filter);
+    public static function display_error_message ($message, $filter = true, $returnValue = false)
+    {
+        $message = self::return_message($message, 'error', $filter);
+        if ($returnValue) {
+            return $message;
+        } else {
+            echo $message;
+        }
     }
 
-    public static function return_message_and_translate($message, $type='normal', $filter = true) {
+    /**
+     * @param string $message
+     * @param string $type
+     * @param bool $filter
+     */
+    public static function return_message_and_translate($message, $type='normal', $filter = true)
+    {
         $message = get_lang($message);
         echo self::return_message($message, $type, $filter);
     }
@@ -387,11 +416,13 @@ class Display
      * @param   bool    Whether to XSS-filter or not
      * @return  string  Message wrapped into an HTML div
      */
-    public static function return_message($message, $type='normal', $filter = true) {
+    public static function return_message($message, $type='normal', $filter = true)
+    {
         if ($filter) {
         	$message = api_htmlentities($message, ENT_QUOTES, api_is_xml_http_request() ? 'UTF-8' : api_get_system_encoding());
             //$message = Security::remove_XSS($message);
         }
+
         $class = "";
         switch($type) {
             case 'warning':
@@ -420,7 +451,8 @@ class Display
      * @param string  optional, class from stylesheet
      * @return string encrypted mailto hyperlink
      */
-    public static function encrypted_mailto_link ($email, $clickable_text = null, $style_class = '') {
+    public static function encrypted_mailto_link ($email, $clickable_text = null, $style_class = '')
+    {
         if (is_null($clickable_text)) {
             $clickable_text = $email;
         }

+ 7 - 2
main/inc/lib/document.lib.php

@@ -1169,7 +1169,11 @@ class DocumentManager
 
         if (!empty($course_id) && !empty($path)) {
             $sql = "SELECT id FROM $TABLE_DOCUMENT
-                    WHERE c_id = $course_id AND path LIKE BINARY '$path' AND session_id = $sessionId LIMIT 1";
+                    WHERE
+                        c_id = $course_id AND
+                        path LIKE BINARY '$path' AND
+                        session_id = $sessionId
+                    LIMIT 1";
             $result = Database::query($sql);
             if ($result && Database::num_rows($result)) {
                 $row = Database::fetch_array($result);
@@ -1207,7 +1211,8 @@ class DocumentManager
 
         $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
         $id = intval($id);
-        $sql = "SELECT * FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND session_id = $session_id AND id = $id ";
+        $sql = "SELECT * FROM $TABLE_DOCUMENT
+                WHERE c_id = $course_id AND session_id = $session_id AND id = $id";
         $result = Database::query($sql);
         if ($result && Database::num_rows($result) == 1) {
             $row = Database::fetch_array($result, 'ASSOC');

+ 42 - 56
main/inc/lib/fileManage.lib.php

@@ -16,58 +16,43 @@
  * @desc Update the file or directory path in the document db document table
  *
  */
-function update_db_info($action, $old_path, $new_path = '') {
+function update_db_info($action, $old_path, $new_path = '')
+{
     $dbTable = Database::get_course_table(TABLE_DOCUMENT);
     $course_id = api_get_course_int_id();
-    
-	/* DELETE */
-	if ($action == 'delete') {
-		/*  // RH: metadata, update 2004/08/23
-		    these two lines replaced by new code below:
-        	$query = "DELETE FROM $dbTable
-    		WHERE path='".$old_path."' OR path LIKE '".$old_path."/%'";
-        */
-        $old_path = Database::escape_string($old_path);
-        $to_delete = "WHERE c_id = $course_id AND (path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%')";
-        $query = "DELETE FROM $dbTable " . $to_delete;
-
-        $result = Database::query("SELECT id FROM $dbTable " . $to_delete);
-
-        if (Database::num_rows($result)) {
-            require_once api_get_path(INCLUDE_PATH).'../metadata/md_funcs.php';
-            $mdStore = new mdstore(TRUE);  // create if needed
-
-            $md_type = (substr($dbTable, -13) == 'scormdocument') ? 'Scorm' : 'Document';
-
-            while ($row = Database::fetch_array($result)) {
-                $eid = $md_type . '.' . $row['id'];
-                $mdStore->mds_delete($eid);
-                $mdStore->mds_delete_offspring($eid);
+    switch ($action) {
+        case 'delete':
+            $old_path = Database::escape_string($old_path);
+            $to_delete = "WHERE c_id = $course_id AND (path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%')";
+            $query = "DELETE FROM $dbTable " . $to_delete;
+            $result = Database::query("SELECT id FROM $dbTable " . $to_delete);
+
+            if (Database::num_rows($result)) {
+                require_once api_get_path(INCLUDE_PATH).'../metadata/md_funcs.php';
+                $mdStore = new mdstore(TRUE);  // create if needed
+
+                $md_type = (substr($dbTable, -13) == 'scormdocument') ? 'Scorm' : 'Document';
+
+                while ($row = Database::fetch_array($result)) {
+                    $eid = $md_type . '.' . $row['id'];
+                    $mdStore->mds_delete($eid);
+                    $mdStore->mds_delete_offspring($eid);
+                }
             }
-        }
-	}
-
-	/* UPDATE */
-
-	if ($action == 'update') {
-		//Display::display_normal_message("new_path = $new_path");
-		if ($new_path[0] == '.') $new_path = substr($new_path, 1);
-		$new_path = str_replace('//', '/', $new_path);
-		//Display::display_normal_message("character 0 = " . $new_path[0] . " 1=" . $new_path[1]);
-		//Display::display_normal_message("new_path = $new_path");
-
-		// Older broken version
-		//$query = "UPDATE $dbTable
-		//SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
-		//WHERE path = '".$old_path."' OR path LIKE '".$old_path."/%'";
-
-		// Attempt to update	- tested & working for root	dir
-		$new_path = Database::escape_string($new_path);
-		$query = "UPDATE $dbTable
-		SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
-		WHERE c_id = $course_id AND (path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%')";
-	}	
-	Database::query($query);
+            Database::query($query);
+            break;
+        case 'update':
+            if ($new_path[0] == '.') $new_path = substr($new_path, 1);
+            $new_path = str_replace('//', '/', $new_path);
+
+            // Attempt to update	- tested & working for root	dir
+            $new_path = Database::escape_string($new_path);
+            $query = "UPDATE $dbTable SET
+                        path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
+                    WHERE c_id = $course_id AND (path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%')";
+            Database::query($query);
+            break;
+    }
 }
 
 /**
@@ -100,9 +85,8 @@ function check_name_exist($file_path) {
  * Deletes a file or a directory
  *
  * @author - Hugues Peeters
- * @param  - $file (String) - the path of file or directory to delete
- * @return - bolean - true if the delete succeed
- *           bolean - false otherwise.
+ * @param  $file (String) - the path of file or directory to delete
+ * @return boolean - true if the delete succeed, false otherwise.
  * @see    - delete() uses check_name_exist() and removeDir() functions
  */
 function my_delete($file) {
@@ -159,17 +143,19 @@ function removeDir($dir) {
 
 
 /**
- * Return true if folder is empty 
+ * Return true if folder is empty
  * @author : hubert.borderiou@grenet.fr
  * @param string $in_folder : folder path on disk
  * @return 1 if folder is empty, 0 otherwise
 */
 
 function folder_is_empty($in_folder) {
-    $tab_folder_content = scandir($in_folder);
     $folder_is_empty = 0;
-    if ((count($tab_folder_content) == 2 && in_array(".", $tab_folder_content) && in_array("..", $tab_folder_content)) || (count($tab_folder_content) < 2)) {
-        $folder_is_empty = 1;
+    if (is_dir($in_folder)) {
+        $tab_folder_content = scandir($in_folder);
+        if ((count($tab_folder_content) == 2 && in_array(".", $tab_folder_content) && in_array("..", $tab_folder_content)) || (count($tab_folder_content) < 2)) {
+            $folder_is_empty = 1;
+        }
     }
     return $folder_is_empty;
 }

+ 20 - 21
main/inc/lib/formvalidator/Element/datepicker.php

@@ -9,57 +9,54 @@ class HTML_QuickForm_datepicker extends HTML_QuickForm_date
 	/**
 	 * Constructor
 	 */
-	function HTML_QuickForm_datepicker($elementName = null, $elementLabel = null, $attributes = null, $optionIncrement = null)
+	public function HTML_QuickForm_datepicker($elementName = null, $elementLabel = null, $attributes = null, $optionIncrement = null)
 	{
-		$js_form_name = $attributes['form_name'];
-		unset($attributes['form_name']);
-		HTML_QuickForm_element :: HTML_QuickForm_element($elementName, $elementLabel, $attributes);
+		$js_form_name = api_get_unique_id();
+		HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
+
 		$this->_persistantFreeze = true;
 		$this->_appendName = true;
 		$this->_type = 'datepicker';
-		$popup_link = '<a href="javascript:openCalendar(\''.$js_form_name.'\',\''.$elementName.'\')"><img src="'.api_get_path(WEB_IMG_PATH).'calendar_select.gif" style="vertical-align:middle;" alt="Select Date" /></a>';
-		$special_chars = array ('D', 'l', 'd', 'M', 'F', 'm', 'y', 'H', 'a', 'A', 's', 'i', 'h', 'g', ' ');
+		$popup_link = '<a href="javascript:openCalendar(\''.$js_form_name.'\',\''.$elementName.'\')">
+		<img src="'.api_get_path(WEB_IMG_PATH).'calendar_select.gif" style="vertical-align:middle;" alt="Select Date" /></a>';
+
 		$hour_minute_devider = get_lang("HourMinuteDivider");
-		foreach ($special_chars as $index => $char)
-		{
+        $special_chars = array('D', 'l', 'd', 'M', 'F', 'm', 'y', 'H', 'a', 'A', 's', 'i', 'h', 'g', ' ');
+		foreach ($special_chars as $char) {
 			$popup_link = str_replace($char, "\\".$char, $popup_link);
 			$hour_minute_devider = str_replace($char, "\\".$char, $hour_minute_devider);
 		}
 		$lang_code = api_get_language_isocode();
 		// If translation not available in PEAR::HTML_QuickForm_date, add the Chamilo-translation
-		if(! array_key_exists($lang_code,$this->_locale))
-		{
+		if (!array_key_exists($lang_code,$this->_locale)) {
 			$this->_locale[$lang_code]['months_long'] = api_get_months_long();
 		}
 		$this->_options['format'] = 'dFY '.$popup_link.'   H '.$hour_minute_devider.' i';
 		$this->_options['minYear'] = date('Y')-5;
 		$this->_options['maxYear'] = date('Y')+10;
 		$this->_options['language'] = $lang_code;
-		//$this->_options['addEmptyOption'] = true;
-		//$this->_options['emptyOptionValue'] = 0;
-		//$this->_options['emptyOptionText'] = ' -- ';
 		if (isset($optionIncrement)) {
-        $this->_options['optionIncrement']['i'] = intval($optionIncrement);
+            $this->_options['optionIncrement']['i'] = intval($optionIncrement);
         }
-		
 	}
+
 	/**
 	 * HTML code to display this datepicker
 	 */
-	function toHtml()
+	public function toHtml()
 	{
 		$js = $this->getElementJS();
 		return $js.parent :: toHtml();
 	}
+
 	/**
 	 * Get the necessary javascript for this datepicker
 	 */
 	function getElementJS()
 	{
 		$js = '';
-		if(!defined('DATEPICKER_JAVASCRIPT_INCLUDED'))
-		{
-			define('DATEPICKER_JAVASCRIPT_INCLUDED',1);
+		if (!defined('DATEPICKER_JAVASCRIPT_INCLUDED')) {
+			define('DATEPICKER_JAVASCRIPT_INCLUDED', 1);
 			$js = "\n";
 			$js .= '<script src="';
 			$js .= api_get_path(WEB_CODE_PATH).'inc/lib/formvalidator/Element/';
@@ -68,8 +65,11 @@ class HTML_QuickForm_datepicker extends HTML_QuickForm_date
 		}
 		return $js;
 	}
+
 	/**
 	 * Export the date value in MySQL format
+     * @param array
+     * @param bool
 	 * @return string YYYY-MM-DD HH:II:SS
 	 */
 	function exportValue(&$submitValues, $assoc = false)
@@ -88,7 +88,7 @@ class HTML_QuickForm_datepicker extends HTML_QuickForm_date
 		$result[$this->getName()]= $datetime;
 		return $result;
 	}
-		/**
+    /**
 	 * Sets an option to a value
 	 */
 	function setLocalOption($name,$value)
@@ -96,4 +96,3 @@ class HTML_QuickForm_datepicker extends HTML_QuickForm_date
 		$this->_options[$name] = $value;
 	}
 }
-?>

+ 8 - 12
main/inc/lib/formvalidator/Element/datepickerdate.php

@@ -9,7 +9,8 @@ class HTML_QuickForm_datepickerdate extends HTML_QuickForm_date
 	/**
 	 * Constructor
 	 */
-	function HTML_QuickForm_datepickerdate($elementName = null, $elementLabel = null, $attributes = null) {
+	public function HTML_QuickForm_datepickerdate($elementName = null, $elementLabel = null, $attributes = null)
+    {
 		global $myMinYear, $myMaxYear;
 		$js_form_name = $attributes['form_name'];
 		unset($attributes['form_name']);
@@ -19,24 +20,20 @@ class HTML_QuickForm_datepickerdate extends HTML_QuickForm_date
 		$this->_type = 'datepicker';
 		$popup_link = '<a href="javascript:openCalendar(\''.$js_form_name.'\',\''.$elementName.'\')"><img src="'.api_get_path(WEB_IMG_PATH).'calendar_select.gif" style="vertical-align:middle;" alt="Select Date" /></a>';
 		$special_chars = array ('D', 'l', 'd', 'M', 'F', 'm', 'y', 'H', 'a', 'A', 's', 'i', 'h', 'g', ' ');
-		foreach ($special_chars as $index => $char)
-		{
+		foreach ($special_chars as $char) {
 			$popup_link = str_replace($char, "\\".$char, $popup_link);
 		}
 		$lang_code = api_get_language_isocode();
 		// If translation not available in PEAR::HTML_QuickForm_date, add the Chamilo-translation
-		if(! array_key_exists($lang_code,$this->_locale))
-		{
+		if (! array_key_exists($lang_code,$this->_locale)) {
 			$this->_locale[$lang_code]['months_long'] = api_get_months_long();
 		}
 		$this->_options['format'] = 'dFY '.$popup_link;
 		$this->_options['minYear'] = date('Y')-5;
 		$this->_options['maxYear'] = date('Y')+10;
 		$this->_options['language'] = $lang_code;
-		//$this->_options['addEmptyOption'] = true;
-		//$this->_options['emptyOptionValue'] = 0;
-		//$this->_options['emptyOptionText'] = ' -- ';
 	}
+
 	/**
 	 * HTML code to display this datepicker
 	 */
@@ -51,9 +48,8 @@ class HTML_QuickForm_datepickerdate extends HTML_QuickForm_date
 	function getElementJS()
 	{
 		$js = '';
-		if(!defined('DATEPICKER_JAVASCRIPT_INCLUDED'))
-		{
-			define('DATEPICKER_JAVASCRIPT_INCLUDED',1);
+		if(!defined('DATEPICKER_JAVASCRIPT_INCLUDED')) {
+			define('DATEPICKER_JAVASCRIPT_INCLUDED', 1);
 			$js = "\n";
 			$js .= '<script src="';
 			$js .= api_get_path(WEB_CODE_PATH).'inc/lib/formvalidator/Element/';
@@ -62,6 +58,7 @@ class HTML_QuickForm_datepickerdate extends HTML_QuickForm_date
 		}
 		return $js;
 	}
+
 	/**
 	 * Export the date value in MySQL format
 	 * @return string YYYY-MM-DD HH:II:SS
@@ -86,4 +83,3 @@ class HTML_QuickForm_datepickerdate extends HTML_QuickForm_date
 		$this->_options[$name] = $value;
 	}
 }
-?>

+ 35 - 30
main/inc/lib/lp_item.lib.php

@@ -2,15 +2,14 @@
 
 /**
  * Class lp_item
- *  made to manipulate datas of lp_item table
+ *  made to manipulate data of lp_item table
  *
- * This class is still incomplte
+ * This class is still incomplete
  * You can add lp_item database manipulation function here
  *
  */
-
-
-class LpItem {
+class LpItem
+{
     public $c_id=0;
     public $id=0;
     public $lp_id=0;
@@ -34,11 +33,14 @@ class LpItem {
     public $search_did=0;
     public $audio="";
 
-    public function __construct($in_c_id=0, $in_id=0) {
+    public function __construct($in_c_id=0, $in_id=0)
+    {
         if ($in_c_id > 0 && $in_id >0) {
             $item_view_table = Database::get_course_table(TABLE_LP_ITEM);
-            $sql = "SELECT * FROM $item_view_table WHERE c_id=".Database::escape_string($in_c_id)."
-                    AND id=".Database::escape_string($in_id);
+            $sql = "SELECT * FROM $item_view_table
+                    WHERE
+                        c_id=".Database::escape_string($in_c_id)." AND
+                        id=".Database::escape_string($in_id);
 
             $res = Database::query($sql);
             $data = Database::fetch_array($res);
@@ -69,33 +71,36 @@ class LpItem {
         }
     }
 
-    public function update_in_bdd() {
+    /**
+     * Update in database
+     */
+    public function update_in_bdd()
+    {
         $item_view_table = Database::get_course_table(TABLE_LP_ITEM);
         if ($this->c_id > 0 && $this->id > 0) {
             $sql = "UPDATE $item_view_table SET
-                    lp_id = '".Database::escape_string($this->lp_id)."' ,
-                    item_type = '".Database::escape_string($this->item_type)."' ,
-                    ref = '".Database::escape_string($this->ref)."' ,
-                    title = '".Database::escape_string($this->title)."' ,
-                    description = '".Database::escape_string($this->description)."' ,
-                    path = '".Database::escape_string($this->path)."' ,
-                    min_score = '".Database::escape_string($this->min_score)."' ,
-                    max_score = '".Database::escape_string($this->max_score)."' ,
-                    mastery_score = '".Database::escape_string($this->mastery_score)."' ,
-                    parent_item_id = '".Database::escape_string($this->parent_item_id)."' ,
-                    previous_item_id = '".Database::escape_string($this->previous_item_id)."' ,
-                    next_item_id = '".Database::escape_string($this->next_item_id)."' ,
-                    display_order = '".Database::escape_string($this->display_order)."' ,
-                    prerequisite = '".Database::escape_string($this->prerequisite)."' ,
-                    parameters = '".Database::escape_string($this->parameters)."' ,
-                    launch_data = '".Database::escape_string($this->launch_data)."' ,
-                    max_time_allowed = '".Database::escape_string($this->max_time_allowed)."' ,
-                    terms = '".Database::escape_string($this->terms)."' ,
-                    search_did = '".Database::escape_string($this->search_did)."' ,
-                    audio = '".Database::escape_string($this->audio)."'
+                        lp_id = '".Database::escape_string($this->lp_id)."' ,
+                        item_type = '".Database::escape_string($this->item_type)."' ,
+                        ref = '".Database::escape_string($this->ref)."' ,
+                        title = '".Database::escape_string($this->title)."' ,
+                        description = '".Database::escape_string($this->description)."' ,
+                        path = '".Database::escape_string($this->path)."' ,
+                        min_score = '".Database::escape_string($this->min_score)."' ,
+                        max_score = '".Database::escape_string($this->max_score)."' ,
+                        mastery_score = '".Database::escape_string($this->mastery_score)."' ,
+                        parent_item_id = '".Database::escape_string($this->parent_item_id)."' ,
+                        previous_item_id = '".Database::escape_string($this->previous_item_id)."' ,
+                        next_item_id = '".Database::escape_string($this->next_item_id)."' ,
+                        display_order = '".Database::escape_string($this->display_order)."' ,
+                        prerequisite = '".Database::escape_string($this->prerequisite)."' ,
+                        parameters = '".Database::escape_string($this->parameters)."' ,
+                        launch_data = '".Database::escape_string($this->launch_data)."' ,
+                        max_time_allowed = '".Database::escape_string($this->max_time_allowed)."' ,
+                        terms = '".Database::escape_string($this->terms)."' ,
+                        search_did = '".Database::escape_string($this->search_did)."' ,
+                        audio = '".Database::escape_string($this->audio)."'
                     WHERE c_id=".$this->c_id." AND id=".$this->id;
             Database::query($sql);
         }
     }
-
 }

+ 23 - 3
main/inc/lib/main_api.lib.php

@@ -6017,7 +6017,9 @@ function api_get_jquery_libraries_js($libraries) {
         $platform_isocode = strtolower(api_get_language_isocode());
 
         //languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
-        $jqgrid_langs = array('bg', 'bg1251', 'cat','cn','cs','da','de','el','en','es','fa','fi','fr','gl','he','hu','is','it','ja','nl','no','pl','pt-br','pt','ro','ru','sk','sr','sv','tr','ua');
+        $jqgrid_langs = array(
+            'bg', 'bg1251', 'cat','cn','cs','da','de','el','en','es','fa','fi','fr','gl','he','hu','is','it','ja','nl','no','pl','pt-br','pt','ro','ru','sk','sr','sv','tr','ua'
+        );
 
         if (in_array($platform_isocode, $jqgrid_langs)) {
             $languaje = $platform_isocode;
@@ -6052,11 +6054,23 @@ function api_get_jquery_libraries_js($libraries) {
         $platform_isocode = strtolower(api_get_language_isocode());
 
         // languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
-        $datapicker_langs = array('af', 'ar', 'ar-DZ', 'az', 'bg', 'bs', 'ca', 'cs', 'cy-GB', 'da', 'de', 'el', 'en-AU', 'en-GB', 'en-NZ', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr', 'fr-CH', 'gl', 'he', 'hi', 'hr', 'hu', 'hy', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'ko', 'lb', 'lt', 'lv', 'mk', 'ml', 'ms', 'nl', 'nl-BE', 'no', 'pl', 'pt', 'pt-BR', 'rm', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sr-SR', 'sv', 'ta', 'th', 'tj', 'tr', 'uk', 'vi', 'zh-CN', 'zh-HK', 'zh-TW');
+        $datapicker_langs = array(
+            'af', 'ar', 'ar-DZ', 'az', 'bg', 'bs', 'ca', 'cs', 'cy-GB', 'da', 'de', 'el', 'en-AU', 'en-GB', 'en-NZ', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr', 'fr-CH', 'gl', 'he', 'hi', 'hr', 'hu', 'hy', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'ko', 'lb', 'lt', 'lv', 'mk', 'ml', 'ms', 'nl', 'nl-BE', 'no', 'pl', 'pt', 'pt-BR', 'rm', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sr-SR', 'sv', 'ta', 'th', 'tj', 'tr', 'uk', 'vi', 'zh-CN', 'zh-HK', 'zh-TW'
+        );
         if (in_array($platform_isocode, $datapicker_langs)) {
             $languaje = $platform_isocode;
         }
-        $js .= api_get_js('jquery-ui/ui/i18n/jquery.ui.datepicker-'.$languaje.'.js');
+
+        $script = '<script>
+        $(function(){
+            $.datepicker.setDefaults($.datepicker.regional["'.$languaje.'"]);
+            $.datepicker.regional["local"] = $.datepicker.regional["'.$languaje.'"];
+        });
+        </script>
+        ';
+        $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
+        $js .= $script; //api_get_js('jquery-ui/ui/i18n/jquery.ui.datepicker-'.$languaje.'.js');
+
     }
     return $js;
 }
@@ -7055,3 +7069,9 @@ function api_get_protocol()
 function convert_double_quote_to_single($in_text) {
     return api_preg_replace('/"/', "''", $in_text);
 }
+
+
+function api_is_unoconv_installed()
+{
+    return false;
+}

+ 7 - 1
main/inc/lib/message.lib.php

@@ -313,7 +313,13 @@ class MessageManager
             $sender_info = api_get_user_info($user_sender_id);
 
             if (empty($group_id)) {
-                $notification->save_notification(Notification::NOTIFICATION_TYPE_MESSAGE, array($receiver_user_id), $subject, $content, $sender_info);
+                $notification->save_notification(
+                    Notification::NOTIFICATION_TYPE_MESSAGE,
+                    array($receiver_user_id),
+                    $subject,
+                    $content,
+                    $sender_info
+                );
             } else {
                 $group_info = GroupPortalManager::get_group_data($group_id);
                 $group_info['topic_id'] = $topic_id;

+ 2 - 2
main/inc/lib/pdf.lib.php

@@ -291,7 +291,7 @@ class PDF
         $clean_search = array (
             '@<script[^>]*?>.*?</script>@si',
             '@<style[^>]*?>.*?</style>@siU'
-            );
+        );
 
         // Formatting the pdf
        	$course_data = api_get_course_info($course_code);
@@ -355,7 +355,7 @@ class PDF
         if (!empty($css)) {
             $this->pdf->WriteHTML($css, 1);
         }
-        $this->pdf->WriteHTML($document_html,2);
+        $this->pdf->WriteHTML($document_html, 2);
 
         if (empty($pdf_name)) {
             $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';

+ 1 - 1
main/inc/lib/pear/HTML/Common.php

@@ -471,4 +471,4 @@ class HTML_Common
         return $charset;
     } // end func charset
 } // end class HTML_Common
-?>
+?>

+ 11 - 3
main/inc/lib/pear/HTML/QuickForm.php

@@ -668,13 +668,20 @@ class HTML_QuickForm extends HTML_Common
 
         // Add the element if it is not an incompatible duplicate
         if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
-            if ($this->_elements[$this->_elementIndex[$elementName]]->getType() ==
-                $elementObject->getType()) {
+            if ($this->_elements[$this->_elementIndex[$elementName]]->getType() == $elementObject->getType()
+            ) {
                 $this->_elements[] =& $elementObject;
                 $elKeys = array_keys($this->_elements);
                 $this->_duplicateIndex[$elementName][] = end($elKeys);
             } else {
-                $error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::addElement()", 'HTML_QuickForm_Error', true);
+                $error = PEAR::raiseError(
+                    null,
+                    QUICKFORM_INVALID_ELEMENT_NAME,
+                    null,
+                    E_USER_WARNING,
+                    "Element '$elementName' already exists in HTML_QuickForm::addElement()", 'HTML_QuickForm_Error',
+                    true
+                );
                 return $error;
             }
         } else {
@@ -682,6 +689,7 @@ class HTML_QuickForm extends HTML_Common
             $elKeys = array_keys($this->_elements);
             $this->_elementIndex[$elementName] = end($elKeys);
         }
+
         if ($this->_freezeAll) {
             $elementObject->freeze();
         }

+ 88 - 96
main/inc/lib/pear/HTML/QuickForm/date.php

@@ -1,33 +1,33 @@
 <?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
 
-/**
- * Class for a group of elements used to input dates (and times).
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category    HTML
- * @package     HTML_QuickForm
- * @author      Alexey Borzov <avb@php.net>
- * @copyright   2001-2009 The PHP Group
- * @license     http://www.php.net/license/3_01.txt PHP License 3.01
- * @version     CVS: $Id: date.php,v 1.62 2009/04/04 21:34:02 avb Exp $
- * @link        http://pear.php.net/package/HTML_QuickForm
- */
-
-/**
- * Class for a group of form elements
- */
+/**
+ * Class for a group of elements used to input dates (and times).
+ *
+ * PHP versions 4 and 5
+ *
+ * LICENSE: This source file is subject to version 3.01 of the PHP license
+ * that is available through the world-wide-web at the following URI:
+ * http://www.php.net/license/3_01.txt If you did not receive a copy of
+ * the PHP License and are unable to obtain it through the web, please
+ * send a note to license@php.net so we can mail you a copy immediately.
+ *
+ * @category    HTML
+ * @package     HTML_QuickForm
+ * @author      Alexey Borzov <avb@php.net>
+ * @copyright   2001-2009 The PHP Group
+ * @license     http://www.php.net/license/3_01.txt PHP License 3.01
+ * @version     CVS: $Id: date.php,v 1.62 2009/04/04 21:34:02 avb Exp $
+ * @link        http://pear.php.net/package/HTML_QuickForm
+ */
+
+/**
+ * Class for a group of form elements
+ */
 require_once 'HTML/QuickForm/group.php';
-/**
- * Class for <select></select> elements
- */
+/**
+ * Class for <select></select> elements
+ */
 require_once 'HTML/QuickForm/select.php';
 
 /**
@@ -36,11 +36,11 @@ require_once 'HTML/QuickForm/select.php';
  * Inspired by original 'date' element but reimplemented as a subclass
  * of HTML_QuickForm_group
  *
- * @category    HTML
- * @package     HTML_QuickForm
- * @author      Alexey Borzov <avb@php.net>
- * @version     Release: 3.2.11
- * @since       3.1
+ * @category    HTML
+ * @package     HTML_QuickForm
+ * @author      Alexey Borzov <avb@php.net>
+ * @version     Release: 3.2.11
+ * @since       3.1
  */
 class HTML_QuickForm_date extends HTML_QuickForm_group
 {
@@ -80,19 +80,19 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
     * @var      array
     */
     var $_locale = array(
-        'en'    => array (
+        'en' => array (
             'weekdays_short'=> array ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'),
             'weekdays_long' => array ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
             'months_short'  => array ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
             'months_long'   => array ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
         ),
-        'de'    => array (
+        'de' => array (
             'weekdays_short'=> array ('So', 'Mon', 'Di', 'Mi', 'Do', 'Fr', 'Sa'),
             'weekdays_long' => array ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'),
             'months_short'  => array ('Jan', 'Feb', 'M&#xe4;rz', 'April', 'Mai', 'Juni', 'Juli', 'Aug', 'Sept', 'Okt', 'Nov', 'Dez'),
             'months_long'   => array ('Januar', 'Februar', 'M&#xe4;rz', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')
         ),
-        'fr'    => array (
+        'fr' => array (
             'weekdays_short'=> array ('Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'),
             'weekdays_long' => array ('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'),
             'months_short'  => array ('Jan', 'F&#xe9;v', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Ao&#xfb;t', 'Sep', 'Oct', 'Nov', 'D&#xe9;c'),
@@ -244,34 +244,34 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
    /**
     * Class constructor
     *
-    * The following keys may appear in $options array:
-    * - 'language': date language
-    * - 'format': Format of the date, based on PHP's date() function.
-    *   The following characters are currently recognised in format string:
-    *   <pre>
-    *       D => Short names of days
-    *       l => Long names of days
-    *       d => Day numbers
-    *       M => Short names of months
-    *       F => Long names of months
-    *       m => Month numbers
-    *       Y => Four digit year
-    *       y => Two digit year
-    *       h => 12 hour format
-    *       H => 23 hour  format
-    *       i => Minutes
-    *       s => Seconds
-    *       a => am/pm
-    *       A => AM/PM
-    *   </pre>
-    * - 'minYear': Minimum year in year select
-    * - 'maxYear': Maximum year in year select
-    * - 'addEmptyOption': Should an empty option be added to the top of
-    *    each select box?
-    * - 'emptyOptionValue': The value passed by the empty option.
-    * - 'emptyOptionText': The text displayed for the empty option.
-    * - 'optionIncrement': Step to increase the option values by (works for 'i' and 's')
-    *
+    * The following keys may appear in $options array:
+    * - 'language': date language
+    * - 'format': Format of the date, based on PHP's date() function.
+    *   The following characters are currently recognised in format string:
+    *   <pre>
+    *       D => Short names of days
+    *       l => Long names of days
+    *       d => Day numbers
+    *       M => Short names of months
+    *       F => Long names of months
+    *       m => Month numbers
+    *       Y => Four digit year
+    *       y => Two digit year
+    *       h => 12 hour format
+    *       H => 23 hour  format
+    *       i => Minutes
+    *       s => Seconds
+    *       a => am/pm
+    *       A => AM/PM
+    *   </pre>
+    * - 'minYear': Minimum year in year select
+    * - 'maxYear': Maximum year in year select
+    * - 'addEmptyOption': Should an empty option be added to the top of
+    *    each select box?
+    * - 'emptyOptionValue': The value passed by the empty option.
+    * - 'emptyOptionText': The text displayed for the empty option.
+    * - 'optionIncrement': Step to increase the option values by (works for 'i' and 's')
+    *
     * @access   public
     * @param    string  Element's name
     * @param    mixed   Label(s) for an element
@@ -305,9 +305,6 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
         }
     }
 
-    // }}}
-    // {{{ _createElements()
-
     function _createElements()
     {
         $this->_separator = $this->_elements = array();
@@ -315,8 +312,6 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
         $locale    =& $this->_locale[$this->_options['language']];
         $backslash =  false;
         // Modified by Ivan Tcholakov, 16-MAR-2010.
-        //for ($i = 0, $length = strlen($this->_options['format']); $i < $length; $i++) {
-        //    $sign = $this->_options['format']{$i};
         for ($i = 0, $length = api_strlen($this->_options['format']); $i < $length; $i++) {
             $sign = api_substr($this->_options['format'], $i, 1);
         //
@@ -444,24 +439,24 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
     }
 
     // }}}
-    // {{{ _trimLeadingZeros()
-
-   /**
-    * Trims leading zeros from the (numeric) string
-    *
-    * @param    string  A numeric string, possibly with leading zeros
-    * @return   string  String with leading zeros removed
-    */
-    function _trimLeadingZeros($str)
-    {
-        if (0 == strcmp($str, $this->_options['emptyOptionValue'])) {
-            return $str;
-        }
-        $trimmed = ltrim($str, '0');
-        return strlen($trimmed)? $trimmed: '0';
-    }
-
-    // }}}
+    // {{{ _trimLeadingZeros()
+
+   /**
+    * Trims leading zeros from the (numeric) string
+    *
+    * @param    string  A numeric string, possibly with leading zeros
+    * @return   string  String with leading zeros removed
+    */
+    function _trimLeadingZeros($str)
+    {
+        if (0 == strcmp($str, $this->_options['emptyOptionValue'])) {
+            return $str;
+        }
+        $trimmed = ltrim($str, '0');
+        return strlen($trimmed)? $trimmed: '0';
+    }
+
+    // }}}
     // {{{ setValue()
 
     function setValue($value)
@@ -473,7 +468,7 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
                 $value = strtotime($value);
             }
             // might be a unix epoch, then we fill all possible values
-            $arr = explode('-', date('w-j-n-Y-g-G-i-s-a-A-W', (int)$value));
+            $arr = explode('-', date('w-j-n-Y-g-G-i-s-a-A-W', (int)$value));
             $value = array(
                 'D' => $arr[0],
                 'l' => $arr[0],
@@ -486,14 +481,14 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
                 'h' => $arr[4],
                 'g' => $arr[4],
                 'H' => $arr[5],
-                'i' => $this->_trimLeadingZeros($arr[6]),
-                's' => $this->_trimLeadingZeros($arr[7]),
+                'i' => $this->_trimLeadingZeros($arr[6]),
+                's' => $this->_trimLeadingZeros($arr[7]),
                 'a' => $arr[8],
                 'A' => $arr[9],
-                'W' => $this->_trimLeadingZeros($arr[10])
+                'W' => $this->_trimLeadingZeros($arr[10])
             );
-        } else {
-            $value = array_map(array($this, '_trimLeadingZeros'), $value);
+        } else {
+            $value = array_map(array($this, '_trimLeadingZeros'), $value);
         }
         parent::setValue($value);
     }
@@ -503,7 +498,7 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
 
     function toHtml()
     {
-        include_once('HTML/QuickForm/Renderer/Default.php');
+        include_once 'HTML/QuickForm/Renderer/Default.php';
         $renderer = new HTML_QuickForm_Renderer_Default();
         $renderer->setElementTemplate('{element}');
         parent::accept($renderer);
@@ -531,7 +526,4 @@ class HTML_QuickForm_date extends HTML_QuickForm_group
             return parent::onQuickFormEvent($event, $arg, $caller);
         }
     }
-
-    // }}}
 }
-?>

+ 4 - 4
main/inc/lib/pear/HTML/QuickForm/element.php

@@ -89,7 +89,7 @@ class HTML_QuickForm_element extends HTML_Common
      * @access    public
      * @return    void
      */
-    function HTML_QuickForm_element($elementName=null, $elementLabel=null, $attributes=null)
+    function HTML_QuickForm_element($elementName = null, $elementLabel = null, $attributes = null)
     {
         HTML_Common::HTML_Common($attributes);
         if (isset($elementName)) {
@@ -238,7 +238,7 @@ class HTML_QuickForm_element extends HTML_Common
         // Modified by Ivan Tcholakov, 16-MAR-2010.
         //return ('' != $value? htmlspecialchars($value): '&nbsp;') .
         //       $this->_getPersistantData();
-        
+
         $value =  ('' != $value ? @htmlspecialchars($value, ENT_COMPAT, HTML_Common::charset()): '&nbsp;') .
                $this->_getPersistantData();
         return '<span class="freeze">'.$value.'</span>';
@@ -378,7 +378,7 @@ class HTML_QuickForm_element extends HTML_Common
         switch ($event) {
             case 'createElement':
                 $className = get_class($this);
-                              
+
                 $this->$className($arg[0], $arg[1], $arg[2], $arg[3], $arg[4]);
                 break;
             case 'addElement':
@@ -498,4 +498,4 @@ class HTML_QuickForm_element extends HTML_Common
 
     // }}}
 } // end class HTML_QuickForm_element
-?>
+?>

+ 10 - 8
main/inc/lib/pear/Text/Diff.php

@@ -17,7 +17,8 @@
  * @package Text_Diff
  * @author  Geoffrey T. Dairiki <dairiki@dairiki.org>
  */
-class Text_Diff {
+class Text_Diff
+{
 
     /**
      * Array of changes.
@@ -380,10 +381,9 @@ class Text_Diff_Op_copy extends Text_Diff_Op {
 
     function &reverse()
     {
-        $reverse = &new Text_Diff_Op_copy($this->final, $this->orig);
+        $reverse = new Text_Diff_Op_copy($this->final, $this->orig);
         return $reverse;
     }
-
 }
 
 /**
@@ -392,7 +392,8 @@ class Text_Diff_Op_copy extends Text_Diff_Op {
  *
  * @access private
  */
-class Text_Diff_Op_delete extends Text_Diff_Op {
+class Text_Diff_Op_delete extends Text_Diff_Op
+{
 
     function Text_Diff_Op_delete($lines)
     {
@@ -402,7 +403,7 @@ class Text_Diff_Op_delete extends Text_Diff_Op {
 
     function &reverse()
     {
-        $reverse = &new Text_Diff_Op_add($this->orig);
+        $reverse = new Text_Diff_Op_add($this->orig);
         return $reverse;
     }
 
@@ -424,7 +425,7 @@ class Text_Diff_Op_add extends Text_Diff_Op {
 
     function &reverse()
     {
-        $reverse = &new Text_Diff_Op_delete($this->final);
+        $reverse = new Text_Diff_Op_delete($this->final);
         return $reverse;
     }
 
@@ -436,7 +437,8 @@ class Text_Diff_Op_add extends Text_Diff_Op {
  *
  * @access private
  */
-class Text_Diff_Op_change extends Text_Diff_Op {
+class Text_Diff_Op_change extends Text_Diff_Op
+{
 
     function Text_Diff_Op_change($orig, $final)
     {
@@ -446,7 +448,7 @@ class Text_Diff_Op_change extends Text_Diff_Op {
 
     function &reverse()
     {
-        $reverse = &new Text_Diff_Op_change($this->final, $this->orig);
+        $reverse = new Text_Diff_Op_change($this->final, $this->orig);
         return $reverse;
     }
 

+ 70 - 67
main/inc/lib/sessionmanager.lib.php

@@ -3451,6 +3451,7 @@ class SessionManager
      * @param string $lastConnectionDate
      * @param array $sessionIdList
      * @param array $studentIdList
+     * @param int $filterByStatus
      * @return array|int
      */
     public static function getAllUsersFromCoursesFromAllSessionFromStatus(
@@ -3465,8 +3466,11 @@ class SessionManager
         $active = null,
         $lastConnectionDate = null,
         $sessionIdList = array(),
-        $studentIdList = array()
+        $studentIdList = array(),
+        $filterByStatus = null
     ) {
+        $filterByStatus = intval($filterByStatus);
+
         $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
         $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
@@ -3477,7 +3481,6 @@ class SessionManager
         $userId = intval($userId);
 
         $limitCondition = null;
-
         if (isset($from) && isset($numberItems)) {
             $from = intval($from);
             $numberItems = intval($numberItems);
@@ -3496,27 +3499,35 @@ class SessionManager
         switch ($status) {
             case 'drh':
                 // Classic DRH
-                if (empty($sessionIdList)) {
-                    $studentListSql = UserManager::get_users_followed_by_drh($userId, STUDENT, true, true);
-                    $studentListSql = array_keys($studentListSql);
+                if (empty($studentIdList)) {
+                    $studentListSql = UserManager::get_users_followed_by_drh($userId, $filterByStatus, true, false);
+                    $studentIdList = array_keys($studentListSql);
+                    $studentListSql = "'".implode("','", $studentIdList)."'";
                 } else {
-                    $studentListSql = $studentIdList;
+                    $studentIdList = array_map('intval', $studentIdList);
+                    $studentListSql = "'".implode("','", $studentIdList)."'";
                 }
                 if (!empty($studentListSql)) {
-                    $studentListSql = array_map('intval', $studentListSql);
                     $statusConditions = " AND u.user_id IN (".$studentListSql.") ";
                 }
                 break;
             case 'drh_all':
                 // Show all by DRH
                 if (empty($sessionIdList)) {
-                    $sessionsListSql = SessionManager::get_sessions_followed_by_drh($userId, null, null, false, true, true);
-                    $sessionsListSql = array_keys($sessionsListSql);
+                    $sessionsListSql = SessionManager::get_sessions_followed_by_drh(
+                        $userId,
+                        null,
+                        null,
+                        false,
+                        true,
+                        true
+                    );
                 } else {
-                    $sessionsListSql = $sessionIdList;
+                    $sessionIdList = array_map('intval', $sessionIdList);
+                    $sessionsListSql = "'".implode("','", $sessionIdList)."'";
                 }
+
                 if (!empty($sessionsListSql)) {
-                    $sessionsListSql = array_map('intval', $sessionsListSql);
                     $statusConditions = " AND s.id IN (".$sessionsListSql.") ";
                 }
                 break;
@@ -3552,6 +3563,10 @@ class SessionManager
                       $activeCondition
                     ";
 
+        if (!empty($filterByStatus)) {
+            $where .= " AND u.status = ".$filterByStatus;
+        }
+
         if (!empty($lastConnectionDate)) {
             $lastConnectionDate = Database::escape_string($lastConnectionDate);
             $where .=  " AND l.login_date <= '$lastConnectionDate' ";
@@ -3562,12 +3577,12 @@ class SessionManager
         if (!empty($keyword)) {
             $keyword = Database::escape_string($keyword);
             $sql .= " AND (
-                        u.username LIKE '%$keyword%' OR
-                        u.firstname LIKE '%$keyword%' OR
-                        u.lastname LIKE '%$keyword%' OR
-                        u.official_code LIKE '%$keyword%' OR
-                        u.email LIKE '%$keyword%'
-                    )";
+                u.username LIKE '%$keyword%' OR
+                u.firstname LIKE '%$keyword%' OR
+                u.lastname LIKE '%$keyword%' OR
+                u.official_code LIKE '%$keyword%' OR
+                u.email LIKE '%$keyword%'
+            )";
         }
 
         if ($getCount) {
@@ -3580,11 +3595,15 @@ class SessionManager
             return $count;
         }
 
-        $sql .= "ORDER BY $column $direction
-                $limitCondition";
+        if (!empty($column) && !empty($direction)) {
+            $sql .= " ORDER BY $column $direction ";
+        }
+
+        $sql .= $limitCondition;
 
         $result = Database::query($sql);
         $result = Database::store_result($result);
+
         return $result ;
     }
 
@@ -3745,21 +3764,17 @@ class SessionManager
         $active = null,
         $lastConnectionDate = null,
         $sessionIdList = array(),
-        $studentIdList = array()
+        $studentIdList = array(),
+        $userStatus = null
     ) {
-        if (!isset($keyword)) {
-            $keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
-        }
-
-        if (!isset($active)) {
-            $active = isset($_GET['active']) ? $_GET['active'] : null;
-        }
+        $userId = api_get_user_id();
 
         if (api_is_drh()) {
             if (api_drh_can_access_all_session_content()) {
+
                 $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
                     'drh_all',
-                    api_get_user_id(),
+                    $userId,
                     true,
                     null,
                     null,
@@ -3769,56 +3784,43 @@ class SessionManager
                     $active,
                     $lastConnectionDate,
                     $sessionIdList,
-                    $studentIdList
+                    $studentIdList,
+                    $userStatus
                 );
             } else {
-                $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
-                    'drh',
-                    api_get_user_id(),
-                    true,
-                    null,
-                    null,
-                    null,
-                    null,
-                    $keyword,
-                    $active,
-                    $lastConnectionDate,
-                    $sessionIdList,
-                    $studentIdList
-                );
-            }
-        } else {
-            if (api_is_platform_admin()) {
-                $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
-                    'admin',
-                    api_get_user_id(),
-                    true,
-                    null,
-                    null,
-                    null,
+
+                $count = UserManager::get_users_followed_by_drh(
+                    $userId,
                     null,
-                    $keyword,
-                    $active,
-                    $lastConnectionDate,
-                    $sessionIdList,
-                    $studentIdList
-                );
-            } else {
-                $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
-                    'teacher',
-                    api_get_user_id(),
+                    false,
+                    false,
                     true,
                     null,
                     null,
                     null,
                     null,
-                    $keyword,
                     $active,
                     $lastConnectionDate,
-                    $sessionIdList,
-                    $studentIdList
+                    array(),
+                    array(),
+                    $userStatus
+
                 );
             }
+        } else {
+            $count = UserManager::get_users_followed_by_drh(
+                $userId,
+                $userStatus,
+                false,
+                false,
+                true,
+                null,
+                null,
+                null,
+                null,
+                $active,
+                $lastConnectionDate
+            );
         }
         return $count;
     }
@@ -3858,7 +3860,7 @@ class SessionManager
                 $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
                 $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
-                // select the courses
+                // Select the teachers.
                 $sql = "SELECT cu.user_id FROM $course c
                         INNER JOIN $sessionCourse src ON c.code = src.course_code
                         INNER JOIN $courseUser cu ON (cu.course_code = c.code)
@@ -3876,6 +3878,7 @@ class SessionManager
                 }
             }
         }
+
         if (!empty($teacherResult)) {
             $tableUser = Database::get_main_table(TABLE_MAIN_USER);
 

+ 30 - 18
main/inc/lib/system_announcements.lib.php

@@ -295,7 +295,7 @@ class SystemAnnouncementManager {
 	 * @param int    Whether to send an e-mail to all users (1) or not (0)
 	 * @return mixed  insert_id on success, false on failure
 	 */
-	public static function add_announcement($title, $content, $date_start, $date_end, $visible_teacher = 0, $visible_student = 0, $visible_guest = 0, $lang = null, $send_mail = 0, $add_to_calendar = false ) {
+	public static function add_announcement($title, $content, $date_start, $date_end, $visible_teacher = 0, $visible_student = 0, $visible_guest = 0, $lang = null, $send_mail = 0, $add_to_calendar = false, $sendEmailTest = false) {
 
 		$original_content = $content;
 		$a_dateS = explode(' ',$date_start);
@@ -318,7 +318,7 @@ class SystemAnnouncementManager {
 			Display :: display_normal_message(get_lang('InvalidEndDate'));
 			return false;
 		}
-		if( strlen(trim($title)) == 0) {
+		if (strlen(trim($title)) == 0) {
 			Display::display_normal_message(get_lang('InvalidTitle'));
 			return false;
 		}
@@ -344,9 +344,13 @@ class SystemAnnouncementManager {
 		$sql = "INSERT INTO ".$db_table." (title,content,date_start,date_end,visible_teacher,visible_student,visible_guest, lang, access_url_id)
 				VALUES ('".$title."','".$content."','".$start."','".$end."','".$visible_teacher."','".$visible_student."','".$visible_guest."',".$langsql.", ".$current_access_url_id.")";
 
-		if ($send_mail==1) {
-			SystemAnnouncementManager::send_system_announcement_by_email($title, $content,$visible_teacher, $visible_student, $lang);
-		}
+        if ($sendEmailTest) {
+            SystemAnnouncementManager::send_system_announcement_by_email($title, $content,$visible_teacher, $visible_student, $lang, true);
+        } else {
+            if ($send_mail == 1) {
+                SystemAnnouncementManager::send_system_announcement_by_email($title, $content,$visible_teacher, $visible_student, $lang);
+            }
+        }
 		$res = Database::query($sql);
 		if ($res === false) {
 			Debug::log_s(mysql_error());
@@ -410,7 +414,7 @@ class SystemAnnouncementManager {
 	 * @param array $date_end : end date of announcement (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
 	 * @return	bool	True on success, false on failure
 	 */
-	public static function update_announcement($id, $title, $content, $date_start, $date_end, $visible_teacher = 0, $visible_student = 0, $visible_guest = 0,$lang=null, $send_mail=0) {
+	public static function update_announcement($id, $title, $content, $date_start, $date_end, $visible_teacher = 0, $visible_student = 0, $visible_guest = 0,$lang=null, $send_mail=0, $sendEmailTest = false) {
 		$a_dateS = explode(' ',$date_start);
 		$a_arraySD = explode('-',$a_dateS[0]);
 		$a_arraySH = explode(':',$a_dateS[1]);
@@ -450,9 +454,13 @@ class SystemAnnouncementManager {
 		$sql = "UPDATE ".$db_table." SET lang=$langsql,title='".$title."',content='".$content."',date_start='".$start."',date_end='".$end."', ";
 		$sql .= " visible_teacher = '".$visible_teacher."', visible_student = '".$visible_student."', visible_guest = '".$visible_guest."' , access_url_id = '".api_get_current_access_url_id()."'  WHERE id = ".$id;
 
-		if ($send_mail==1) {
-			SystemAnnouncementManager::send_system_announcement_by_email($title, $content,$visible_teacher, $visible_student, $lang);
-		}
+        if ($sendEmailTest) {
+            SystemAnnouncementManager::send_system_announcement_by_email($title, $content, null, null, $lang, $sendEmailTest);
+        } else {
+            if ($send_mail==1) {
+                SystemAnnouncementManager::send_system_announcement_by_email($title, $content, $visible_teacher, $visible_student, $lang);
+            }
+        }
 		$res = Database::query($sql);
 		if ($res === false) {
 			Debug::log_s(mysql_error());
@@ -523,18 +531,25 @@ class SystemAnnouncementManager {
 	 * @param	string	Language (optional, considered for all languages if left empty)
      * @return  bool    True if the message was sent or there was no destination matching. False on database or e-mail sending error.
 	 */
-	public static function send_system_announcement_by_email($title, $content, $teacher, $student, $language = null) {
+	public static function send_system_announcement_by_email($title, $content, $teacher, $student, $language = null, $sendEmailTest = false) {
 		global $charset;
 
+        $title = api_html_entity_decode(stripslashes($title), ENT_QUOTES, $charset);
+        $content = api_html_entity_decode(stripslashes(str_replace(array('\r\n', '\n', '\r'),'', $content)), ENT_QUOTES, $charset);
+
+        if ($sendEmailTest) {
+            MessageManager::send_message_simple(api_get_user_id(), $title, $content);
+            return true;
+        }
+
+        $user_table = Database :: get_main_table(TABLE_MAIN_USER);
         if (api_is_multiple_url_enabled()) {
             $current_access_url_id = api_get_current_access_url_id();
             $url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
             $url_condition = " INNER JOIN $url_rel_user uu ON uu.user_id = u.user_id ";
         }
 
-		$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-
-		if ($teacher <> 0 AND $student == 0) {
+        if ($teacher <> 0 AND $student == 0) {
 			$sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition WHERE status = '1' ";
 		}
 
@@ -554,7 +569,7 @@ class SystemAnnouncementManager {
             $sql .= " AND access_url_id = '".$current_access_url_id."' ";
         }
 
-        //Sent to active users
+        // Sent to active users.
         $sql .= " AND email <>'' AND active = 1 ";
 
 		if ((empty($teacher) or $teacher == '0') AND  (empty($student) or $student == '0')) {
@@ -566,9 +581,6 @@ class SystemAnnouncementManager {
 			return false;
 		}
 
-        $title      = api_html_entity_decode(stripslashes($title), ENT_QUOTES, $charset);
-        $content    = api_html_entity_decode(stripslashes(str_replace(array('\r\n', '\n', '\r'),'', $content)), ENT_QUOTES, $charset);
-
         $message_sent = false;
 
 		while ($row = Database::fetch_array($result,'ASSOC')) {
@@ -636,4 +648,4 @@ class SystemAnnouncementManager {
 		}
 		return $html;
 	}
-}
+}

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

@@ -444,9 +444,9 @@ class Template
             $css[] = api_get_path(WEB_CSS_PATH).$this->theme.'/scorm.css';
         }
 
-        // if we have a scorm file in theme dont use default_scorm.css file
-        if (!is_file(api_get_path(SYS_CSS_PATH) . $this->theme . '/scorm.css')) {
-            $css[] = api_get_cdn_path(api_get_path(WEB_CSS_PATH).'/default_scorm.css');
+        // if we have a scorm file in theme don't use default_scorm.css file
+        if (!is_file(api_get_path(SYS_CSS_PATH).$this->theme.'/scorm.css')) {
+            $css[] = api_get_cdn_path(api_get_path(WEB_CSS_PATH).'default_scorm.css');
         }
 
         if (api_is_global_chat_enabled()) {

+ 74 - 0
main/inc/lib/tracking.lib.php

@@ -22,6 +22,80 @@ require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
  */
 class Tracking
 {
+    /**
+     * @param int $userId
+     *
+     * @return array
+     */
+    public static function getStats($userId)
+    {
+        if (api_is_drh() && api_drh_can_access_all_session_content()) {
+            $studentList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'drh_all',
+                $userId,
+                false,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                array(),
+                array(),
+                STUDENT
+            );
+            $students = array();
+            foreach ($studentList as $studentData) {
+                $students[] = $studentData['user_id'];
+            }
+
+            $teacherList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'drh_all',
+                $userId,
+                false,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                array(),
+                array(),
+                COURSEMANAGER
+            );
+            $teachers = array();
+            foreach ($teacherList as $teacherData) {
+                $teachers[] = $teacherData['user_id'];
+            }
+
+            $platformCourses = SessionManager::getAllCoursesFromAllSessionFromDrh($userId);
+            $courses = array();
+            foreach ($platformCourses as $course) {
+                $courses[$course] = $course;
+            }
+            $sessions = SessionManager::get_sessions_followed_by_drh($userId);
+        } else {
+            $students = array_keys(UserManager::get_users_followed_by_drh($userId, STUDENT));
+            $teachers = array_keys(UserManager::get_users_followed_by_drh($userId, COURSEMANAGER));
+
+            $platformCourses = CourseManager::get_courses_followed_by_drh($userId);
+            foreach ($platformCourses as $course) {
+                $courses[$course['code']] = $course['code'];
+            }
+
+            $sessions = SessionManager::get_sessions_followed_by_drh($userId);
+        }
+
+        return array(
+            'teachers' => $teachers,
+            'students' => $students,
+            'courses' => $courses,
+            'sessions' => $sessions
+        );
+    }
+
     /**
      * Calculates the time spent on the platform by a user
      * @param   int|array User id

+ 33 - 5
main/inc/lib/usergroup.lib.php

@@ -53,6 +53,7 @@ class UserGroup extends Model
     public function getTotalCount()
     {
         $row = Database::select('count(*) as count', $this->table, array(), 'first');
+
         return $row['count'];
     }
 
@@ -64,14 +65,17 @@ class UserGroup extends Model
         if ($this->useMultipleUrl) {
             $urlId = api_get_current_access_url_id();
             $sql = "SELECT count(u.id) as count FROM ".$this->table." u
-                    INNER JOIN ".$this->access_url_rel_usergroup." a ON (u.id = a.usergroup_id)
+                    INNER JOIN ".$this->access_url_rel_usergroup." a
+                        ON (u.id = a.usergroup_id)
                     WHERE access_url_id = $urlId
             ";
             $result = Database::query($sql);
             if (Database::num_rows($result)) {
                 $row  = Database::fetch_array($result);
+
                 return $row['count'];
             }
+
             return 0;
         } else {
             return $this->getTotalCount();
@@ -97,6 +101,7 @@ class UserGroup extends Model
                 $row  = Database::fetch_array($result);
                 return $row['count'];
             }
+
             return 0;
 
         } else {
@@ -106,6 +111,7 @@ class UserGroup extends Model
                 array('where' => array('course_id = ?' => $course_id)),
                 'first'
             );
+
             return $row['count'];
         }
     }
@@ -118,6 +124,7 @@ class UserGroup extends Model
     public function get_id_by_name($name)
     {
         $row = Database::select('id', $this->table, array('where' => array('name = ?' => $name)), 'first');
+
         return $row['id'];
     }
 
@@ -146,8 +153,8 @@ class UserGroup extends Model
 
     /**
      * Gets a list of course ids by user group
-     * @param   int user group id
-     * @param array $conditionsLike
+     * @param int user group id
+     * @param array $loadCourseData
      * @return  array
      */
     public function get_courses_by_usergroup($id, $loadCourseData = false)
@@ -204,11 +211,13 @@ class UserGroup extends Model
                 }
             }
         }
+
         return $array;
     }
 
     /**
      * @param array $options
+     *
      * @return array
      */
     public function get_usergroup_in_course($options = array())
@@ -235,13 +244,24 @@ class UserGroup extends Model
             $urlId = api_get_current_access_url_id();
             $sql .= " AND access_url_id = $urlId ";
         }
+
+        if (isset($options['LIMIT'])) {
+            $limits = explode(',', $options['LIMIT']);
+            $limits = array_map('intval', $limits);
+            if (isset($limits[0]) && isset($limits[1])) {
+                $sql .= " LIMIT ".$limits[0].', '.$limits[1];
+            }
+        }
+
         $result = Database::query($sql);
         $array = Database::store_result($result, 'ASSOC');
+
         return $array;
     }
 
     /**
      * @param array $options
+     *
      * @return array|bool
      */
     public function get_usergroup_not_in_course($options = array())
@@ -251,13 +271,13 @@ class UserGroup extends Model
             $course_id = intval($options['course_id']);
             unset($options['course_id']);
         }
+
         if (empty($course_id)) {
             return false;
         }
-        if ($this->useMultipleUrl) {
 
+        if ($this->useMultipleUrl) {
             $urlId = api_get_current_access_url_id();
-
             $sql = "SELECT DISTINCT u.id, name
                     FROM {$this->table} u
                     INNER JOIN {$this->access_url_rel_usergroup} a
@@ -281,8 +301,16 @@ class UserGroup extends Model
             $sql .= " AND access_url_id = $urlId";
         }
 
+        if (isset($options['LIMIT'])) {
+            $limits = explode(',', $options['LIMIT']);
+            $limits = array_map('intval', $limits);
+            if (isset($limits[0]) && isset($limits[1])) {
+                $sql .= " LIMIT ".$limits[0].', '.$limits[1];
+            }
+        }
         $result = Database::query($sql);
         $array = Database::store_result($result, 'ASSOC');
+
         return $array;
     }
 

+ 68 - 15
main/inc/lib/usermanager.lib.php

@@ -3136,15 +3136,14 @@ class UserManager
         $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
         $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
         $tags = UserManager::get_user_tags($user_id, $field_id);
-        //echo '<pre>';var_dump($tags);
         if (is_array($tags) && count($tags) > 0) {
             foreach ($tags as $key => $tag) {
                 if ($tag['count'] > '0') {
                     $sql = "UPDATE $table_user_tag SET count = count - 1  WHERE id = $key ";
-                    $result = Database::query($sql);
+                    Database::query($sql);
                 }
                 $sql = "DELETE FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $key";
-                $result = Database::query($sql);
+                Database::query($sql);
             }
         }
     }
@@ -3462,14 +3461,25 @@ class UserManager
 
     /**
      * get users followed by human resource manager
-     * @param int          hr_dept id
-     * @param int        user status (optional)
+     * @param int hr_dept id
+     * @param int  user status (optional)
      * @param bool $getOnlyUserId
      * @param bool $getSql
      * @return array     users
      */
-    public static function get_users_followed_by_drh($hr_dept_id, $user_status = 0, $getOnlyUserId = false, $getSql = false)
-    {
+    public static function get_users_followed_by_drh(
+        $hr_dept_id,
+        $user_status = 0,
+        $getOnlyUserId = false,
+        $getSql = false,
+        $getCount = false,
+        $from = null,
+        $numberItems = null,
+        $column = null,
+        $direction = null,
+        $active = null,
+        $lastConnectionDate = null
+    ) {
         // Database Table Definitions
         $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
         $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
@@ -3477,6 +3487,16 @@ class UserManager
 
         $hr_dept_id = intval($hr_dept_id);
 
+        $limitCondition = null;
+        if (isset($from) && isset($numberItems)) {
+            $from = intval($from);
+            $numberItems = intval($numberItems);
+            $limitCondition = "LIMIT $from, $numberItems";
+        }
+
+        $column = Database::escape_string($column);
+        $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : null;
+
         $condition_status = '';
         if (!empty($user_status)) {
             $condition_status = ' AND u.status = '.$user_status;
@@ -3485,9 +3505,20 @@ class UserManager
         if ($getOnlyUserId) {
             $select = " SELECT u.user_id";
         }
+        if ($getCount) {
+            $select = " SELECT COUNT(DISTINCT(u.user_id)) as count ";
+        }
+
+        $join = null;
+        if (!empty($lastConnectionDate)) {
+            $loginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+            $join .= " INNER JOIN $loginTable l ON (l.login_user_id = u.user_id) ";
+        }
+
         $sql = " $select FROM $tbl_user u
                 INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.user_id)
                 LEFT JOIN $tbl_user_rel_access_url a ON (a.user_id = u.user_id)
+                $join
                 WHERE
                     friend_user_id = '$hr_dept_id' AND
                     relation_type = '".USER_RELATION_TYPE_RRHH."'
@@ -3495,24 +3526,46 @@ class UserManager
                     access_url_id = ".api_get_current_access_url_id()."
                 ";
 
+        if (!is_null($active)) {
+            $active = intval($active);
+            $sql.= " AND active = $active";
+        }
+
+        if (!empty($lastConnectionDate)) {
+            $lastConnectionDate = Database::escape_string($lastConnectionDate);
+            $sql .=  " AND l.login_date <= '$lastConnectionDate' ";
+        }
+
         if ($getSql) {
             return $sql;
         }
 
+        if ($getCount) {
+            $result = Database::query($sql);
+            $row = Database::fetch_array($result);
+            return $row['count'];
+        }
+
+        $orderBy = null;
         if (api_is_western_name_order()) {
-            $sql .= " ORDER BY u.firstname, u.lastname ";
+            $orderBy .= " ORDER BY u.firstname, u.lastname ";
         } else {
-            $sql .= " ORDER BY u.lastname, u.firstname ";
+            $orderBy .= " ORDER BY u.lastname, u.firstname ";
         }
 
-        $rs_assigned_users = Database::query($sql);
-        $assigned_users_to_hrm = array();
-        if (Database::num_rows($rs_assigned_users) > 0) {
-            while ($row_assigned_users = Database::fetch_array($rs_assigned_users)) {
-                $assigned_users_to_hrm[$row_assigned_users['user_id']] = $row_assigned_users;
+        if (!empty($column) && !empty($direction)) {
+            $orderBy = " ORDER BY $column $direction ";
+        }
+        $sql .= $orderBy;
+        $sql .= $limitCondition;
+        $result = Database::query($sql);
+        $users = array();
+        if (Database::num_rows($result) > 0) {
+            while ($row = Database::fetch_array($result)) {
+                $users[$row['user_id']] = $row;
             }
         }
-        return $assigned_users_to_hrm;
+        return $users;
     }
 
     /**

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

@@ -1100,7 +1100,7 @@ class IndexManager
                         }
                         $date_session_start = $session['date_start'];
                         $date_session_end = $session['date_end'];
-                        $days_access_before_beginning   = $session['nb_days_access_before_beginning'];
+                        $days_access_before_beginning = $session['nb_days_access_before_beginning'];
                         $days_access_after_end  = $session['nb_days_access_after_end'];
 
                         $session_now = time();

+ 4 - 0
main/lang/english/trad4all.inc.php

@@ -2,6 +2,10 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$SendOnlyAnEmailToMySelfToTest = "Send an email to myself for testing purposes.";
+$DeleteAllSelectedAttendances = "Delete all selected attendances";
+$AvailableClasses = "Available classes";
+$RegisteredClasses = "Registered classes";
 $DeleteItemsNotInFile = "Delete items not in file";
 $ImportGroups = "Import groups";
 $HereIsYourFeedback = "Here is your feedback";

+ 5 - 0
main/lang/spanish/exercice.inc.php

@@ -2,6 +2,11 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$SelectADateOnTheCalendar = "Seleccione una fecha del calendario";
+$AreYouSureDeleteTestResultBeforeDateD = "¿Está seguro que desea eliminar los resultados de este ejercicio antes de la fecha seleccionada?";
+$CleanStudentsResultsBeforeDate = "Eliminar todos los resultados antes de la fecha selecionada";
+$AreYouSureToEmptyAllTestResults = "¿Está seguro de eliminar todos los resultados de todos los ejercicios?";
+$CleanAllStudentsResultsForAllTests = "¿Está seguro de eliminar todos los resultados de los ejericios?";
 $TestFeedbackNotShown = "Esta prueba está configurada para no dar retro-alimentación a los alumnos. Los comentarios correspondientes no se mostrarán al fin de la prueba, pero podrían serle útil, como docente, en el momento de revisar los detalles de las preguntas.";
 $FeedbackDisplayOptions = "Manera en la cual se mostrará el comentario definido para cada pregunta. Esta opción define como un estudiante visualizará (o no) los comentarios (retro-alimentación) ingresados para cada alternativa en cada pregunta. Recomendamos evaluar las distintas opciones antes de invitar los estudiantes a tomar la prueba.";
 $ImportAikenQuizExplanationExample = "Este es el texto de la pregunta 1

File diff suppressed because it is too large
+ 2 - 0
main/lang/spanish/help.inc.php


+ 8 - 0
main/lang/spanish/trad4all.inc.php

@@ -2,6 +2,14 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$SendOnlyAnEmailToMySelfToTest = "Enviar correo electrónico solamente a mi mismo para pruebas.";
+$DeleteAllSelectedAttendances = "Eliminar todas las hojas de asistencia seleccionadas";
+$AvailableClasses = "Clases disponibles";
+$RegisteredClasses = "Clases subscritas";
+$DeleteItemsNotInFile = "Eliminar elementos que no se encuentran en el archivo";
+$ImportGroups = "Importar grupos";
+$HereIsYourFeedback = "Respuesta del profesor:";
+$ShowSystemFolders = "Mostrar directorios del sistema.";
 $LoginToGoToThisCourse = "Conectarse para entrar al curso";
 $LoginDate = "Fecha de ingreso";
 $ChooseStartDateAndEndDate = "Elija fechas de inicio y de fin";

+ 166 - 203
main/mySpace/index.php

@@ -32,8 +32,7 @@ $csv_content = array();
 $nameTools = get_lang('MySpace');
 
 $user_id = api_get_user_id();
-$is_coach = api_is_coach($_GET['session_id']); // This is used?
-
+$is_coach = api_is_coach($_GET['session_id']);
 $session_id = isset($_GET['session_id']) ? intval($_GET['session_id']) : 0;
 
 $is_platform_admin 	= api_is_platform_admin();
@@ -65,58 +64,9 @@ if (!$export_csv) {
 }
 
 // Database table definitions
-$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$tbl_sessions 				= Database :: get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-/* FUNCTIONS */
-function count_coaches()
-{
-    global $total_no_coaches;
-    return $total_no_coaches;
-}
-
-function sort_users($a, $b)
-{
-    return api_strcmp(
-        trim(api_strtolower($a[$_SESSION['tracking_column']])),
-        trim(api_strtolower($b[$_SESSION['tracking_column']]))
-    );
-}
-
-function rsort_users($a, $b)
-{
-    return api_strcmp(
-        trim(api_strtolower($b[$_SESSION['tracking_column']])),
-        trim(api_strtolower($a[$_SESSION['tracking_column']]))
-    );
-}
-
-function count_sessions_coached()
-{
-    global $count_sessions;
-    return $count_sessions;
-}
-
-function sort_sessions($a, $b)
-{
-    global $tracking_column;
-    if ($a[$tracking_column] > $b[$tracking_column]) {
-        return 1;
-    } else {
-        return -1;
-    }
-}
-
-function rsort_sessions($a, $b)
-{
-    global $tracking_column;
-    if ($b[$tracking_column] > $a[$tracking_column]) {
-        return 1;
-    } else {
-        return -1;
-    }
-}
+$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+$tbl_sessions = Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
 /* MAIN CODE  */
 
@@ -133,7 +83,6 @@ if (isset($_GET['view']) && in_array($_GET['view'], $views)) {
 }
 
 $menu_items = array();
-global $_configuration;
 
 if ($is_platform_admin) {
     if ($view == 'admin') {
@@ -205,46 +154,13 @@ if (empty($session_id) || in_array($display, array('accessoverview','lpprogresso
 
 echo '</div>';
 
+$userId  = api_get_user_id();
+$stats = Tracking::getStats($userId);
 
-// Getting courses followed by a coach (No session courses).
-$courses = CourseManager::get_course_list_as_coach($user_id, false);
-
-// Courses with no session:
-if (isset($courses[0])) {
-    $courses = $courses[0];
-}
-
-// If is drh
-if ($is_drh) {
-    if (api_drh_can_access_all_session_content()) {
-        $studentList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus('drh_all', api_get_user_id());
-
-        $students = array();
-        foreach ($studentList as $studentData) {
-            $students[] = $studentData['user_id'];
-        }
-        $courses_of_the_platform = SessionManager::getAllCoursesFromAllSessionFromDrh(api_get_user_id());
-
-        foreach ($courses_of_the_platform as $course) {
-            $courses[$course] = $course;
-        }
-        $sessions = SessionManager::get_sessions_followed_by_drh(api_get_user_id());
-
-    } else {
-        $students = array_keys(UserManager::get_users_followed_by_drh($user_id, STUDENT));
-        $courses_of_the_platform = CourseManager::get_courses_followed_by_drh($user_id);
-        foreach ($courses_of_the_platform as $course) {
-            $courses[$course['code']] = $course['code'];
-        }
-        $sessions = SessionManager::get_sessions_followed_by_drh($user_id);
-    }
-} else {
-    // Getting students from courses and courses in sessions (To show the total students that the user follows)
-    $students = CourseManager::get_user_list_from_courses_as_coach($user_id);
-
-    // Sessions for the coach
-    $sessions = Tracking::get_sessions_coached_by_user($user_id);
-}
+$students = $stats['teachers'];
+$teachers = $stats['students'];
+$courses = $stats['courses'];
+$sessions = $stats['sessions'];
 
 $sessionIdList = array();
 if (!empty($sessions)) {
@@ -259,144 +175,191 @@ $count_courses = count($courses);
 // Sessions for the user
 $count_sessions = count($sessions);
 
-// Students
-$nb_students = count($students);
-
 $total_time_spent = 0;
 $total_courses = 0;
 $avg_total_progress = 0;
 $avg_results_to_exercises = 0;
 $nb_inactive_students = 0;
 $nb_posts = $nb_assignments = 0;
-
 $inactiveTime = time() - (3600 * 24 * 7);
+$nb_students = 0;
+$numberTeachers = 0;
 
 $daysAgo = 7;
 if (!empty($students)) {
-
+    // Students
+    $nb_students = count($students);
     $studentIds = array_values($students);
-    $nb_students = count($studentIds);
-
-    // Inactive students
-    $inactiveUsers = Tracking::getInactiveUsers($studentIds, $daysAgo);
-    $totalTimeSpent = Tracking::get_time_spent_on_the_platform($studentIds);
-    $posts = Tracking::count_student_messages($studentIds);
-    $countAssignments = Tracking::count_student_assignments($studentIds);
-    $progress  = Tracking::get_avg_student_progress($studentIds);
-    $averageScore = Tracking::getAverageStudentScore($studentIds);
-
     // average progress
     $avg_total_progress = $progress / $nb_students;
-    // average results to the tests
-    $avg_results_to_exercises = $averageScore;
     // average assignments
     $nb_assignments = $countAssignments / $nb_students;
-    // average posts
-    $nb_posts = $posts ;
-
-    $avg_time_spent = $totalTimeSpent;
 
     $avg_courses_per_student = $count_courses / $nb_students;
+}
+
+if (!empty($teachers)) {
+    $numberTeachers = count($teachers);
+}
+
+
+// Inactive students
+//$countInactiveUsers = Tracking::getInactiveUsers($studentIds, $daysAgo);
+$totalTimeSpent = Tracking::get_time_spent_on_the_platform($studentIds);
+$posts = Tracking::count_student_messages($studentIds);
+$countAssignments = Tracking::count_student_assignments($studentIds);
+$progress  = Tracking::get_avg_student_progress($studentIds);
+$averageScore = Tracking::getAverageStudentScore($studentIds);
+$avg_results_to_exercises = $averageScore;
+
+// average posts
+$nb_posts = $posts;
+$avg_time_spent = $totalTimeSpent;
+
+$linkAddUser = null;
+$linkAddCourse = null;
+$linkAddSession = null;
+
+if (api_is_platform_admin()) {
+    $linkAddUser = ' '.Display::url(
+        Display::return_icon('add.png', get_lang('Add')),
+        api_get_path(WEB_CODE_PATH).'admin/dashboard_add_users_to_user.php?user='.api_get_user_id(),
+        array('class' => '')
+    );
+    $linkAddCourse = ' '.Display::url(
+        Display::return_icon('add.png', get_lang('Add')),
+        api_get_path(WEB_CODE_PATH).'admin/dashboard_add_courses_to_user.php?user='.api_get_user_id(),
+        array('class' => '')
+    );
+    $linkAddSession = ' '.Display::url(
+        Display::return_icon('add.png', get_lang('Add')),
+        api_get_path(WEB_CODE_PATH).'admin/dashboard_add_sessions_to_user.php?user='.api_get_user_id(),
+        array('class' => '')
+    );
+}
+
+echo Display::page_subheader(get_lang('Overview'));
+echo '<div class="report_section">
+        <table class="table table-bordered">
+            <tr>
+                <td>'.get_lang('FollowedStudents').'</td>
+                <td align="right">'.$nb_students.'</td>
+            </tr>
+            <tr>
+                <td>'.get_lang('FollowedTeachers').'</td>
+                <td align="right">'.$numberTeachers.'</td>
+            </tr>
+            <tr>
+                <td>'.get_lang('FollowedUsers').'</td>
+                <td align="right">'.($nb_students+$numberTeachers).$linkAddUser.'</td>
+            </tr>
+            <tr>
+                <td>'.get_lang('FollowedCourses').'</td>
+                <td align="right">'.$count_courses.$linkAddCourse.'</td>
+            </tr>
+            <tr>
+                <td>'.get_lang('FollowedSessions').'</td>
+                <td align="right">'.$count_sessions.$linkAddSession.'</td>
+            </tr>
+            </table>';
+echo '</div>';
+
+echo Display::page_subheader(get_lang('Students').' ('.$nb_students.')');
+
+if ($export_csv) {
+    //csv part
+    $csv_content[] = array(get_lang('Students'));
+    $csv_content[] = array(get_lang('InactivesStudents'), $nb_inactive_students);
+    $csv_content[] = array(get_lang('AverageTimeSpentOnThePlatform'), $avg_time_spent);
+    $csv_content[] = array(get_lang('AverageCoursePerStudent'), $avg_courses_per_student);
+    $csv_content[] = array(get_lang('AverageProgressInLearnpath'), is_null($avg_total_progress) ? null : round($avg_total_progress, 2).'%');
+    $csv_content[] = array(get_lang('AverageResultsToTheExercices'), is_null($avg_results_to_exercises) ? null : round($avg_results_to_exercises, 2).'%');
+    $csv_content[] = array(get_lang('AveragePostsInForum'), $nb_posts);
+    $csv_content[] = array(get_lang('AverageAssignments'), $nb_assignments);
+    $csv_content[] = array();
+} else {
+    $lastConnectionDate = api_get_utc_datetime(strtotime('15 days ago'));
+    $countActiveUsers = SessionManager::getCountUserTracking(null, 1, null, array(), array());
+
+    $countInactiveUsers = SessionManager::getCountUserTracking(null, 0, null, $sessionIdList, $studentIds);
+    $countSleepingTeachers = SessionManager::getTeacherTracking(
+        api_get_user_id(),
+        1,
+        $lastConnectionDate,
+        true,
+        $sessionIdList
+    );
+
+    $countSleepingStudents = SessionManager::getCountUserTracking(
+        null,
+        1,
+        $lastConnectionDate,
+        $sessionIdList,
+        $studentIds
+    );
 
-    echo Display::page_subheader(get_lang('Overview'));
+    $form = new FormValidator('search_user', 'get', api_get_path(WEB_CODE_PATH).'mySpace/student.php');
+    $form->addElement('text', 'keyword', get_lang('User'));
+    $form->addElement('button', 'submit', get_lang('Search'));
+    $form->display();
 
+    // html part
     echo '<div class="report_section">
             <table class="table table-bordered">
                 <tr>
-                    <td>'.get_lang('FollowedUsers').'</td>
-                    <td align="right">'.$nb_students.'</td>
+                    <td>'.Display::url(
+                        get_lang('ActiveUsers'),
+                        api_get_path(WEB_CODE_PATH).'mySpace/users.php?active=1').'</td>
+                    <td align="right">'.intval($countActiveUsers).'</td>
                 </tr>
                 <tr>
-                    <td>'.get_lang('FollowedCourses').'</td>
-                    <td align="right">'.$count_courses.'</td>
+                    <td>'.Display::url(get_lang('InactiveUsers'), api_get_path(WEB_CODE_PATH).'mySpace/users.php?active=0').'</td>
+                    <td align="right">'.$countInactiveUsers.'</td>
                 </tr>
                 <tr>
-                    <td>'.get_lang('FollowedSessions').'</td>
-                    <td align="right">'.$count_sessions.'</td>
+                    <td>'.Display::url(get_lang('SleepingTeachers'), api_get_path(WEB_CODE_PATH).'mySpace/teachers.php?sleeping_days=15').'</td>
+                    <td align="right">'.$countSleepingTeachers.'</td>
                 </tr>
-                </table>';
-    echo '</div>';
-
-    echo Display::page_subheader(get_lang('Students').' ('.$nb_students.')');
-
-    if ($export_csv) {
-        //csv part
-        $csv_content[] = array(get_lang('Students'));
-        $csv_content[] = array(get_lang('InactivesStudents'), $nb_inactive_students);
-        $csv_content[] = array(get_lang('AverageTimeSpentOnThePlatform'), $avg_time_spent);
-        $csv_content[] = array(get_lang('AverageCoursePerStudent'), $avg_courses_per_student);
-        $csv_content[] = array(get_lang('AverageProgressInLearnpath'), is_null($avg_total_progress) ? null : round($avg_total_progress, 2).'%');
-        $csv_content[] = array(get_lang('AverageResultsToTheExercices'), is_null($avg_results_to_exercises) ? null : round($avg_results_to_exercises, 2).'%');
-        $csv_content[] = array(get_lang('AveragePostsInForum'), $nb_posts);
-        $csv_content[] = array(get_lang('AverageAssignments'), $nb_assignments);
-        $csv_content[] = array();
-    } else {
-        $lastConnectionDate = api_get_utc_datetime(strtotime('15 days ago'));
-        $countActiveUsers = $nb_students; //SessionManager::getCountUserTracking(null, 1);
-        $countInactiveUsers = SessionManager::getCountUserTracking(null, 0, null, $sessionIdList, $studentIds);
-        $countSleepingTeachers = SessionManager::getTeacherTracking(api_get_user_id(), 1, $lastConnectionDate, true, $sessionIdList);
-        $countSleepingStudents = SessionManager::getCountUserTracking(null, 1, $lastConnectionDate, $sessionIdList, $studentIds);
-
-        $form = new FormValidator('search_user', 'get', api_get_path(WEB_CODE_PATH).'mySpace/student.php');
-        $form->addElement('text', 'keyword', get_lang('User'));
-        $form->addElement('button', 'submit', get_lang('Search'));
-        $form->display();
-
-        // html part
-        echo '<div class="report_section">
-                <table class="table table-bordered">
-                    <tr>
-                        <td>'.Display::url(get_lang('ActiveUsers'), api_get_path(WEB_CODE_PATH).'mySpace/student.php?active=1').'</td>
-                        <td align="right">'.$countActiveUsers.'</td>
-                    </tr>
-                    <tr>
-                        <td>'.Display::url(get_lang('InactiveUsers'), api_get_path(WEB_CODE_PATH).'mySpace/student.php?active=0').'</td>
-                        <td align="right">'.$countInactiveUsers.'</td>
-                    </tr>
-                    <tr>
-                        <td>'.Display::url(get_lang('SleepingTeachers'), api_get_path(WEB_CODE_PATH).'mySpace/teachers.php?sleeping_days=15').'</td>
-                        <td align="right">'.$countSleepingTeachers.'</td>
-                    </tr>
-                    <tr>
-                        <td>'.Display::url(get_lang('SleepingStudents'), api_get_path(WEB_CODE_PATH).'mySpace/student.php?sleeping_days=15').'</td>
-                        <td align="right">'.$countSleepingStudents.'</td>
-                    </tr>
-                    <tr>
-                        <td>'.get_lang('AverageCoursePerStudent').'</td>
-                        <td align="right">'.(is_null($avg_courses_per_student) ? '' : round($avg_courses_per_student, 2)).'</td>
-                    </tr>
-                    <tr>
-                        <td>'.get_lang('InactivesStudents').'</td>
-                        <td align="right">'.$nb_inactive_students.'</td>
-                    </tr>
-                    <tr>
-                        <td>'.get_lang('AverageTimeSpentOnThePlatform').'</td>
-                        <td align="right">'.(is_null($avg_time_spent) ? '' : api_time_to_hms($avg_time_spent)).'</td>
-                    </tr>
-                    <tr>
-                        <td>'.get_lang('AverageProgressInLearnpath').'</td>
-                        <td align="right">'.(is_null($avg_total_progress) ? '' : round($avg_total_progress, 2).'%').'</td>
-                    </tr>
-                    <tr>
-                        <td>'.get_lang('AvgCourseScore').'</td>
-                        <td align="right">'.(is_null($avg_results_to_exercises) ? '' : round($avg_results_to_exercises, 2).'%').'</td>
-                    </tr>
-                    <tr>
-                        <td>'.get_lang('AveragePostsInForum').'</td>
-                        <td align="right">'.(is_null($nb_posts) ? '' : round($nb_posts, 2)).'</td>
-                    </tr>
-                    <tr>
-                        <td>'.get_lang('AverageAssignments').'</td>
-                        <td align="right">'.(is_null($nb_assignments) ? '' : round($nb_assignments, 2)).'</td>
-                    </tr>
-                </table>
-                <a class="btn" href="'.api_get_path(WEB_CODE_PATH).'mySpace/student.php">
-                '.get_lang('SeeStudentList').'
-                </a>
-             </div><br />';
-    }
+                <tr>
+                    <td>'.Display::url(get_lang('SleepingStudents'), api_get_path(WEB_CODE_PATH).'mySpace/student.php?sleeping_days=15').'</td>
+                    <td align="right">'.$countSleepingStudents.'</td>
+                </tr>
+                <tr>
+                    <td>'.get_lang('AverageCoursePerStudent').'</td>
+                    <td align="right">'.(is_null($avg_courses_per_student) ? '' : round($avg_courses_per_student, 2)).'</td>
+                </tr>
+                <tr>
+                    <td>'.get_lang('InactivesStudents').'</td>
+                    <td align="right">'.$nb_inactive_students.'</td>
+                </tr>
+                <tr>
+                    <td>'.get_lang('AverageTimeSpentOnThePlatform').'</td>
+                    <td align="right">'.(is_null($avg_time_spent) ? '' : api_time_to_hms($avg_time_spent)).'</td>
+                </tr>
+                <tr>
+                    <td>'.get_lang('AverageProgressInLearnpath').'</td>
+                    <td align="right">'.(is_null($avg_total_progress) ? '' : round($avg_total_progress, 2).'%').'</td>
+                </tr>
+                <tr>
+                    <td>'.get_lang('AvgCourseScore').'</td>
+                    <td align="right">'.(is_null($avg_results_to_exercises) ? '' : round($avg_results_to_exercises, 2).'%').'</td>
+                </tr>
+                <tr>
+                    <td>'.get_lang('AveragePostsInForum').'</td>
+                    <td align="right">'.(is_null($nb_posts) ? '' : round($nb_posts, 2)).'</td>
+                </tr>
+                <tr>
+                    <td>'.get_lang('AverageAssignments').'</td>
+                    <td align="right">'.(is_null($nb_assignments) ? '' : round($nb_assignments, 2)).'</td>
+                </tr>
+            </table>
+            <a class="btn" href="'.api_get_path(WEB_CODE_PATH).'mySpace/student.php">
+            '.get_lang('SeeStudentList').'
+            </a>
+         </div><br />';
 }
 
+
 // Send the csv file if asked
 if ($export_csv) {
 	ob_end_clean();

+ 9 - 7
main/mySpace/student.php

@@ -46,7 +46,7 @@ function get_count_users($keyword = null, $active = null)
 
 function get_users($from, $number_of_items, $column, $direction)
 {
-    $active = isset($_GET['active']) ? $_GET['active'] : null;
+    $active = isset($_GET['active']) ? $_GET['active'] : 1;
     $keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
     $sleepingDays = isset($_GET['sleeping_days']) ? intval($_GET['sleeping_days']) : null;
 
@@ -74,15 +74,16 @@ function get_users($from, $number_of_items, $column, $direction)
                 $lastConnectionDate
             );
         } else {
-            $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
-                'drh',
+            $students = UserManager::get_users_followed_by_drh(
                 api_get_user_id(),
+                null,
+                false,
+                false,
                 false,
                 $from,
                 $number_of_items,
                 $column,
                 $direction,
-                $keyword,
                 $active,
                 $lastConnectionDate
             );
@@ -102,15 +103,16 @@ function get_users($from, $number_of_items, $column, $direction)
                 $lastConnectionDate
             );
         } else {
-            $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
-                'teacher',
+            $students = UserManager::get_users_followed_by_drh(
                 api_get_user_id(),
+                null,
+                false,
+                false,
                 false,
                 $from,
                 $number_of_items,
                 $column,
                 $direction,
-                $keyword,
                 $active,
                 $lastConnectionDate
             );

+ 10 - 10
main/mySpace/teachers.php

@@ -9,28 +9,30 @@
  */
 ob_start();
 
-// names of the language file that needs to be included
-$language_file = array ('registration', 'index', 'trad4all', 'tracking', 'admin');
+// names of the language file that needs to be included.
+$language_file = array('registration', 'index', 'trad4all', 'tracking', 'admin');
 $cidReset = true;
 require_once '../inc/global.inc.php';
 require_once 'myspace.lib.php';
 
 $userId = api_get_user_id();
-
 $this_section = SECTION_TRACKING;
 
 $nameTools = get_lang('Teachers');
 
 api_block_anonymous_users();
 $interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
+
 Display :: display_header($nameTools);
 
 $sleepingDays = isset($_GET['sleeping_days']) ? intval($_GET['sleeping_days']) : null;
+$active = isset($_GET['active']) ? intval($_GET['active']) : 1;
 
 $formateurs = array();
 if (api_is_drh() || api_is_platform_admin()) {
+
     // Followed teachers by drh
-    if (api_drh_can_access_all_session_content()) {
+    /*if (api_drh_can_access_all_session_content()) {
         $sessions = SessionManager::get_sessions_followed_by_drh($userId);
         if (!empty($sessions)) {
             $formateurs = array();
@@ -49,15 +51,13 @@ if (api_is_drh() || api_is_platform_admin()) {
         }
     } else {
         $formateurs = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
-    }
+    }*/
 
     $lastConnectionDate = null;
-
     if (!empty($sleepingDays)) {
         $lastConnectionDate = api_get_utc_datetime(strtotime($sleepingDays.' days ago'));
     }
-
-    $formateurs = SessionManager::getTeacherTracking($userId, 1, $lastConnectionDate);
+    $formateurs = SessionManager::getTeacherTracking($userId, $active, $lastConnectionDate);
 
     $menu_items = array(
         Display::url(Display::return_icon('stats.png', get_lang('MyStats'), '', ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH)."auth/my_progress.php" ),
@@ -138,8 +138,8 @@ $start_date = $end_date = null;
 
 if ($form->validate()) {
     $values = $form->exportValues();
-    $start_date = $defaults['start_date'] =  $values['start_date'];
-    $end_date = $defaults['end_date']   =  $values['end_date'];
+    $start_date = $defaults['start_date'] = $values['start_date'];
+    $end_date = $defaults['end_date'] = $values['end_date'];
     $time_filter = 'custom';
     $time_label = sprintf(get_lang('TimeSpentBetweenXAndY'), $start_date, $end_date);
 }

+ 295 - 0
main/mySpace/users.php

@@ -0,0 +1,295 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * Student report
+ * @package chamilo.reporting
+ */
+/**
+ * Code
+ */
+ // name of the language file that needs to be included
+$language_file = array ('registration', 'index', 'tracking', 'admin');
+$cidReset = true;
+
+require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
+
+$export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
+$keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
+$active = isset($_GET['active']) ? intval($_GET['active']) : null;
+
+api_block_anonymous_users();
+
+$this_section = SECTION_TRACKING;
+
+$interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
+
+if (isset($_GET["user_id"]) && $_GET["user_id"] != "" && !isset($_GET["type"])) {
+    $interbreadcrumb[] = array ("url" => "teachers.php", "name" => get_lang('Teachers'));
+}
+
+if (isset($_GET["user_id"]) && $_GET["user_id"]!="" && isset($_GET["type"]) && $_GET["type"] == "coach") {
+    $interbreadcrumb[] = array ("url" => "coaches.php", "name" => get_lang('Tutors'));
+}
+
+function get_count_users($keyword = null, $active = null)
+{
+    $sleepingDays = isset($_GET['sleeping_days']) ? intval($_GET['sleeping_days']) : null;
+
+    $lastConnectionDate = null;
+    if (!empty($sleepingDays)) {
+        $lastConnectionDate = api_get_utc_datetime(strtotime($sleepingDays.' days ago'));
+    }
+
+    return SessionManager::getCountUserTracking($keyword, $active, $lastConnectionDate);
+}
+
+function get_users($from, $number_of_items, $column, $direction)
+{
+    $active = isset($_GET['active']) ? $_GET['active'] : 1;
+    $keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
+    $sleepingDays = isset($_GET['sleeping_days']) ? intval($_GET['sleeping_days']) : null;
+
+    $lastConnectionDate = null;
+    if (!empty($sleepingDays)) {
+        $lastConnectionDate = api_get_utc_datetime(strtotime($sleepingDays.' days ago'));
+    }
+
+    $is_western_name_order = api_is_western_name_order();
+    $coach_id = api_get_user_id();
+    $column = 'u.user_id';
+
+    if (api_is_drh()) {
+        if (api_drh_can_access_all_session_content()) {
+            $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'drh_all',
+                api_get_user_id(),
+                false,
+                $from,
+                $number_of_items,
+                $column,
+                $direction,
+                $keyword,
+                $active,
+                $lastConnectionDate
+            );
+        } else {
+            $students = UserManager::get_users_followed_by_drh(
+                api_get_user_id(),
+                null,
+                false,
+                false,
+                false,
+                $from,
+                $number_of_items,
+                $column,
+                $direction,
+                $active,
+                $lastConnectionDate
+            );
+
+        }
+    } else {
+        if (api_is_platform_admin()) {
+            $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'admin',
+                api_get_user_id(),
+                false,
+                $from,
+                $number_of_items,
+                $column,
+                $direction,
+                $keyword,
+                $active,
+                $lastConnectionDate
+            );
+        } else {
+
+            $students = UserManager::get_users_followed_by_drh(
+                api_get_user_id(),
+                null,
+                false,
+                false,
+                false,
+                $from,
+                $number_of_items,
+                $column,
+                $direction,
+                $active,
+                $lastConnectionDate
+            );
+        }
+    }
+
+    $all_datas = array();
+
+    foreach ($students as $student_data) {
+        $student_id = $student_data['user_id'];
+        if (isset($_GET['id_session'])) {
+            $courses = Tracking :: get_course_list_in_session_from_student($student_id, $_GET['id_session']);
+        }
+
+        $avg_time_spent = $avg_student_score = $avg_student_progress = $total_assignments = $total_messages = 0;
+        $nb_courses_student = 0;
+        if (!empty($courses)) {
+            foreach ($courses as $course_code) {
+                if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
+                    $avg_time_spent 	+= Tracking :: get_time_spent_on_the_course($student_id, $course_code, $_GET['id_session']);
+                    $my_average 		 = Tracking :: get_avg_student_score($student_id, $course_code);
+                    if (is_numeric($my_average)) {
+                        $avg_student_score += $my_average;
+                    }
+                    $avg_student_progress += Tracking :: get_avg_student_progress($student_id, $course_code);
+                    $total_assignments += Tracking :: count_student_assignments($student_id, $course_code);
+                    $total_messages += Tracking :: count_student_messages($student_id, $course_code);
+                    $nb_courses_student++;
+                }
+            }
+        }
+
+        if ($nb_courses_student > 0) {
+            $avg_time_spent = $avg_time_spent / $nb_courses_student;
+            $avg_student_score = $avg_student_score / $nb_courses_student;
+            $avg_student_progress = $avg_student_progress / $nb_courses_student;
+        } else {
+            $avg_time_spent = null;
+            $avg_student_score = null;
+            $avg_student_progress = null;
+        }
+
+        $row = array();
+        if ($is_western_name_order) {
+            $row[] = $student_data['firstname'];
+            $row[] = $student_data['lastname'];
+        } else {
+            $row[] = $student_data['lastname'];
+            $row[] = $student_data['firstname'];
+        }
+        $string_date = Tracking :: get_last_connection_date($student_id, true);
+        $first_date = Tracking :: get_first_connection_date($student_id);
+        $row[] = $first_date;
+        $row[] = $string_date;
+
+        if (isset($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
+            $detailsLink = '<a href="myStudents.php?student='.$student_id.'&id_coach='.$coach_id.'&id_session='.$_GET['id_session'].'">
+				          <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+        } else {
+            $detailsLink =  '<a href="myStudents.php?student='.$student_id.'">
+				             <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+        }
+        $row[] = $detailsLink;
+        $all_datas[] = $row;
+    }
+    return $all_datas;
+}
+
+if ($export_csv) {
+    $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+} else {
+    $is_western_name_order = api_is_western_name_order();
+}
+
+$sort_by_first_name = api_sort_by_first_name();
+$actions .= '<div class="actions">';
+
+if (api_is_drh()) {
+    $menu_items = array(
+        Display::url(Display::return_icon('stats.png', get_lang('MyStats'), '', ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH)."auth/my_progress.php" ),
+        Display::url(Display::return_icon('user_na.png', get_lang('Students'), array(), ICON_SIZE_MEDIUM), '#'),
+        Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), ICON_SIZE_MEDIUM), 'teachers.php'),
+        Display::url(Display::return_icon('course.png', get_lang('Courses'), array(), ICON_SIZE_MEDIUM), 'course.php'),
+        Display::url(Display::return_icon('session.png', get_lang('Sessions'), array(), ICON_SIZE_MEDIUM), 'session.php')
+    );
+
+    $nb_menu_items = count($menu_items);
+    if ($nb_menu_items > 1) {
+        foreach ($menu_items as $key => $item) {
+            $actions .= $item;
+        }
+    }
+}
+
+$actions .= '<span style="float:right">';
+$actions .= Display::url(Display::return_icon('printer.png', get_lang('Print'), array(), ICON_SIZE_MEDIUM), 'javascript: void(0);', array('onclick'=>'javascript: window.print();'));
+$actions .= Display::url(Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), array(), ICON_SIZE_MEDIUM), api_get_self().'?export=csv&keyword='.$keyword);
+$actions .= '</span>';
+$actions .= '</div>';
+
+$table = new SortableTable(
+    'tracking_student',
+    'get_count_users',
+    'get_users',
+    ($is_western_name_order xor $sort_by_first_name) ? 1 : 0,
+    10
+);
+
+$params = array(
+    'keyword' => $keyword,
+    'active' => $active
+);
+$table->set_additional_parameters($params);
+
+if ($is_western_name_order) {
+    $table->set_header(0, get_lang('FirstName'), false);
+    $table->set_header(1, get_lang('LastName'), false);
+} else {
+    $table->set_header(0, get_lang('LastName'), false);
+    $table->set_header(1, get_lang('FirstName'), false);
+}
+
+$table->set_header(2, get_lang('FirstLogin'), false);
+$table->set_header(3, get_lang('LastConnexion'), false);
+$table->set_header(4, get_lang('Details'), false);
+
+if ($export_csv) {
+    if ($is_western_name_order) {
+        $csv_header[] = array (
+            get_lang('FirstName', ''),
+            get_lang('LastName', ''),
+            get_lang('FirstLogin', ''),
+            get_lang('LastConnexion', '')
+        );
+    } else {
+        $csv_header[] = array (
+            get_lang('LastName', ''),
+            get_lang('FirstName', ''),
+            get_lang('FirstLogin', ''),
+            get_lang('LastConnexion', '')
+        );
+    }
+}
+
+$form = new FormValidator('search_user', 'get', api_get_path(WEB_CODE_PATH).'mySpace/student.php');
+$form->addElement('text', 'keyword', get_lang('User'));
+$form->addElement('button', 'submit', get_lang('Search'));
+$form->setDefaults($params);
+
+// send the csv file if asked
+$content = $table->get_table_data();
+
+if ($export_csv) {
+    foreach ($content as &$row) {
+        unset($row[4]);
+    }
+    $csv_content = array_merge($csv_header, $content);
+    ob_end_clean();
+    Export :: export_table_csv($csv_content, 'reporting_student_list');
+    exit;
+} else {
+    Display::display_header($nameTools);
+    echo $actions;
+    $page_title = get_lang('Users');
+    echo Display::page_subheader($page_title);
+    if (isset($active)) {
+        if ($active) {
+            $activeLabel = get_lang('ActiveUsers');
+        } else {
+            $activeLabel = get_lang('InactiveUsers');
+        }
+        echo Display::page_subheader2($activeLabel);
+    }
+    $form->display();
+    $table->display();
+}
+
+Display :: display_footer();

+ 36 - 23
main/newscorm/learnpath.class.php

@@ -4962,11 +4962,12 @@ class learnpath
                     }
                     $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
                     $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
+                    $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
                     $this->arrMenu[] = array(
                         'id' => $array[$i]['id'],
                         'item_type' => $array[$i]['item_type'],
                         'title' => $array[$i]['title'],
-                        'path' => $array[$i]['path'],
+                        'path' => $path,
                         'description' => $array[$i]['description'],
                         'parent_item_id' => $array[$i]['parent_item_id'],
                         'previous_item_id' => $array[$i]['previous_item_id'],
@@ -7569,11 +7570,12 @@ class learnpath
      * @param string $item_type
      * @return string
      */
-    public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT) {
+    public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
+    {
+        global $charset, $_course;
         $course_id = api_get_course_int_id();
         $course_code = api_get_course_id();
 
-        global $charset, $_course;
         $return = '<div class="actions">';
 
         switch ($item_type) {
@@ -7613,15 +7615,17 @@ class learnpath
 
         $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
         $item_id = intval($item_id);
-        $sql    = "SELECT * FROM " . $tbl_lp_item . " as lp WHERE lp.c_id = ".$course_id." AND lp.id = " . $item_id;
+        $sql = "SELECT * FROM " . $tbl_lp_item . " as lp
+                WHERE lp.c_id = ".$course_id." AND lp.id = " . $item_id;
         $result = Database::query($sql);
-
         $row = Database::fetch_assoc($result);
 
         $audio_player = null;
         // We display an audio player if needed.
         if (!empty($row['audio'])) {
-            $audio_player .= '<div class="lp_mediaplayer" id="container"><a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.</div>';
+            $audio_player .= '<div class="lp_mediaplayer" id="container">
+                              <a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.
+                              </div>';
             $audio_player .= '<script type="text/javascript" src="../inc/lib/mediaplayer/swfobject.js"></script>';
             $audio_player .= '<script>
                                 var s1 = new SWFObject("../inc/lib/mediaplayer/player.swf","ply","250","20","9","#FFFFFF");
@@ -7630,16 +7634,30 @@ class learnpath
                                 s1.write("container");
                             </script>';
         }
-        $url = api_get_self() . '?cidReq='.Security::remove_XSS($_GET['cidReq']).'&view=build&id='.$item_id .'&lp_id='.$this->lp_id;
 
-        $return .= Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), $url.'&action=edit_item&path_item=' . $row['path']);
-        $return .= Display::url(Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL), $url.'&action=move_item');
+        $url = api_get_self().'?cidReq='.Security::remove_XSS($_GET['cidReq']).'&view=build&id='.$item_id .'&lp_id='.$this->lp_id;
+
+        $return .= Display::url(
+            Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL),
+            $url.'&action=edit_item&path_item=' . $row['path']
+        );
+
+        $return .= Display::url(
+            Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL),
+            $url.'&action=move_item'
+        );
 
         // Commented for now as prerequisites cannot be added to chapters.
         if ($item_type != 'dokeos_chapter' && $item_type != 'chapter') {
-            $return .= Display::url(Display::return_icon('accept.png', get_lang('LearnpathPrerequisites'), array(), ICON_SIZE_SMALL), $url.'&action=edit_item_prereq');
+            $return .= Display::url(
+                Display::return_icon('accept.png', get_lang('LearnpathPrerequisites'), array(), ICON_SIZE_SMALL),
+                $url.'&action=edit_item_prereq'
+            );
         }
-        $return .= Display::url(Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL), $url.'&action=delete_item');
+        $return .= Display::url(
+            Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL),
+            $url.'&action=delete_item'
+        );
 
          if ($item_type == TOOL_HOTPOTATOES ) {
             $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
@@ -7797,6 +7815,7 @@ class learnpath
         $form->addElement('hidden', 'parent', $data['parent_item_id']);
         $form->addElement('hidden', 'previous', $data['previous_item_id']);
         $form->setDefaults(array('title' => $data['title']));
+
         return $form->toHtml();
     }
 
@@ -7816,16 +7835,12 @@ class learnpath
         $row    = Database::fetch_array($result);
 
         $preq_id = $row['prerequisite'];
-        //$preq_mastery = $row['mastery_score'];
-        //$preq_max = $row['max_score'];
 
-        $return = $this->display_manipulate($item_id, TOOL_DOCUMENT);
+        //$return = $this->display_manipulate($item_id, TOOL_DOCUMENT);
         $return = '<legend>';
         $return .= get_lang('AddEditPrerequisites');
         $return .= '</legend>';
-
         $return .= '<form method="POST">';
-
         $return .= '<table class="data_table">';
         $return .= '<tr>';
         $return .= '<th height="24">' . get_lang('LearnpathPrerequisites') . '</th>';
@@ -7867,31 +7882,28 @@ class learnpath
         }
         $this->tree_array($arrLP);
         $arrLP = $this->arrMenu;
-        unset ($this->arrMenu);
+        unset($this->arrMenu);
 
         for ($i = 0; $i < count($arrLP); $i++) {
             if ($arrLP[$i]['id'] == $item_id)
                 break;
             $return .= '<tr>';
             $return .= '<td class="radio"' . (($arrLP[$i]['item_type'] != TOOL_QUIZ && $arrLP[$i]['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '') . '>';
-
             $return .= '<label for="id' . $arrLP[$i]['id'] . '">';
-
             $return .= '<input' . (($arrLP[$i]['id'] == $preq_id) ? ' checked="checked" ' : '') . (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter') ? ' disabled="disabled" ' : ' ') . 'id="id' . $arrLP[$i]['id'] . '" name="prerequisites" style="margin-left:' . $arrLP[$i]['depth'] * 10 . 'px; margin-right:10px;" type="radio" value="' . $arrLP[$i]['id'] . '" />';
             $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
             if (file_exists('../img/lp_' . $icon_name . '.png')) {
                 $return .= '<img alt="" src="../img/lp_' . $icon_name . '.png" style="margin-right:5px;" title="" />';
-            } else
+            } else {
                 if (file_exists('../img/lp_' . $icon_name . '.gif')) {
                     $return .= '<img alt="" src="../img/lp_' . $icon_name . '.gif" style="margin-right:5px;" title="" />';
                 } else {
                     $return .= Display::return_icon('folder_document.gif','',array('style'=>'margin-right:5px;'));
                 }
+            }
             $return .=  $arrLP[$i]['title'] . '</label>';
             $return .= '</td>';
 
-            //$return .= '<td class="radio"' . (($arrLP[$i]['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '') . ' />';
-
             if ($arrLP[$i]['item_type'] == TOOL_QUIZ) {
                 // lets update max_score Quiz information depending of the Quiz Advanced properties
                 require_once api_get_path(LIBRARY_PATH)."lp_item.lib.php";
@@ -7909,6 +7921,7 @@ class learnpath
                 $return .= '<center><input size="4" maxlength="3" name="max_' . $arrLP[$i]['id'] . '" type="text" value="' . $arrLP[$i]['max_score'] . '" disabled="true" /></center>';
                 $return .= '</td>';
             }
+
             if ($arrLP[$i]['item_type'] == TOOL_HOTPOTATOES) {
                 $return .= '<td class="exercise" style="border:1px solid #ccc;">';
                 $return .= '<center><input size="4" maxlength="3" name="min_' . $arrLP[$i]['id'] . '" type="text" value="' . (($arrLP[$i]['id'] == $preq_id) ? $preq_mastery : 0) . '" /></center>';
@@ -7924,8 +7937,8 @@ class learnpath
         $return .= '</table>';
         $return .= '<div style="padding-top:3px;">';
         $return .= '<button class="save" name="submit_button" type="submit">' . get_lang('ModifyPrerequisites') . '</button>';
-
         $return .= '</form>';
+
         return $return;
     }
 

+ 3 - 4
main/newscorm/lp_edit_item_prereq.php

@@ -46,9 +46,8 @@ if ((!$is_allowed_to_edit) || ($isStudentView)) {
 }
 $course_id = api_get_course_int_id();
 
-
-$sql_query = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND id = $learnpath_id";
-$result = Database::query($sql_query);
+$sql = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND id = $learnpath_id";
+$result = Database::query($sql);
 $therow = Database::fetch_array($result);
 
 /* SHOWING THE ADMIN TOOLS */
@@ -114,4 +113,4 @@ if (isset($is_success) && $is_success == true) {
 }
 echo '</div>';
 
-Display::display_footer();
+Display::display_footer();

+ 43 - 25
main/survey/fillsurvey.php

@@ -34,10 +34,18 @@ require_once 'survey.lib.php';
 if (!empty($_user)) {
     $interbreadcrumb[] = array('url' => 'survey_list.php?cidReq='.Security::remove_XSS($_GET['course']), 'name' => get_lang('SurveyList'));
 }
-if (($_GET['invitationcode'] == 'auto' && isset($_GET['scode'])) && ((!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'], true)))) {
-    // anonymous users not allowed
-    api_not_allowed();
-}
+
+// Database table definitions
+$table_survey = Database :: get_course_table(TABLE_SURVEY);
+$table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
+$table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
+$table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
+$table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
+
+$table_user = Database :: get_main_table(TABLE_MAIN_USER);
+
+// We initialize test as private (not anonymous):
+$isAnonymous = false;
 
 // getting all the course information
 if (isset($_GET['course'])) {
@@ -51,20 +59,27 @@ if (empty($course_info)) {
 }
 
 $course_id = $course_info['real_id'];
+$surveyCode = isset($_GET['scode']) ? Database::escape_string($_GET['scode']) : ''; 
+
+if ($surveyCode != "") {
+    // Firstly we check if this survey is ready for anonymous use:
+    $sqlAnonymous = "SELECT anonymous FROM $table_survey WHERE c_id = $course_id AND code ='".$surveyCode."'";
+    $resultAnonymous = Database::query($sqlAnonymous);
+    $rowAnonymous = Database::fetch_array($resultAnonymous, 'ASSOC');
+    // If is anonymous and is not allowed to take the survey to anonymous users, forbid access:
+    if (!isset($rowAnonymous['anonymous']) || ($rowAnonymous['anonymous'] == 0 && api_is_anonymous($_user['user_id'], true)) || count($rowAnonymous) == 0) {
+        api_not_allowed();
+    } 
+// If is anonymous and it is allowed to take the survey as anonymous, mark survey as anonymous:
+} else {
+    if (api_is_anonymous($_user['user_id'], true)) {
+        $isAnonymous = true;
+    }
+} 
 
 // Header
 Display :: display_header(get_lang('ToolSurvey'));
 
-// Database table definitions
-$table_survey = Database :: get_course_table(TABLE_SURVEY);
-$table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
-$table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
-$table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
-$table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
-
-$table_user = Database :: get_main_table(TABLE_MAIN_USER);
-
-
 // First we check if the needed parameters are present
 if ((!isset($_GET['course']) || !isset($_GET['invitationcode'])) && !isset($_GET['user_id'])) {
     Display :: display_error_message(get_lang('SurveyParametersMissingUseCopyPaste'), false);
@@ -77,11 +92,16 @@ $invitationcode = $_GET['invitationcode'];
 // Start auto-invitation feature FS#3403 (all-users-can-do-the-survey-URL handling)
 if ($invitationcode == 'auto' && isset($_GET['scode'])) {
     $userid = $_user['user_id'];
-
-    $scode = Database::escape_string($_GET['scode']); // Survey_code of the survey
-    $autoInvitationcode = "auto-$userid-$scode"; // New invitation code from userid
+    $surveyCode = Database::escape_string($_GET['scode']); 	// Survey_code of the survey
+	  if ($isAnonymous) {
+	      $autoInvitationcode = "auto-ANONY_".md5(time())."-$surveyCode";
+    } else {
+        // New invitation code from userid
+        $autoInvitationcode = "auto-$userid-$surveyCode"; 				
+    }
+	
     // The survey code must exist in this course, or the URL is invalid
-    $sql = "SELECT * FROM $table_survey WHERE c_id = $course_id AND code ='".$scode."'";
+    $sql = "SELECT * FROM $table_survey WHERE c_id = $course_id AND code = '".$surveyCode."'";
     $result = Database::query($sql);
     if (Database :: num_rows($result) > 0) { // Ok
         // Check availability
@@ -93,7 +113,7 @@ if ($invitationcode == 'auto' && isset($_GET['scode'])) {
         $result = Database::query($sql);
         if (Database :: num_rows($result) == 0) { // Ok
             $sql = "INSERT INTO $table_survey_invitation (c_id, survey_code,user, invitation_code, invitation_date) ";
-            $sql .= " VALUES ($course_id, \"$scode\", \"$userid\", \"$autoInvitationcode\", now())";
+            $sql .= " VALUES ($course_id, \"$surveyCode\", \"$userid\", \"$autoInvitationcode\", now())";
             Database::query($sql);
         }
         // From here we use the new invitationcode auto-userid-surveycode string
@@ -120,6 +140,8 @@ if ($survey_invitation['answered'] == 1 && !isset($_GET['user_id'])) {
     exit;
 }
 
+
+
 // Checking if there is another survey with this code.
 // If this is the case there will be a language choice
 $sql = "SELECT * FROM $table_survey WHERE c_id = $course_id AND code='".Database::escape_string($survey_invitation['survey_code'])."'";
@@ -159,9 +181,7 @@ if (count($_POST) > 0) {
         while ($row = Database::fetch_array($result, 'ASSOC')) {
             $types[$row['question_id']] = $row['type'];
         }
-        if ($survey_data['anonymous'] == 0) {
-            $survey_invitation['user'] = api_get_user_id();
-        }
+
         // Looping through all the post values
         foreach ($_POST as $key => & $value) {
             // If the post value key contains the string 'question' then it is an answer on a question
@@ -221,9 +241,7 @@ if (count($_POST) > 0) {
         while ($row = Database::fetch_array($result, 'ASSOC')) {
             $types[$row['question_id']] = $row['type'];
         }
-        if ($survey_data['anonymous'] == 0) {
-            $survey_invitation['user'] = api_get_user_id();
-        }
+
         // Looping through all the post values
         foreach ($_POST as $key => & $value) {
             // If the post value key contains the string 'question' then it is an answer to a question

+ 17 - 1
main/survey/preview.php

@@ -26,9 +26,25 @@ $table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
 $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
 $table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$table_survey_invitation        = Database :: get_course_table(TABLE_SURVEY_INVITATION);
 
 $course_id = api_get_course_int_id();
-
+$userId = api_get_user_id();
+$surveyId = Database::escape_string($_GET['survey_id']);
+$userInvited = 0;
+
+//query to ask if logged user is allowed to see the preview (if he is invited of he is a teacher)
+$sql = "SELECT survey_invitation.user FROM $table_survey_invitation survey_invitation LEFT JOIN $table_survey survey
+       ON survey_invitation.survey_code = survey.code WHERE survey_invitation.c_id = $course_id AND survey.survey_id = $surveyId AND survey_invitation.user = $userId";
+$result = Database::query($sql);
+if (Database::num_rows($result) > 0) {
+    $userInvited = 1;    
+}
+if($userInvited == 0) {
+    if(!api_is_allowed_to_edit()) {    
+        api_not_allowed();
+    }                
+}
 // We exit here if ther is no valid $_GET parameter
 if (!isset($_GET['survey_id']) || !is_numeric($_GET['survey_id'])){
 	Display :: display_header(get_lang('SurveyPreview'));

+ 43 - 1528
main/wiki/index.php

@@ -9,20 +9,15 @@
 /**
  * Code
  */
+use \ChamiloSession as Session;
+
 // name of the language file that needs to be included
 $language_file = 'wiki';
-$newtitle = null;
 
 // including the global initialization file
 require_once '../inc/global.inc.php';
 require_once 'wiki.inc.php';
 
-// Database table definition
-$tbl_wiki           = Database::get_course_table(TABLE_WIKI);
-$tbl_wiki_discuss   = Database::get_course_table(TABLE_WIKI_DISCUSS);
-$tbl_wiki_mailcue   = Database::get_course_table(TABLE_WIKI_MAILCUE);
-$tbl_wiki_conf      = Database::get_course_table(TABLE_WIKI_CONF);
-
 global $charset;
 
 $wiki = new Wiki();
@@ -34,6 +29,11 @@ $current_course_tool  = TOOL_WIKI;
 require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
 
 $course_id = api_get_course_int_id();
+$session_id = api_get_session_id();
+$condition_session = api_get_session_condition($session_id);
+$course_id = api_get_course_int_id();
+$groupId = api_get_group_id();
+
 // additional style information
 $htmlHeadXtra[] ='<link rel="stylesheet" type="text/css" href="'.api_get_path(WEB_CODE_PATH).'wiki/css/default.css"/>';
 
@@ -42,43 +42,31 @@ $htmlHeadXtra[] = '<script>
 function advanced_parameters() {
     if (document.getElementById(\'options\').style.display == \'none\') {
         document.getElementById(\'options\').style.display = \'block\';
-        document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+        document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif', get_lang('Hide'), array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
     } else {
         document.getElementById(\'options\').style.display = \'none\';
-        document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+        document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif', get_lang('Show'), array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
     }
 }
-function setFocus(){
+function setFocus() {
     $("#search_title").focus();
 }
 
-$(document).ready(function () {
+$(document).ready(function() {
     setFocus();
+    $("#start_date_toggle").click(function() {
+        $("#start_date").toggle();
+    });
+
+    $("#end_date_toggle").click(function() {
+        $("#end_date").toggle();
+    });
 });
 
 </script>';
 
 /* Constants and variables */
 $tool_name = get_lang('ToolWiki');
-$MonthsLong = array(
-    get_lang("JanuaryLong"),
-    get_lang("FebruaryLong"),
-    get_lang("MarchLong"),
-    get_lang("AprilLong"),
-    get_lang("MayLong"),
-    get_lang("JuneLong"),
-    get_lang("JulyLong"),
-    get_lang("AugustLong"),
-    get_lang("SeptemberLong"),
-    get_lang("OctoberLong"),
-    get_lang("NovemberLong"),
-    get_lang("DecemberLong")
-);
-
-//condition for the session
-$session_id = api_get_session_id();
-$condition_session = api_get_session_condition($session_id);
-$course_id = api_get_course_int_id();
 
 /* ACCESS */
 api_protect_course_script();
@@ -87,1531 +75,58 @@ api_block_anonymous_users();
 /* TRACKING */
 event_access_tool(TOOL_WIKI);
 
-/* HEADER & TITLE */
-// If it is a group wiki then the breadcrumbs will be different.
-
-// Setting variable
-$groupId = api_get_group_id();
-
 if ($groupId) {
     $group_properties = GroupManager::get_group_properties($groupId);
-    $interbreadcrumb[] = array("url" => "../group/group.php", "name" => get_lang('Groups'));
-    $interbreadcrumb[] = array("url"=>"../group/group_space.php?gidReq=".$groupId, "name"=> get_lang('GroupSpace').' '.$group_properties['name']);
-
-    $add_group_to_title = ' '.$group_properties['name'];
-    $groupfilter='group_id="'.$groupId.'"';
-
+    $interbreadcrumb[] = array("url" => api_get_path(WEB_CODE_PATH)."group/group.php", "name" => get_lang('Groups'));
+    $interbreadcrumb[] = array(
+        "url" => api_get_path(WEB_CODE_PATH)."group/group_space.php?gidReq=".$groupId,
+        "name" => get_lang('GroupSpace').' '.$group_properties['name']
+    );
     //ensure this tool in groups whe it's private or deactivated
     if ($group_properties['wiki_state'] == 0) {
         api_not_allowed();
     } elseif ($group_properties['wiki_state']==2) {
-        if (!api_is_allowed_to_edit(false,true) and !GroupManager :: is_user_in_group($_user['user_id'], $_SESSION['_gid'])) {
+        if (!api_is_allowed_to_edit(false,true) and !GroupManager :: is_user_in_group(api_get_user_id(), api_get_group_id())) {
             api_not_allowed();
         }
     }
-} else {
-    $groupfilter='group_id=0';
-}
-
-if (isset($_POST['action']) && $_POST['action']=='export_to_pdf' && isset($_POST['wiki_id']) && api_get_setting('students_export2pdf') == 'true') {
-    $wiki->export_to_pdf($_POST['wiki_id'], api_get_course_id());
-    exit;
 }
 
-$action = isset($_GET['action']) ? $_GET['action'] : null;
-Display::display_header($tool_name, 'Wiki');
 $is_allowed_to_edit = api_is_allowed_to_edit(false, true);
-/* INITIALISATION */
 
-//the page we are dealing with
-if (!isset($_GET['title'])) {
-    $page = 'index';
-} else {
-    $page = $_GET['title'];
-}
+// The page we are dealing with
+$page = isset($_GET['title']) ? $_GET['title']: 'index';
+$action = isset($_GET['action']) ? $_GET['action'] : 'showpage';
+$view = isset($_GET['view']) ? $_GET['view'] : null;
 
 $wiki->page = $page;
+$wiki->action = $action;
 
 /* MAIN CODE */
 
-// Tool introduction
-Display::display_introduction_section(TOOL_WIKI);
-
 /* ACTIONS */
 $wiki->blockConcurrentEditions(api_get_user_id(), $action);
 
-// Saving a change
-
-if (isset($_POST['SaveWikiChange']) AND $_POST['title']<>'') {
-    if (empty($_POST['title'])) {
-        Display::display_error_message(get_lang("NoWikiPageTitle"));
-    } elseif (!$wiki->double_post($_POST['wpost_id'])) {
-        //double post
-    } elseif ($_POST['version']!='' && $_SESSION['_version']!=0 && $_POST['version']!=$_SESSION['_version']) {
-        //prevent concurrent users and double version
-        Display::display_error_message(get_lang("EditedByAnotherUser"));
-    } else {
-        $return_message = $wiki->save_wiki();
-        Display::display_confirmation_message($return_message, false);
-    }
-}
-
-// Saving a new wiki entry
-if (isset($_POST['SaveWikiNew'])) {
-    if (empty($_POST['title'])) {
-        Display::display_error_message(get_lang("NoWikiPageTitle"));
-    } elseif (strtotime($wiki->get_date_from_select('startdate_assig')) > strtotime($wiki->get_date_from_select('enddate_assig'))) {
-        Display::display_error_message(get_lang("EndDateCannotBeBeforeTheStartDate"));
-    } elseif (!$wiki->double_post($_POST['wpost_id'])) {
-        //double post
-    } else {
-        $_clean['assignment'] = null;
-        if (isset($_POST['assignment'])) {
-            // for mode assignment
-            $_clean['assignment'] = Database::escape_string($_POST['assignment']);
-        }
-
-        if ($_clean['assignment'] == 1) {
-            $wiki->auto_add_page_users($_clean['assignment']);
-        }
-        $return_message = $wiki->save_new_wiki();
-        if ($return_message == false) {
-            Display::display_error_message(get_lang('NoWikiPageTitle'), false);
-        } else {
-            Display::display_confirmation_message($return_message, false);
-        }
-    }
-}
-
-// check last version
-if (isset($_GET['view']) && $_GET['view']) {
-    $sql = 'SELECT * FROM '.$tbl_wiki.'
-            WHERE
-                c_id = '.$course_id.' AND
-                id="'.Database::escape_string($_GET['view']).'"'; //current view
-    $result=Database::query($sql);
-    $current_row=Database::fetch_array($result);
-
-    $sql = 'SELECT * FROM '.$tbl_wiki.'
-            WHERE c_id = '.$course_id.' AND reflink="'.Database::escape_string($page).'" AND '.$groupfilter.$condition_session.' ORDER BY id DESC'; //last version
-    $result=Database::query($sql);
-    $last_row=Database::fetch_array($result);
-
-    if ($_GET['view'] < $last_row['id']) {
-       $message = '<center>'.get_lang('NoAreSeeingTheLastVersion').'<br /> '.get_lang("Version").' (<a href="index.php?cidReq='.$_course['id'].'&action=showpage&amp;title='.api_htmlentities(urlencode($current_row['reflink'])).'&group_id='.$current_row['group_id'].'&session_id='.$current_row['session_id'].'&view='.api_htmlentities($_GET['view']).'" title="'.get_lang('CurrentVersion').'">'.$current_row['version'].'</a> / <a href="index.php?cidReq='.$_course['id'].'&action=showpage&amp;title='.api_htmlentities(urlencode($last_row['reflink'])).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'" title="'.get_lang('LastVersion').'">'.$last_row['version'].'</a>) <br />'.get_lang("ConvertToLastVersion").': <a href="index.php?cidReq='.$_course['id'].'&action=restorepage&amp;title='.api_htmlentities(urlencode($last_row['reflink'])).'&group_id='.$last_row['group_id'].'&session_id='.$last_row['session_id'].'&view='.api_htmlentities($_GET['view']).'">'.get_lang("Restore").'</a></center>';
-       Display::display_warning_message($message,false);
-    }
-
-    // Restore page.
-
-    if ($action == 'restorepage') {
-        //Only teachers and platform admin can edit the index page. Only teachers and platform admin can edit an assignment teacher
-        if ((
-            $current_row['reflink']=='index' ||
-            $current_row['reflink']=='' ||
-            $current_row['assignment'] == 1
-            ) &&
-            (!api_is_allowed_to_edit(false,true) && intval($_GET['group_id'])==0)
-        ) {
-            Display::display_normal_message(get_lang('OnlyEditPagesCourseManager'));
-        } else {
-            $PassEdit=false;
-
-            //check if is a wiki group
-            if ($current_row['group_id'] != 0) {
-				//Only teacher, platform admin and group members can edit a wiki group
-				if (api_is_allowed_to_edit(false,true) || api_is_platform_admin() || GroupManager :: is_user_in_group($_user['user_id'],intval($_GET['group_id']))) {
-                    $PassEdit = true;
-                } else {
-                    Display::display_normal_message(get_lang('OnlyEditPagesGroupMembers'));
-                }
-            } else {
-                $PassEdit=true;
-            }
-
-            // check if is an assignment
-            $icon_assignment = null;
-            if ($current_row['assignment']==1) {
-                Display::display_normal_message(get_lang('EditAssignmentWarning'));
-                $icon_assignment=Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'),'',ICON_SIZE_SMALL);
-            } elseif($current_row['assignment']==2) {
-                $icon_assignment=Display::return_icon('wiki_work.png', get_lang('AssignmentWorkExtra'),'',ICON_SIZE_SMALL);
-                if ((api_get_user_id()==$current_row['user_id'])==false) {
-                    if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-                        $PassEdit=true;
-                    } else {
-                        Display::display_warning_message(get_lang('LockByTeacher'));
-                        $PassEdit=false;
-                    }
-                } else {
-                    $PassEdit=true;
-                }
-            }
-
-            //show editor if edit is allowed
-            if ($PassEdit) {
-                if ($row['editlock']==1 && (api_is_allowed_to_edit(false,true)==false || api_is_platform_admin()==false)) {
-                    Display::display_normal_message(get_lang('PageLockedExtra'));
-                } else {
-                    if ($last_row['is_editing']!=0 && $last_row['is_editing'] != $_user['user_id']) {
-                        //checking for concurrent users
-                        $timestamp_edit = strtotime($last_row['time_edit']);
-                        $time_editing = time()-$timestamp_edit;
-                        $max_edit_time = 1200; // 20 minutes
-                        $rest_time = $max_edit_time - $time_editing;
-                        $userinfo = api_get_user_info($last_row['is_editing']);
-                        $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username']), ENT_QUOTES);
-                        $is_being_edited = get_lang('ThisPageisBeginEditedBy').' <a href=../user/userInfo.php?uInfo='.$userinfo['user_id'].'>'.
-                            Display::tag('span', api_get_person_name($userinfo['firstname'], $userinfo['lastname'], array('title'=>$username))).
-                            get_lang('ThisPageisBeginEditedTryLater').' '.date( "i",$rest_time).' '.get_lang('MinMinutes');
-                        Display::display_normal_message($is_being_edited, false);
-                    } else {
-                         Display::display_confirmation_message(
-                             $wiki->restore_wikipage(
-                                 $current_row['page_id'],
-                                 $current_row['reflink'],
-                                 api_htmlentities($current_row['title']),
-                                 api_htmlentities($current_row['content']),
-                                 $current_row['group_id'],
-                                 $current_row['assignment'],
-                                 $current_row['progress'],
-                                 $current_row['version'],
-                                 $last_row['version'],
-                                 $current_row['linksto']
-                             ).': <a href="index.php?cidReq='.$_course['id'].'&action=showpage&amp;title='.api_htmlentities(urlencode($last_row['reflink'])).'&session_id='.$last_row['session_id'].'&group_id='.$last_row['group_id'].'">'.api_htmlentities($last_row['title']).'</a>',
-                             false
-                         );
-                    }
-                }
-            }
-        }
-    }
-}
-
-if ($action == 'deletewiki') {
-    if (api_is_allowed_to_edit(false, true) || api_is_platform_admin()) {
-        if ($_GET['delete'] == 'yes') {
-            $return_message = $wiki->delete_wiki();
-            Display::display_confirmation_message($return_message);
-        }
-    }
-}
-if ($action =='discuss' && isset($_POST['Submit']) && $_POST['Submit']) {
-    Display::display_confirmation_message(get_lang('CommentAdded'));
-}
-
 /* MAIN WIKI AREA */
 
-/** menuwiki (= actions of the page, not of the wiki tool) **/
-
-echo '<div class="actions">';
-/*        echo '&nbsp;<a href="index.php?cidReq='.$_course['id'].'&action=show&amp;title=index&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('show').'>'.
-    Display::return_icon('wiki.png',get_lang('HomeWiki'),'',ICON_SIZE_MEDIUM).'</a>&nbsp;';*/
-echo '<ul class="nav" style="margin-bottom:0px">
-    <li class="dropdown">
-    <a class="dropdown-toggle" href="javascript:void(0)">'.Display::return_icon('menu.png', get_lang('Menu'), '', ICON_SIZE_MEDIUM).'</a>';
-// menu home
-echo '<ul class="dropdown-menu">';
-echo '<li><a href="index.php?cidReq='.$_course['id'].'&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('Home').'</a></li>';
-if (api_is_allowed_to_session_edit(false,true)) {
-    //menu add page
-    echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=addnew&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('addnew').'>'.get_lang('AddNew').'</a>';
-}
-$lock_unlock_addnew = null;
-$protect_addnewpage = null;
-
-if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-    // page action: enable or disable the adding of new pages
-    if ($wiki->check_addnewpagelock()==0) {
-        $protect_addnewpage = Display::return_icon('off.png', get_lang('AddOptionProtected'));
-        $lock_unlock_addnew ='unlockaddnew';
-    } else {
-        $protect_addnewpage = Display::return_icon('on.png', get_lang('AddOptionUnprotected'));
-        $lock_unlock_addnew ='lockaddnew';
-    }
-}
-
-echo '<a href="index.php?action=show&amp;actionpage='.$lock_unlock_addnew.'&amp;title='.api_htmlentities(urlencode($page)).'">'.$protect_addnewpage.'</a></li>';
-// menu find
-echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=searchpages&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('searchpages').'>'.get_lang('SearchPages').'</a></li>';
-// menu all pages
-echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=allpages&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('allpages').'>'.get_lang('AllPages').'</a></li>';
-// menu recent changes
-echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=recentchanges&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('recentchanges').'>'.get_lang('RecentChanges').'</a></li>';
-// menu delete all wiki
-if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-    echo '<li><a href="index.php?action=deletewiki&amp;title='.api_htmlentities(urlencode($page)).'"'.$wiki->is_active_navigation_tab('deletewiki').'>'.get_lang('DeleteWiki').'</a></li>';
-}
-///menu more
-echo '<li><a href="index.php?action=more&amp;title='.api_htmlentities(urlencode($page)).'"'.$wiki->is_active_navigation_tab('more').'>'.get_lang('Statistics').'</a></li>';
-echo '</ul>';
-echo '</li>';
-
-//menu show page
-echo '<a href="index.php?cidReq='.$_course['id'].'&action=showpage&amp;title='.api_htmlentities(urlencode($page)).'&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('showpage').'>'.Display::return_icon('page.png',get_lang('ShowThisPage'),'',ICON_SIZE_MEDIUM).'</a>';
-
-if (api_is_allowed_to_session_edit(false,true) ) {
-    //menu edit page
-    echo '<a href="index.php?cidReq='.$_course['id'].'&action=edit&amp;title='.api_htmlentities(urlencode($page)).'&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('edit').'>'.Display::return_icon('edit.png',get_lang('EditThisPage'),'',ICON_SIZE_MEDIUM).'</a>';
-
-    //menu discuss page
-    echo '<a href="index.php?action=discuss&amp;title='.api_htmlentities(urlencode($page)).'"'.$wiki->is_active_navigation_tab('discuss').'>'.Display::return_icon('discuss.png',get_lang('DiscussThisPage'),'',ICON_SIZE_MEDIUM).'</a>';
- }
-
-//menu history
-echo '<a href="index.php?cidReq='.$_course['id'].'&action=history&amp;title='.api_htmlentities(urlencode($page)).'&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('history').'>'.Display::return_icon('history.png',get_lang('ShowPageHistory'),'',ICON_SIZE_MEDIUM).'</a>';
-//menu linkspages
-echo '<a href="index.php?action=links&amp;title='.api_htmlentities(urlencode($page)).'&session_id='.$session_id.'&group_id='.$groupId.'"'.$wiki->is_active_navigation_tab('links').'>'.Display::return_icon('what_link_here.png',get_lang('LinksPages'),'',ICON_SIZE_MEDIUM).'</a>';
-
-//menu delete wikipage
-if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-    echo '<a href="index.php?action=delete&amp;title='.api_htmlentities(urlencode($page)).'"'.$wiki->is_active_navigation_tab('delete').'>'.Display::return_icon('delete.png',get_lang('DeleteThisPage'),'',ICON_SIZE_MEDIUM).'</a>';
-}
-echo '</ul>';
-echo '</div>'; // End actions
-
-
-//In new pages go to new page
-if (isset($_POST['SaveWikiNew'])) {
-    if (isset($_POST['reflink'])) {
-        $wiki->display_wiki_entry($_POST['reflink']);
-    }
-}
-
-//More for export to course document area. See display_wiki_entry
-if (isset($_POST['export2DOC']) && $_POST['export2DOC']) {
-    $doc_id = $_POST['doc_id'];
-    $export2doc = $wiki->export2doc($doc_id);
-    if ($export2doc) {
-        Display::display_confirmation_message(get_lang('ThePageHasBeenExportedToDocArea'));
-    }
-}
-
-if (isset($action) && $action =='more') {
-    echo '<div class="actions">'.get_lang('More').'</div>';
-    echo '<table border="0">';
-    echo '  <tr>';
-    echo '    <td>';
-    echo '      <ul>';
-    //Submenu Most active users
-    echo '        <li><a href="index.php?cidReq='.$_course['id'].'&action=mactiveusers&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostActiveUsers').'</a></li>';
-    //Submenu Most visited pages
-    echo '        <li><a href="index.php?cidReq='.$_course['id'].'&action=mvisited&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostVisitedPages').'</a></li>';
-    //Submenu Most changed pages
-    echo '        <li><a href="index.php?cidReq='.$_course['id'].'&action=mostchanged&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostChangedPages').'</a></li>';
-    echo '      </ul>';
-    echo '    </td>';
-    echo '    <td>';
-    echo '      <ul>';
-    // Submenu Orphaned pages
-    echo '        <li><a href="index.php?cidReq='.$_course['id'].'&action=orphaned&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('OrphanedPages').'</a></li>';
-    // Submenu Wanted pages
-    echo '        <li><a href="index.php?cidReq='.$_course['id'].'&action=wanted&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('WantedPages').'</a></li>';
-	// Submenu Most linked pages
-    echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=mostlinked&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('MostLinkedPages').'</a></li>';
-    echo '</ul>';
-	echo '</td>';
-	echo '<td style="vertical-align:top">';
-    echo '<ul>';
-	// Submenu Statistics
-	if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-    	echo '<li><a href="index.php?cidReq='.$_course['id'].'&action=statistics&session_id='.$session_id.'&group_id='.$groupId.'">'.get_lang('Statistics').'</a></li>';
-	}
-    echo '      </ul>';
-    echo'    </td>';
-    echo '  </tr>';
-    echo '</table>';
-}
-
-// Statistics Juan Carlos Raña Trabado
-
-if ($action =='statistics' && (api_is_allowed_to_edit(false,true) || api_is_platform_admin())) {
-    $wiki->getStats();
-}
-
-// Most active users Juan Carlos Raña Trabado
-
-if ($action =='mactiveusers') {
-    $wiki->getActiveUsers($action);
-}
-
-// User contributions Juan Carlos Raña Trabado
-
-if ($action =='usercontrib') {
-    $userinfo = api_get_user_info($_GET['user_id']);
-    $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username']), ENT_QUOTES);
-
-    echo '<div class="actions">'.get_lang('UserContributions').': <a href="../user/userInfo.php?uInfo='.$userinfo['user_id'].'">'.
-            Display::tag('span', api_htmlentities(api_get_person_name($userinfo['firstname'], $userinfo['lastname'])), array('title'=>$username)).
-            '</a><a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=usercontrib&user_id='.urlencode($row['user_id']).
-            '&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'"></a></div>';
-
-    if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-        //only by professors if page is hidden
-        $sql='SELECT * FROM '.$tbl_wiki.'  WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND user_id="'.Database::escape_string($_GET['user_id']).'"';
-    } else {
-        $sql='SELECT * FROM '.$tbl_wiki.'  WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND user_id="'.Database::escape_string($_GET['user_id']).'" AND visibility=1';
-    }
-
-    $allpages = Database::query($sql);
-
-    //show table
-    if (Database::num_rows($allpages) > 0) {
-        $row = array ();
-        while ($obj = Database::fetch_object($allpages)) {
-            //get author
-            $userinfo = api_get_user_info($obj->user_id);
-
-            //get time
-            $year 	 = substr($obj->dtime, 0, 4);
-            $month	 = substr($obj->dtime, 5, 2);
-            $day 	 = substr($obj->dtime, 8, 2);
-            $hours   = substr($obj->dtime, 11,2);
-            $minutes = substr($obj->dtime, 14,2);
-            $seconds = substr($obj->dtime, 17,2);
-
-            //get type assignment icon
-            if ($obj->assignment==1) {
-                $ShowAssignment=Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'),'',ICON_SIZE_SMALL);
-            } elseif ($obj->assignment==2) {
-                $ShowAssignment=Display::return_icon('wiki_work.png', get_lang('AssignmentWork'),'',ICON_SIZE_SMALL);
-            } elseif ($obj->assignment==0) {
-                $ShowAssignment='<img src="../img/px_transparent.gif" />';
-            }
-
-            $row = array ();
-            $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
-            $row[] =$ShowAssignment;
-            $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&view='.$obj->id.'&session_id='.api_htmlentities(urlencode($_GET['$session_id'])).'&group_id='.api_htmlentities(urlencode($_GET['group_id'])).'">'.api_htmlentities($obj->title).'</a>';
-            $row[] =Security::remove_XSS($obj->version);
-            $row[] =Security::remove_XSS($obj->comment);
-            $row[] =Security::remove_XSS($obj->progress).' %';
-            $row[] =Security::remove_XSS($obj->score);
-            $rows[] = $row;
-
-        }
-
-        $table = new SortableTableFromArrayConfig($rows,2,10,'UsersContributions_table','','','ASC');
-        $table->set_additional_parameters(
-            array('cidReq' =>Security::remove_XSS($_GET['cidReq']),'action'=>Security::remove_XSS($action ),'user_id'=>Security::remove_XSS($_GET['user_id']),'session_id'=>Security::remove_XSS($_GET['session_id']),'group_id'=>Security::remove_XSS($_GET['group_id']))
-        );
-        $table->set_header(0,get_lang('Date'), true, array ('style' => 'width:200px;'));
-        $table->set_header(1,get_lang('Type'), true, array ('style' => 'width:30px;'));
-        $table->set_header(2,get_lang('Title'), true, array ('style' => 'width:200px;'));
-        $table->set_header(3,get_lang('Version'), true, array ('style' => 'width:30px;'));
-        $table->set_header(4,get_lang('Comment'), true, array ('style' => 'width:200px;'));
-        $table->set_header(5,get_lang('Progress'), true, array ('style' => 'width:30px;'));
-        $table->set_header(6,get_lang('Rating'), true, array ('style' => 'width:30px;'));
-        $table->display();
-    }
-}
-
-/* Most changed pages */
-
-if ($action =='mostchanged') {
-    echo '<div class="actions">'.get_lang('MostChangedPages').'</div>';
-
-    if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) { //only by professors if page is hidden
-        $sql='SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'  WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' GROUP BY reflink';//TODO:check MAX and group by return last version
-    } else {
-        $sql='SELECT *, MAX(version) AS MAX FROM '.$tbl_wiki.'  WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1 GROUP BY reflink'; //TODO:check MAX and group by return last version
-    }
-
-    $allpages=Database::query($sql);
-
-    //show table
-    if (Database::num_rows($allpages) > 0) {
-        $row = array ();
-        while ($obj = Database::fetch_object($allpages)) {
-            //get type assignment icon
-            if ($obj->assignment==1) {
-                $ShowAssignment=Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'),'',ICON_SIZE_SMALL);
-            } elseif ($obj->assignment==2) {
-                $ShowAssignment=Display::return_icon('wiki_work.png', get_lang('AssignmentWork'),'',ICON_SIZE_SMALL);
-            } elseif ($obj->assignment==0) {
-                $ShowAssignment='<img src="../img/px_transparent.gif" />';
-            }
-
-            $row = array ();
-            $row[] = $ShowAssignment;
-            $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.api_htmlentities($obj->title).'</a>';
-            $row[] = $obj->MAX;
-            $rows[] = $row;
-        }
-
-        $table = new SortableTableFromArrayConfig($rows,2,10,'MostChangedPages_table','','','DESC');
-        $table->set_additional_parameters(array('cidReq' =>Security::remove_XSS($_GET['cidReq']),'action'=>Security::remove_XSS($action ),'session_id'=>Security::remove_XSS($_GET['session_id']),'group_id'=>Security::remove_XSS($_GET['group_id'])));
-        $table->set_header(0,get_lang('Type'), true, array ('style' => 'width:30px;'));
-        $table->set_header(1,get_lang('Title'), true);
-        $table->set_header(2,get_lang('Changes'), true);
-        $table->display();
-    }
-}
-
-/* Most visited pages */
-
-if ($action =='mvisited') {
-    echo '<div class="actions">'.get_lang('MostVisitedPages').'</div>';
-
-    if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) { //only by professors if page is hidden
-        $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
-                WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
-                GROUP BY reflink';
-    } else {
-        $sql = 'SELECT *, SUM(hits) AS tsum FROM '.$tbl_wiki.'
-                WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND visibility=1
-                GROUP BY reflink';
-    }
-
-    $allpages=Database::query($sql);
-
-    //show table
-    if (Database::num_rows($allpages) > 0) {
-        $row = array ();
-        while ($obj = Database::fetch_object($allpages)) {
-            //get type assignment icon
-            if ($obj->assignment==1) {
-                $ShowAssignment=Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'),'',ICON_SIZE_SMALL);
-            } elseif ($obj->assignment==2) {
-                $ShowAssignment=$ShowAssignment=Display::return_icon('wiki_work.png', get_lang('AssignmentWork'),'',ICON_SIZE_SMALL);
-            } elseif ($obj->assignment==0) {
-                $ShowAssignment='<img src="../img/px_transparent.gif" />';
-            }
-
-            $row = array ();
-            $row[] =$ShowAssignment;
-            $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.api_htmlentities($obj->title).'</a>';
-            $row[] = $obj->tsum;
-            $rows[] = $row;
-        }
-
-        $table = new SortableTableFromArrayConfig($rows,2,10,'MostVisitedPages_table','','','DESC');
-        $table->set_additional_parameters(array('cidReq' =>Security::remove_XSS($_GET['cidReq']),'action'=>Security::remove_XSS($action ),'session_id'=>Security::remove_XSS($_GET['session_id']),'group_id'=>Security::remove_XSS($_GET['group_id'])));
-        $table->set_header(0,get_lang('Type'), true, array ('style' => 'width:30px;'));
-        $table->set_header(1,get_lang('Title'), true);
-        $table->set_header(2,get_lang('Visits'), true);
-        $table->display();
-    }
-}
-
-/* Wanted pages */
-
-if ($action =='wanted') {
-    echo '<div class="actions">'.get_lang('WantedPages').'</div>';
-    $pages = array();
-    $refs = array();
-	$wanted = array();
-    //get name pages
-    $sql = 'SELECT * FROM '.$tbl_wiki.'
-            WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
-            GROUP BY reflink ORDER BY reflink ASC';
-    $allpages=Database::query($sql);
-
-    while ($row=Database::fetch_array($allpages)) {
-		if ($row['reflink']=='index'){
-			$row['reflink']=str_replace(' ','_',get_lang('DefaultTitle'));
-		}
-        $pages[] = $row['reflink'];
-    }
-
-    //get name refs in last pages
-    $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
-    		WHERE s1.c_id = '.$course_id.' AND id=(
-    		    SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2
-    		    WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.'
-            )';
-
-    $allpages = Database::query($sql);
-
-    while ($row=Database::fetch_array($allpages)) {
-        $refs = explode(" ", trim($row["linksto"]));
-		// Find linksto into reflink. If not found ->page is wanted
-		foreach ($refs as $v) {
-
-			if (!in_array($v, $pages)) {
-				if (trim($v)!="") {
-					$wanted[]=$v;
-				}
-			}
-		}
-	}
-
-	$wanted = array_unique($wanted);//make a unique list
-
-	//show table
-    $rows = array();
-    foreach ($wanted as $wanted_show) {
-        $row = array();
-        $wanted_show=Security::remove_XSS($wanted_show);
-        $row[] = '<a href="'.api_get_path(WEB_PATH).'main/wiki/index.php?cidReq=&action=addnew&title='.str_replace('_',' ',$wanted_show).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'" class="new_wiki_link">'.str_replace('_',' ',$wanted_show).'</a>';//meter un remove xss en lugar de htmlentities
-        $rows[] = $row;
-    }
-
-    $table = new SortableTableFromArrayConfig($rows,0,10,'WantedPages_table','','','DESC');
-    $table->set_additional_parameters(array('cidReq' =>Security::remove_XSS($_GET['cidReq']),'action'=>Security::remove_XSS($action ),'session_id'=>Security::remove_XSS($_GET['session_id']),'group_id'=>Security::remove_XSS($_GET['group_id'])));
-    $table->set_header(0,get_lang('Title'), true);
-    $table->display();
-}
-
-/* Orphaned pages */
-
-if ($action =='orphaned') {
-    echo '<div class="actions">'.get_lang('OrphanedPages').'</div>';
-
-    $pages = array();
-    $refs = array();
-	$list_refs = array();
-    $orphaned = array();
-
-    //get name pages
-    $sql = 'SELECT * FROM '.$tbl_wiki.'
-            WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
-            GROUP BY reflink
-            ORDER BY reflink ASC';
-    $allpages=Database::query($sql);
-    while ($row=Database::fetch_array($allpages)) {
-        $pages[] = $row['reflink'];
-    }
-
-    //get name refs in last pages and make a unique list
-    $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1
-    		WHERE s1.c_id = '.$course_id.' AND id=(
-    		SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2 WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.')';
-
-    $allpages=Database::query($sql);
-    while ($row=Database::fetch_array($allpages)) {
-        $row['linksto']= str_replace($row["reflink"], " ", trim($row["linksto"])); //remove self reference
-		$refs = explode(" ", trim($row["linksto"]));
-		foreach ($refs as $ref_linked){
-			if ($ref_linked==str_replace(' ','_',get_lang('DefaultTitle'))) {
-				$ref_linked='index';
-			}
-			$array_refs_linked[]= $ref_linked;
-		}
-    }
-
-	$array_refs_linked = array_unique($array_refs_linked);
-
-    //search each name of list linksto into list reflink
-    foreach ($pages as $v) {
-        if (!in_array($v, $array_refs_linked)) {
-            $orphaned[] = $v;
-        }
-    }
-
-    foreach ($orphaned as $orphaned_show) {
-		// get visibility status and title
-		$sql = 'SELECT  *  FROM   '.$tbl_wiki.'
-		        WHERE c_id = '.$course_id.' AND '.$groupfilter.$condition_session.' AND reflink="'.Database::escape_string($orphaned_show).'" GROUP BY reflink';
-        $allpages=Database::query($sql);
-		while ($row=Database::fetch_array($allpages)) {
-			$orphaned_title=$row['title'];
-			$orphaned_visibility=$row['visibility'];
-			if ($row['assignment']==1) {
-                $ShowAssignment=Display::return_icon('wiki_assignment.png','','',ICON_SIZE_SMALL);
-            } elseif ($row['assignment']==2) {
-                $ShowAssignment=Display::return_icon('wiki_work.png','','',ICON_SIZE_SMALL);
-            } elseif ($row['assignment']==0) {
-                $ShowAssignment='<img src="../img/px_transparent.gif" />';
-            }
-		}
-		if (!api_is_allowed_to_edit(false,true) || !api_is_platform_admin() AND $orphaned_visibility==0){
-			continue;
-		}
-
-		//show table
-        $row = array();
-			$row[] = $ShowAssignment;
-            $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=showpage&title='.api_htmlentities(urlencode($orphaned_show)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.api_htmlentities($orphaned_title).'</a>';
-            $rows[] = $row;
-        }
-
-        $table = new SortableTableFromArrayConfig($rows,1,10,'OrphanedPages_table','','','DESC');
-        $table->set_additional_parameters(array('cidReq' =>Security::remove_XSS($_GET['cidReq']),'action'=>Security::remove_XSS($action ),'session_id'=>Security::remove_XSS($_GET['session_id']),'group_id'=>Security::remove_XSS($_GET['group_id'])));
-        $table->set_header(0,get_lang('Type'), true, array ('style' => 'width:30px;'));
-        $table->set_header(1,get_lang('Title'), true);
-        $table->display();
-}
-
-/* Most linked pages */
-
-if ($action =='mostlinked') {
-    echo '<div class="actions">'.get_lang('MostLinkedPages').'</div>';
-	$pages = array();
-    $refs = array();
-	$linked = array();
-
-    //get name pages
-    $sql = 'SELECT * FROM '.$tbl_wiki.'
-            WHERE  c_id = '.$course_id.' AND '.$groupfilter.$condition_session.'
-            GROUP BY reflink ORDER BY reflink ASC';
-    $allpages=Database::query($sql);
+ob_start();
+$wiki->handleAction($action);
+$content = ob_get_contents();
+ob_end_clean();
 
-    while ($row=Database::fetch_array($allpages)) {
-		if ($row['reflink']=='index') {
-			$row['reflink']=str_replace(' ','_',get_lang('DefaultTitle'));
-		}
-		$pages[] = $row['reflink'];
-    }
-
-    //get name refs in last pages
-    $sql = 'SELECT  *  FROM   '.$tbl_wiki.' s1 WHERE s1.c_id = '.$course_id.' AND id=(
-            SELECT MAX(s2.id) FROM '.$tbl_wiki.' s2 WHERE s2.c_id = '.$course_id.' AND s1.reflink = s2.reflink AND '.$groupfilter.$condition_session.')';
-
-    $allpages=Database::query($sql);
-
-    while ($row=Database::fetch_array($allpages)) {
-	 	$row['linksto']= str_replace($row["reflink"], " ", trim($row["linksto"])); //remove self reference
-        $refs = explode(" ", trim($row["linksto"]));
-
-		// Find linksto into reflink. If found ->page is linked
-		foreach ($refs as $v) {
-			if (in_array($v, $pages)) {
-				if (trim($v)!="") {
-					$linked[]=$v;
-				}
-			}
-		}
-	}
-
-	$linked = array_unique($linked);
-	//make a unique list. TODO:delete this line and count how many for each page
-    //show table
-    $rows = array();
-    foreach ($linked as $linked_show) {
-        $row = array();
-        $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=showpage&title='.api_htmlentities(urlencode(str_replace('_',' ',$linked_show))).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.str_replace('_',' ',$linked_show).'</a>';
-        $rows[] = $row;
-    }
-
-    $table = new SortableTableFromArrayConfig($rows,0,10,'LinkedPages_table','','','DESC');
-    $table->set_additional_parameters(
-        array(
-            'cidReq' =>Security::remove_XSS($_GET['cidReq']),
-            'action'=>Security::remove_XSS($action ),
-            'session_id'=>Security::remove_XSS($_GET['session_id']),
-            'group_id'=>Security::remove_XSS($_GET['group_id'])
-        )
-    );
-    $table->set_header(0,get_lang('Title'), true);
-    $table->display();
-}
-
-/* Delete current page */
-
-if ($action =='delete') {
-    if (!$_GET['title']) {
-        Display::display_error_message(get_lang('MustSelectPage'));
-        exit;
-    }
-
-    if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-        echo '<div id="wikititle">'.get_lang('DeletePageHistory').'</div>';
-
-        if ($page == "index") {
-            Display::display_warning_message(get_lang('WarningDeleteMainPage'),false);
-        }
-
-        $message = get_lang('ConfirmDeletePage')."</p>"."<p>"."<a href=\"index.php\">".get_lang("No")."</a>"."&nbsp;&nbsp;|&nbsp;&nbsp;"."<a href=\"".api_get_self()."?action=delete&amp;title=".api_htmlentities(urlencode($page))."&amp;delete=yes\">".get_lang("Yes")."</a>"."</p>";
-
-        if (!isset ($_GET['delete'])) {
-            Display::display_warning_message($message,false);
-        }
-
-        if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
-            $result = $wiki->deletePage($page, $course_id, $groupfilter, $condition_session);
-            if ($result) {
-                Display::display_confirmation_message(get_lang('WikiPageDeleted'));
-            }
-        }
-    } else {
-        Display::display_normal_message(get_lang("OnlyAdminDeletePageWiki"));
-    }
-}
-
-/* Delete all wiki */
-
-if ($action =='deletewiki') {
-    echo '<div class="actions">'.get_lang('DeleteWiki').'</div>';
-    echo '<div style="overflow:hidden">';
-    if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-        $message = 	get_lang('ConfirmDeleteWiki');
-        $message .= '<p>
-                        <a href="index.php">'.get_lang('No').'</a>
-                        &nbsp;&nbsp;|&nbsp;&nbsp;
-                        <a href="'.api_get_self().'?action=deletewiki&amp;delete=yes">'.get_lang('Yes').'</a>
-                    </p>';
-
-        if (!isset($_GET['delete'])) {
-            Display::display_warning_message($message,false);
-        }
-    } else {
-        Display::display_normal_message(get_lang("OnlyAdminDeleteWiki"));
-    }
-    echo '</div>';
-}
-
-/* Search wiki pages */
-
-if ($action =='searchpages') {
-    echo '<div class="actions">'.get_lang('SearchPages').'</div>';
-	if (isset($_GET['mode_table'])) {
-		if (!isset($_GET['SearchPages_table_page_nr'])) {
-			$_GET['search_term'] = $_POST['search_term'];
-			$_GET['search_content'] = $_POST['search_content'];
-			$_GET['all_vers'] = $_POST['all_vers'];
-		}
-		$wiki->display_wiki_search_results(
-            api_htmlentities($_GET['search_term']),
-            api_htmlentities($_GET['search_content']),
-            api_htmlentities($_GET['all_vers'])
-        );
-	} else {
-
-		// initiate the object
-		$form = new FormValidator('wiki_search',
-            'post',
-            api_get_self().'?cidReq='.api_htmlentities($_GET['cidReq']).'&action='.api_htmlentities($action).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'&mode_table=yes1&search_term='.api_htmlentities($_GET['search_term']).'&search_content='.api_htmlentities($_GET['search_content']).'&all_vers='.api_htmlentities($_GET['all_vers'])
-        );
-
-		// Setting the form elements
-
-		$form->addElement('text', 'search_term', get_lang('SearchTerm'),'class="input_titles" id="search_title"');
-		$form->addElement('checkbox', 'search_content', null, get_lang('AlsoSearchContent'));
-		$form->addElement('checkbox', 'all_vers', null, get_lang('IncludeAllVersions'));
-		$form->addElement('style_submit_button', 'SubmitWikiSearch', get_lang('Search'), 'class="search"');
-
-		// setting the rules
-		$form->addRule('search_term', get_lang('ThisFieldIsRequired'), 'required');
-		$form->addRule('search_term', get_lang('TooShort'),'minlength',3); //TODO: before fixing the pagination rules worked, not now
-		if ($form->validate()) {
-			$form->display();
-			$values = $form->exportValues();
-			$wiki->display_wiki_search_results(
-                $values['search_term'],
-                $values['search_content'],
-                $values['all_vers']
-            );
-		} else {
-			$form->display();
-		}
-	}
-}
-
-/* What links here. Show pages that have linked this page */
-
-if ($action =='links') {
-    if (!$_GET['title']) {
-        Display::display_error_message(get_lang("MustSelectPage"));
-    } else {
-        $sql = 'SELECT * FROM '.$tbl_wiki.'
-                WHERE
-                    c_id = '.$course_id.' AND
-                    reflink="'.Database::escape_string($page).'" AND
-                    '.$groupfilter.$condition_session.'';
-        $result = Database::query($sql);
-        $row = Database::fetch_array($result);
-
-        //get type assignment icon
-
-        if ($row['assignment']==1) {
-            $ShowAssignment=Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'),'',ICON_SIZE_SMALL);
-        } elseif ($row['assignment']==2) {
-            $ShowAssignment=Display::return_icon('wiki_work.png', get_lang('AssignmentWork'),'',ICON_SIZE_SMALL);
-        } elseif ($row['assignment']==0) {
-            $ShowAssignment='<img src="../img/px_transparent.gif" />';
-        }
-
-        //fix Title to reflink (link Main Page)
-
-        if ($page==get_lang('DefaultTitle')) {
-            $page='index';
-        }
-
-        echo '<div id="wikititle">';
-        echo get_lang('LinksPagesFrom').': '.$ShowAssignment.' <a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=showpage&title='.api_htmlentities(urlencode($page)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.api_htmlentities($row['title']).'</a>';
-        echo '</div>';
-
-        //fix index to title Main page into linksto
-
-        if ($page=='index') {
-            $page=str_replace(' ','_',get_lang('DefaultTitle'));
-        }
-
-        //table
-        if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) { //only by professors if page is hidden
-			$sql="SELECT * FROM ".$tbl_wiki." s1 WHERE s1.c_id = $course_id AND linksto LIKE '%".Database::escape_string($page)." %' AND id=(SELECT MAX(s2.id) FROM ".$tbl_wiki." s2 WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";//add blank space after like '%" " %' to identify each word
-        } else {
-            $sql="SELECT * FROM ".$tbl_wiki." s1 WHERE s1.c_id = $course_id AND visibility=1 AND linksto LIKE '%".Database::escape_string($page)." %' AND id=(SELECT MAX(s2.id) FROM ".$tbl_wiki." s2 WHERE s2.c_id = $course_id AND s1.reflink = s2.reflink AND ".$groupfilter.$condition_session.")";//add blank space after like '%" " %' to identify each word
-        }
-
-        $allpages=Database::query($sql);
-
-        //show table
-        if (Database::num_rows($allpages) > 0) {
-            $row = array ();
-            while ($obj = Database::fetch_object($allpages)) {
-                //get author
-                $userinfo = api_get_user_info($obj->user_id);
-                $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username']), ENT_QUOTES);
-
-                //get time
-                $year 	 = substr($obj->dtime, 0, 4);
-                $month	 = substr($obj->dtime, 5, 2);
-                $day 	 = substr($obj->dtime, 8, 2);
-                $hours   = substr($obj->dtime, 11,2);
-                $minutes = substr($obj->dtime, 14,2);
-                $seconds = substr($obj->dtime, 17,2);
-
-                //get type assignment icon
-                if ($obj->assignment==1) {
-                    $ShowAssignment=Display::return_icon('wiki_assignment.png', get_lang('AssignmentDesc'),'',ICON_SIZE_SMALL);
-                } elseif ($obj->assignment==2) {
-                    $ShowAssignment=Display::return_icon('wiki_work.png', get_lang('AssignmentWork'),'',ICON_SIZE_SMALL);
-                } elseif ($obj->assignment==0) {
-                    $ShowAssignment='<img src="../img/px_transparent.gif" />';
-                }
-
-                $row = array ();
-                $row[] =$ShowAssignment;
-                $row[] = '<a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=showpage&title='.api_htmlentities(urlencode($obj->reflink)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">'.api_htmlentities($obj->title).'</a>';
-                if ($obj->user_id <>0) {
-                    $row[] = '<a href="../user/userInfo.php?uInfo='.$userinfo['user_id'].'">'.
-                    Display::tag('span', api_htmlentities(api_get_person_name($userinfo['firstname'], $userinfo['lastname'])), array('title'=>$username)).'</a>';
-                }
-                else {
-                    $row[] = get_lang('Anonymous').' ('.$obj->user_ip.')';
-                }
-                $row[] = $year.'-'.$month.'-'.$day.' '.$hours.":".$minutes.":".$seconds;
-                $rows[] = $row;
-            }
-
-            $table = new SortableTableFromArrayConfig($rows,1,10,'AllPages_table','','','ASC');
-            $table->set_additional_parameters(array('cidReq' =>Security::remove_XSS($_GET['cidReq']),'action'=>Security::remove_XSS($action ),'group_id'=>Security::remove_XSS($_GET['group_id'])));
-            $table->set_header(0,get_lang('Type'), true, array ('style' => 'width:30px;'));
-            $table->set_header(1,get_lang('Title'), true);
-            $table->set_header(2,get_lang('Author'), true);
-            $table->set_header(3,get_lang('Date'), true);
-            $table->display();
-        }
-    }
-}
-
-// Adding a new page
-// Display the form for adding a new wiki page
-
-if ($action =='addnew') {
-    if (api_get_session_id()!=0 && api_is_allowed_to_session_edit(false,true)==false) {
-        api_not_allowed();
-    }
-
-    echo '<div class="actions">'.get_lang('AddNew').'</div>';
-	echo '<br/>';
-    //first, check if page index was created. chektitle=false
-    if ($wiki->checktitle('index')) {
-        if (api_is_allowed_to_edit(false,true) || api_is_platform_admin() || GroupManager :: is_user_in_group($_user['user_id'],$_SESSION['_gid'])) {
-            Display::display_normal_message(get_lang('GoAndEditMainPage'));
-        } else {
-            return Display::display_normal_message(get_lang('WikiStandBy'));
-        }
-    } elseif ($wiki->check_addnewpagelock()==0 && (api_is_allowed_to_edit(false,true)==false || api_is_platform_admin()==false)) {
-        Display::display_error_message(get_lang('AddPagesLocked'));
-    } else {
-        if(api_is_allowed_to_edit(false,true) || api_is_platform_admin() || GroupManager :: is_user_in_group($_user['user_id'],$_SESSION['_gid']) || Security::remove_XSS($_GET['group_id'])==0) {
-            $wiki->display_new_wiki_form();
-        } else {
-            Display::display_normal_message(get_lang('OnlyAddPagesGroupMembers'));
-        }
-    }
-}
-
-// Show home page
-if (!$action  OR $action =='show' AND !isset($_POST['SaveWikiNew'])) {
-    $wiki->display_wiki_entry($newtitle);
-}
-
-// Show current page
-if ($action =='showpage' AND !isset($_POST['SaveWikiNew'])) {
-    if ($_GET['title']) {
-        $wiki->display_wiki_entry($newtitle);
-    } else {
-        Display::display_error_message(get_lang('MustSelectPage'));
-    }
-}
-
-// Edit current page
-
-if (isset($action) && $action =='edit') {
-
-    if (api_get_session_id()!=0 && api_is_allowed_to_session_edit(false,true)==false) {
-        api_not_allowed();
-    }
-
-    $sql = 'SELECT * FROM '.$tbl_wiki.', '.$tbl_wiki_conf.'
-    		WHERE
-    		'.$tbl_wiki.'.c_id = '.$course_id.' AND
-    		'.$tbl_wiki_conf.'.c_id = '.$course_id.' AND
-    		'.$tbl_wiki_conf.'.page_id='.$tbl_wiki.'.page_id AND
-    		'.$tbl_wiki.'.reflink="'.Database::escape_string($page).'" AND
-    		'.$tbl_wiki.'.'.$groupfilter.$condition_session.'
-    		ORDER BY id DESC';
-    $result=Database::query($sql);
-    $row=Database::fetch_array($result); // we do not need a while loop since we are always displaying the last version
-
-
-    if ($row['content']=='' AND $row['title']=='' AND $page=='') {
-        Display::display_error_message(get_lang('MustSelectPage'));
-        exit;
-    } elseif ($row['content']=='' AND $row['title']=='' AND $page=='index') {
-        //Table structure for better export to pdf
-        $default_table_for_content_Start='<table align="center" border="0"><tr><td align="center">';
-        $default_table_for_content_End='</td></tr></table>';
-
-        $content=$default_table_for_content_Start.sprintf(get_lang('DefaultContent'),api_get_path(WEB_IMG_PATH)).$default_table_for_content_End;
-        $title=get_lang('DefaultTitle');
-        $page_id=0;
-    } else {
-        $content = api_html_entity_decode($row['content']);
-        $title = api_html_entity_decode($row['title']);
-        $page_id = $row['page_id'];
-    }
-
-    //Only teachers and platform admin can edit the index page. Only teachers and platform admin can edit an assignment teacher. And users in groups
-    if (($row['reflink']=='index' || $row['reflink']=='' || $row['assignment']==1) && (!api_is_allowed_to_edit(false,true) && intval($_GET['group_id'])==0)) {
-        Display::display_error_message(get_lang('OnlyEditPagesCourseManager'));
-    } else {
-        $PassEdit=false;
-
-        //check if is a wiki group
-        if ($groupId!=0) {
-            //Only teacher, platform admin and group members can edit a wiki group
-            if (api_is_allowed_to_edit(false,true) || api_is_platform_admin() || GroupManager :: is_user_in_group($_user['user_id'],intval($_GET['group_id']))) {
-                $PassEdit=true;
-            } else {
-                  Display::display_normal_message(get_lang('OnlyEditPagesGroupMembers'));
-            }
-        } else {
-            $PassEdit=true;
-        }
-        $icon_assignment = null;
-        // check if is a assignment
-        if ($row['assignment']==1) {
-            Display::display_normal_message(get_lang('EditAssignmentWarning'));
-            $icon_assignment=Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'),'',ICON_SIZE_SMALL);
-        } elseif ($row['assignment']==2) {
-            $icon_assignment=Display::return_icon('wiki_work.png', get_lang('AssignmentWorkExtra'),'',ICON_SIZE_SMALL);
-            if ((api_get_user_id()==$row['user_id'])==false) {
-                if (api_is_allowed_to_edit(false,true) || api_is_platform_admin()) {
-                    $PassEdit=true;
-                } else {
-                    Display::display_warning_message(get_lang('LockByTeacher'));
-                    $PassEdit=false;
-                }
-            } else {
-                $PassEdit=true;
-            }
-        }
-
-         if ($PassEdit) { //show editor if edit is allowed
-             if ($row['editlock']==1 && (api_is_allowed_to_edit(false,true)==false || api_is_platform_admin()==false)) {
-                   Display::display_normal_message(get_lang('PageLockedExtra'));
-            } else {
-                //check tasks
-                if (!empty($row['startdate_assig']) && $row['startdate_assig']!='0000-00-00 00:00:00' && time()<strtotime($row['startdate_assig'])) {
-                    $message=get_lang('TheTaskDoesNotBeginUntil').': '.api_get_local_time($row['startdate_assig'], null, date_default_timezone_get());
-                    Display::display_warning_message($message);
-                    if (!api_is_allowed_to_edit(false,true)) {
-                        exit;
-                    }
-                }
-
-                //
-                if (!empty($row['enddate_assig']) && $row['enddate_assig']!='0000-00-00 00:00:00' && time()>strtotime($row['enddate_assig']) && $row['enddate_assig']!='0000-00-00 00:00:00' && $row['delayedsubmit']==0) {
-                    $message=get_lang('TheDeadlineHasBeenCompleted').': '.api_get_local_time($row['enddate_assig'], null, date_default_timezone_get());
-                    Display::display_warning_message($message);
-                    if (!api_is_allowed_to_edit(false,true)) {
-                        exit;
-                    }
-                }
-
-                if (!empty($row['max_version']) && $row['version']>=$row['max_version']) {
-                    $message=get_lang('HasReachedMaxiNumVersions');
-                    Display::display_warning_message($message);
-                    if (!api_is_allowed_to_edit(false,true)) {
-                        exit;
-                    }
-                }
-
-                if (!empty($row['max_text']) && $row['max_text']<=$wiki->word_count($row['content'])) {
-                    $message=get_lang('HasReachedMaxNumWords');
-                    Display::display_warning_message($message);
-                    if (!api_is_allowed_to_edit(false,true)) {
-                        exit;
-                    }
-                }
-
-                if (!empty($row['task'])) {
-                    //previous change 0 by text
-                    if ($row['startdate_assig']=='0000-00-00 00:00:00') {
-                        $message_task_startdate=get_lang('No');
-                    } else {
-                        $message_task_startdate=api_get_local_time($row['startdate_assig'], null, date_default_timezone_get());
-                    }
-
-                    if ($row['enddate_assig']=='0000-00-00 00:00:00') {
-                        $message_task_enddate=get_lang('No');
-                    } else {
-                        $message_task_endate=api_get_local_time($row['enddate_assig'], null, date_default_timezone_get());
-                    }
-
-                    if ($row['delayedsubmit']==0) {
-                        $message_task_delayedsubmit=get_lang('No');
-                    } else {
-                        $message_task_delayedsubmit=get_lang('Yes');
-                    }
-                    if ($row['max_version']==0) {
-                        $message_task_max_version=get_lang('No');
-                    } else {
-                        $message_task_max_version=$row['max_version'];
-                    }
-                    if ($row['max_text']==0) {
-                        $message_task_max_text=get_lang('No');
-                    } else {
-                        $message_task_max_text=$row['max_text'];
-                    }
-
-                    //comp message
-                    $message_task='<b>'.get_lang('DescriptionOfTheTask').'</b><p>'.$row['task'].'</p><hr>';
-                    $message_task.='<p>'.get_lang('StartDate').': '.$message_task_startdate.'</p>';
-                    $message_task.='<p>'.get_lang('EndDate').': '.$message_task_enddate;
-                    $message_task.=' ('.get_lang('AllowLaterSends').') '.$message_task_delayedsubmit.'</p>';
-                    $message_task.='<p>'.get_lang('OtherSettings').': '.get_lang('NMaxVersion').': '.$message_task_max_version;
-                    $message_task.=' '.get_lang('NMaxWords').': '.$message_task_max_text;
-                    //display message
-                    Display::display_normal_message($message_task,false);
-                }
-
-                if ($row['progress']==$row['fprogress1'] && !empty($row['fprogress1'])) {
-                    $feedback_message='<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback1']).'</p>';
-                    Display::display_normal_message($feedback_message, false);
-                } elseif ($row['progress']==$row['fprogress2'] && !empty($row['fprogress2'])) {
-                    $feedback_message='<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback2']).'</p>';
-                    Display::display_normal_message($feedback_message, false);
-                } elseif ($row['progress']==$row['fprogress3'] && !empty($row['fprogress3'])) {
-                    $feedback_message='<b>'.get_lang('Feedback').'</b><p>'.api_htmlentities($row['feedback3']).'</p>';
-                    Display::display_normal_message($feedback_message, false);
-                }
-
-                //previous checking for concurrent editions
-                if ($row['is_editing']==0) {
-                    Display::display_normal_message(get_lang('WarningMaxEditingTime'));
-
-                    $time_edit = date("Y-m-d H:i:s");
-                    $sql='UPDATE '.$tbl_wiki.' SET is_editing="'.$_user['user_id'].'", time_edit="'.$time_edit.'" WHERE c_id = '.$course_id.' AND  id="'.$row['id'].'"';
-                    Database::query($sql);
-                } elseif ($row['is_editing']!=$_user['user_id']) {
-                    $timestamp_edit=strtotime($row['time_edit']);
-                    $time_editing=time()-$timestamp_edit;
-                    $max_edit_time=1200; // 20 minutes
-                    $rest_time=$max_edit_time-$time_editing;
-
-                    $userinfo = api_get_user_info($row['is_editing']);
-                    $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username']), ENT_QUOTES);
-
-                    $is_being_edited= get_lang('ThisPageisBeginEditedBy').
-                    ' <a href=../user/userInfo.php?uInfo='.
-                    $userinfo['user_id'].'>'.
-                    Display::tag('span', api_htmlentities(api_get_person_name($userinfo['firstname'], $userinfo['lastname'])), array('title'=>$username)).
-                    '</a>. '.get_lang('ThisPageisBeginEditedTryLater').' '.date( "i",$rest_time).' '.get_lang('MinMinutes').'';
-                    Display::display_normal_message($is_being_edited, false);
-                    exit;
-                }
-
-                // Form.
-                echo '<div id="wikititle">'.$icon_assignment.str_repeat('&nbsp;',3).api_htmlentities($title).'</div>';
-                echo '<form name="form1" method="post" action="'.api_get_self().'?action=showpage&amp;title='.api_htmlentities(urlencode($page)).'&session_id='.api_htmlentities($_GET['session_id']).'&group_id='.api_htmlentities($_GET['group_id']).'">';
-
-                if ((api_is_allowed_to_edit(false,true) || api_is_platform_admin()) && $row['reflink'] != 'index') {
-                    echo '<a href="javascript://" onclick="advanced_parameters()" >
-                         <div id="plus_minus">&nbsp;'.
-                        Display::return_icon(
-                            'div_show.gif',
-                            get_lang('Show'),
-                            array('style'=>'vertical-align:middle')
-                        ).'&nbsp;'.get_lang('AdvancedParameters').'</div></a>';
-
-                    echo '<div id="options" style="display:none; margin: 20px;" >';
-
-                    // Task
-                    echo '<input type="checkbox" value="1" name="checktask" onclick="javascript: if(this.checked){document.getElementById(\'option4\').style.display=\'block\';}else{document.getElementById(\'option4\').style.display=\'none\';}"/>&nbsp;'.Display::return_icon('wiki_task.png', get_lang('DefineTask'),'',ICON_SIZE_SMALL).' '.get_lang('DescriptionOfTheTask').'';
-                    echo '&nbsp;&nbsp;&nbsp;<span id="msg_error4" style="display:none;color:red"></span>';
-                    echo '<div id="option4" style="padding:4px; margin:5px; border:1px dotted; display:none;">';
-                    echo '<table>';
-                    echo '<tr>';
-                    echo '<td>'.get_lang('DescriptionOfTheTask').'</td>';
-                    echo '</tr>';
-                    echo '<tr>';
-                    echo '<td>'.api_disp_html_area('task', $row['task'], '', '', null, array('ToolbarSet' => 'wiki_task', 'Width' => '100%', 'Height' => '200')).'</td>';
-                    echo '</tr>';
-                    echo '</table>';
-                    echo '</div>';
-
-                    // Feedback
-                    echo '<input type="checkbox" value="1" name="checkfeedback" onclick="javascript: if(this.checked){document.getElementById(\'option2\').style.display=\'block\';}else{document.getElementById(\'option2\').style.display=\'none\';}"/>&nbsp;'.get_lang('AddFeedback').'';
-                    echo '&nbsp;&nbsp;&nbsp;<span id="msg_error2" style="display:none;color:red"></span>';
-
-                    echo '<div id="option2" style="padding:4px; margin:5px; border:1px dotted; display:none;">';
-
-                    echo '<table border="0" style="font-weight:normal" align="center">';
-                    echo '<tr>';
-                    echo '<td colspan="2">'.get_lang('Feedback1').'</td>';
-                    echo '<td colspan="2">'.get_lang('Feedback2').'</td>';
-                    echo '<td colspan="2">'.get_lang('Feedback3').'</td>';
-                    echo '</tr>';
-                    echo '<tr>';
-                    echo '<td colspan="2"><textarea name="feedback1" cols="21" rows="4" >'.api_htmlentities($row['feedback1']).'</textarea></td>';
-                    echo '<td colspan="2"><textarea name="feedback2" cols="21" rows="4" >'.api_htmlentities($row['feedback2']).'</textarea></td>';
-                    echo '<td colspan="2"><textarea name="feedback3" cols="21" rows="4" >'.api_htmlentities($row['feedback3']).'</textarea></td>';
-                    echo '</tr>';
-                    echo '<tr>';
-                    echo '<td>'.get_lang('FProgress').':</td>';
-                    echo '<td><select name="fprogress1">';
-                     echo '<option value="'.api_htmlentities($row['fprogress1']).'" selected>'.api_htmlentities($row['fprogress1']).'</option>';
-                    echo '<option value="10">10</option>
-                       <option value="20">20</option>
-                       <option value="30">30</option>
-                       <option value="40">40</option>
-                       <option value="50">50</option>
-                       <option value="60">60</option>
-                       <option value="70">70</option>
-                       <option value="80">80</option>
-                       <option value="90">90</option>
-                       <option value="100">100</option>
-                       </select> %</td>';
-                    echo '<td>'.get_lang('FProgress').':</td>';
-                    echo '<td><select name="fprogress2">';
-                     echo '<option value="'.api_htmlentities($row['fprogress2']).'" selected>'.api_htmlentities($row['fprogress2']).'</option>';;
-                    echo '<option value="10">10</option>
-                       <option value="20">20</option>
-                       <option value="30">30</option>
-                       <option value="40">40</option>
-                       <option value="50">50</option>
-                       <option value="60">60</option>
-                       <option value="70">70</option>
-                       <option value="80">80</option>
-                       <option value="90">90</option>
-                       <option value="100">100</option>
-                       </select> %</td>';
-                    echo '<td>'.get_lang('FProgress').':</td>';
-                    echo '<td><select name="fprogress3">';
-                    echo '<option value="'.api_htmlentities($row['fprogress3']).'" selected>'.api_htmlentities($row['fprogress3']).'</option>';
-                    echo '<option value="10">10</option>
-                       <option value="20">20</option>
-                       <option value="30">30</option>
-                       <option value="40">40</option>
-                       <option value="50">50</option>
-                       <option value="60">60</option>
-                       <option value="70">70</option>
-                       <option value="80">80</option>
-                       <option value="90">90</option>
-                       <option value="100">100</option>
-                       </select> %</td>';
-                    echo '</tr>';
-                    echo '</table>';
-                    echo '</div>';
-
-                    //time limit
-                    echo  '<div>&nbsp;</div><input type="checkbox" value="1" name="checktimelimit" onclick="javascript: if(this.checked){document.getElementById(\'option1\').style.display=\'block\'; $pepe=\'a\';}else{document.getElementById(\'option1\').style.display=\'none\';}"/>&nbsp;'.get_lang('PutATimeLimit').'';
-                    echo  '&nbsp;&nbsp;&nbsp;<span id="msg_error1" style="display:none;color:red"></span>';
-                    echo  '<div id="option1" style="padding:4px; margin:5px; border:1px dotted; display:none;">';
-                    echo '<table width="100%" border="0" style="font-weight:normal">';
-                    echo '<tr>';
-                    echo '<td align="right" width="150">'.get_lang('StartDate').':</td>';
-                    echo '<td>';
-                    if ($row['startdate_assig']=='0000-00-00 00:00:00') {
-                        echo $wiki->draw_date_picker('startdate_assig').' <input type="checkbox" name="initstartdate" value="1"> '.get_lang('Yes').'/'.get_lang('No').'';
-                    } else {
-                        echo $wiki->draw_date_picker('startdate_assig', $row['startdate_assig']).' <input type="checkbox" name="initstartdate" value="1">'.get_lang('Yes').'/'.get_lang('No').'';
-                    }
-                    echo '</td>';
-                    echo '</tr>';
-                    echo '<tr>';
-                    echo '<td align="right" width="150">'.get_lang("EndDate").':</td>';
-                    echo '<td>';
-                    if ($row['enddate_assig']=='0000-00-00 00:00:00') {
-                        echo $wiki->draw_date_picker('enddate_assig').' <input type="checkbox" name="initenddate" value="1"> '.get_lang('Yes').'/'.get_lang('No').'';
-                    } else {
-                        echo $wiki->draw_date_picker('enddate_assig', $row['enddate_assig']).' <input type="checkbox" name="initenddate" value="1"> '.get_lang('Yes').'/'.get_lang('No').'';
-                    }
-                    echo '</td>';
-                    echo '</tr>';
-                    echo '<tr>';
-                    echo '<td align="right">'.get_lang('AllowLaterSends').':</td>';
-                    if ($row['delayedsubmit']==1) {
-                        $check_uncheck='checked';
-                    }
-                    echo '<td><input type="checkbox" name="delayedsubmit" value="1" '.$check_uncheck.'></td>';
-                    echo '</tr>';
-                    echo'</table>';
-                    echo '</div>';
-
-                    //other limit
-                    echo '<div>&nbsp;</div><input type="checkbox" value="1" name="checkotherlimit" onclick="javascript: if(this.checked){document.getElementById(\'option3\').style.display=\'block\';}else{document.getElementById(\'option3\').style.display=\'none\';}"/>&nbsp;'.get_lang('OtherSettings').'';
-                    echo '&nbsp;&nbsp;&nbsp;<span id="msg_error3" style="display:none;color:red"></span>';
-                    echo '<div id="option3" style="padding:4px; margin:5px; border:1px dotted; display:none;">';
-                    echo '<div style="font-weight:normal"; align="center">'.get_lang('NMaxWords').':&nbsp;<input type="text" name="max_text" size="3" value="'.$row['max_text'].'">&nbsp;&nbsp;'.get_lang('NMaxVersion').':&nbsp;<input type="text" name="max_version" size="3" value="'.$row['max_version'].'"></div>';
-                    echo '</div>';
-
-                    echo '</div>';
-                }
-
-                echo '<input type="hidden" name="page_id" value="'.$page_id.'">';
-                echo '<input type="hidden" name="reflink" value="'.api_htmlentities($page).'">';
-                echo '<input type="hidden" name="title" value="'.api_htmlentities($title).'">';
-
-                api_disp_html_area('content', $content, '', '', null, api_is_allowed_to_edit(null,true)
-                    ? array('ToolbarSet' => 'Wiki', 'Width' => '100%', 'Height' => '400')
-                    : array('ToolbarSet' => 'WikiStudent', 'Width' => '100%', 'Height' => '400', 'UserStatus' => 'student')
-                );
-                echo '<br/>';
-                echo '<br/>';
-
-                echo get_lang('Comments').':&nbsp;&nbsp;<input type="text" name="comment" size="40">&nbsp;&nbsp;&nbsp;';
-                echo '<input TYPE="hidden" NAME="assignment" VALUE="'.$row['assignment'].'"/>';
-                echo '<input TYPE="hidden" NAME="version" VALUE="'.$row['version'].'"/>';
-
-                //hack date for edit
-                echo '<input TYPE="hidden" NAME="startdate_assig" VALUE="'.$row['startdate_assig'].'"/>';
-                echo '<input TYPE="hidden" NAME="enddate_assig" VALUE="'.$row['enddate_assig'].'"/>';
-
-                echo get_lang('Progress').':&nbsp;&nbsp;<select name="progress" id="progress">';
-                echo '<option value="'.api_htmlentities($row['progress']).'" selected>'.api_htmlentities($row['progress']).'</option>';
-                echo '<option value="10">10</option>
-                <option value="20">20</option>
-                <option value="30">30</option>
-                <option value="40">40</option>
-                <option value="50">50</option>
-                <option value="60">60</option>
-                <option value="70">70</option>
-                <option value="80">80</option>
-                <option value="90">90</option>
-                <option value="100">100</option>
-                </select> %';
-                echo '<br/><br/>';
-                echo '<input type="hidden" name="wpost_id" value="'.md5(uniqid(rand(), true)).'">';//prevent double post
-                 //for save button Don't change name (see fckeditor/editor/plugins/customizations/fckplugin_compressed.js and fckplugin.js
-                echo '<button class="save" type="submit" name="SaveWikiChange">'.get_lang('Save').'</button>';
-                echo '</form>';
-            }
-        }
-    }
-}
-
-// Page history
-
-if ($action == 'history' or isset($_POST['HistoryDifferences'])) {
-    if (!$_GET['title']) {
-        Display::display_error_message(get_lang("MustSelectPage"));
-        exit;
-    }
-
-    /* First, see the property visibility that is at the last register and
-    therefore we should select descending order.
-    But to give ownership to each record,
-    this is no longer necessary except for the title. TODO: check this*/
-
-    $sql = 'SELECT * FROM '.$tbl_wiki.'
-            WHERE c_id = '.$course_id.' AND reflink="'.Database::escape_string($page).'" AND '.$groupfilter.$condition_session.'
-            ORDER BY id DESC';
-    $result=Database::query($sql);
-
-    $KeyVisibility = null;
-    $KeyAssignment = null;
-    $KeyTitle = null;
-    $KeyUserId = null;
-    while ($row=Database::fetch_array($result)) {
-        $KeyVisibility = $row['visibility'];
-        $KeyAssignment = $row['assignment'];
-        $KeyTitle = $row['title'];
-        $KeyUserId = $row['user_id'];
-    }
-    $icon_assignment = null;
-    if ($KeyAssignment == 1) {
-        $icon_assignment = Display::return_icon('wiki_assignment.png', get_lang('AssignmentDescExtra'), '', ICON_SIZE_SMALL);
-    } elseif($KeyAssignment == 2) {
-        $icon_assignment = Display::return_icon('wiki_work.png', get_lang('AssignmentWorkExtra'), '', ICON_SIZE_SMALL);
-    }
-
-    // Second, show
-
-    //if the page is hidden and is a job only sees its author and professor
-    if ($KeyVisibility == 1 ||
-        api_is_allowed_to_edit(false,true) ||
-        api_is_platform_admin() ||
-        (
-            $KeyAssignment==2 && $KeyVisibility==0 &&
-            (api_get_user_id() == $KeyUserId)
-        )
-    ) {
-        // We show the complete history
-        if (!isset($_POST['HistoryDifferences']) && !isset($_POST['HistoryDifferences2'])) {
-            $sql = 'SELECT * FROM '.$tbl_wiki.'
-                    WHERE
-                        c_id = '.$course_id.' AND
-                        reflink="'.Database::escape_string($page).'" AND
-                        '.$groupfilter.$condition_session.'
-                    ORDER BY id DESC';
-            $result = Database::query($sql);
-            $title		= $_GET['title'];
-            $group_id	= $_GET['group_id'];
-
-            echo '<div id="wikititle">';
-            echo $icon_assignment.'&nbsp;&nbsp;&nbsp;'.api_htmlentities($KeyTitle);
-            echo '</div>';
-
-            echo '<form id="differences" method="POST" action="index.php?cidReq='.$_course['id'].'&action=history&title='.api_htmlentities(urlencode($title)).'&session_id='.api_htmlentities($session_id).'&group_id='.api_htmlentities($group_id).'">';
-
-            echo '<ul style="list-style-type: none;">';
-            echo '<br/>';
-            echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang('ShowDifferences').' '.get_lang('LinesDiff').'</button>';
-            echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang('ShowDifferences').' '.get_lang('WordsDiff').'</button>';
-            echo '<br/><br/>';
-
-            $counter=0;
-            $total_versions=Database::num_rows($result);
-
-            while ($row=Database::fetch_array($result)) {
-                $userinfo = api_get_user_info($row['user_id']);
-                $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username']), ENT_QUOTES);
-
-                echo '<li style="margin-bottom: 5px;">';
-                ($counter==0) ? $oldstyle='style="visibility: hidden;"':$oldstyle='';
-                ($counter==0) ? $newchecked=' checked':$newchecked='';
-                ($counter==$total_versions-1) ? $newstyle='style="visibility: hidden;"':$newstyle='';
-                ($counter==1) ? $oldchecked=' checked':$oldchecked='';
-                echo '<input name="old" value="'.$row['id'].'" type="radio" '.$oldstyle.' '.$oldchecked.'/> ';
-                echo '<input name="new" value="'.$row['id'].'" type="radio" '.$newstyle.' '.$newchecked.'/> ';
-                echo '<a href="'.api_get_self().'?action=showpage&amp;title='.api_htmlentities(urlencode($page)).'&amp;view='.$row['id'].'">';
-                echo '<a href="'.api_get_self().'?cidReq='.$_course['id'].'&action=showpage&amp;title='.api_htmlentities(urlencode($page)).'&amp;view='.$row['id'].'&session_id='.$session_id.'&group_id='.$group_id.'">';
-
-                echo api_get_local_time($row['dtime'], null, date_default_timezone_get());
-                echo '</a>';
-                echo ' ('.get_lang('Version').' '.$row['version'].')';
-                echo ' '.get_lang('By').' ';
-                if ($row['user_id']<>0) {
-                    echo '<a href="../user/userInfo.php?uInfo='.$userinfo['user_id'].'">'.
-                    Display::tag('span', api_htmlentities(api_get_person_name($userinfo['firstname'], $userinfo['lastname'])), array('title'=>$username)).
-                    '</a>';
-                } else {
-                    echo get_lang('Anonymous').' ('.api_htmlentities($row['user_ip']).')';
-                }
-                echo ' ( '.get_lang('Progress').': '.api_htmlentities($row['progress']).'%, ';
-                $comment = $row['comment'];
-                if (!empty($comment)) {
-                    echo get_lang('Comments').': '.api_htmlentities(api_substr($row['comment'],0,100));
-                    if (api_strlen($row['comment'])>100) {
-                        echo '... ';
-                    }
-                } else {
-                    echo get_lang('Comments').':  ---';
-                }
-                echo ' ) </li>';
-                $counter++;
-            } //end while
-
-            echo '<br/>';
-            echo '<button class="search" type="submit" name="HistoryDifferences" value="HistoryDifferences">'.get_lang('ShowDifferences').' '.get_lang('LinesDiff').'</button>';
-            echo '<button class="search" type="submit" name="HistoryDifferences2" value="HistoryDifferences2">'.get_lang('ShowDifferences').' '.get_lang('WordsDiff').'</button>';
-            echo '</ul></form>';
-        } else { // We show the differences between two versions
-            $version_old = array();
-            if (isset($_POST['old'])) {
-                $sql_old= "SELECT * FROM $tbl_wiki
-                           WHERE c_id = $course_id AND id='".Database::escape_string($_POST['old'])."'";
-                $result_old=Database::query($sql_old);
-                $version_old=Database::fetch_array($result_old);
-            }
-
-            $sql_new="SELECT * FROM $tbl_wiki WHERE c_id = $course_id AND id='".Database::escape_string($_POST['new'])."'";
-            $result_new=Database::query($sql_new);
-            $version_new=Database::fetch_array($result_new);
-            $oldTime = isset($version_old['dtime']) ? $version_old['dtime'] : null;
-            $oldContent = isset($version_old['content']) ? $version_old['content'] : null;
-
-            if (isset($_POST['HistoryDifferences'])) {
-                include 'diff.inc.php';
-                //title
-                echo '<div id="wikititle">'.api_htmlentities($version_new['title']).'
-                <font size="-2"><i>('.get_lang('DifferencesNew').'</i>
-                    <font style="background-color:#aaaaaa">'.$version_new['dtime'].'</font>
-                    <i>'.get_lang('DifferencesOld').'</i>
-                    <font style="background-color:#aaaaaa">'.$oldTime.'</font>
-                ) '.get_lang('Legend').':  <span class="diffAdded" >'.get_lang('WikiDiffAddedLine').'</span>
-                <span class="diffDeleted" >'.get_lang('WikiDiffDeletedLine').'</span> <span class="diffMoved">'.get_lang('WikiDiffMovedLine').'</span></font>
-                </div>';
-            }
-            if (isset($_POST['HistoryDifferences2'])) {
-                // including global PEAR diff libraries
-                require_once 'Text/Diff.php';
-                require_once 'Text/Diff/Renderer/inline.php';
-                //title
-                echo '<div id="wikititle">'.api_htmlentities($version_new['title']).'
-                <font size="-2"><i>('.get_lang('DifferencesNew').'</i> <font style="background-color:#aaaaaa">'.$version_new['dtime'].'</font>
-                <i>'.get_lang('DifferencesOld').'</i> <font style="background-color:#aaaaaa">'.$version_old['dtime'].'</font>)
-                '.get_lang('Legend').':  <span class="diffAddedTex" >'.get_lang('WikiDiffAddedTex').'</span>
-                <span class="diffDeletedTex" >'.get_lang('WikiDiffDeletedTex').'</span></font></div>';
-            }
-
-
-            if (isset($_POST['HistoryDifferences'])) {
-                echo '<table>'.diff($oldContent, $version_new['content'], true, 'format_table_line' ).'</table>'; // format_line mode is better for words
-                echo '<br />';
-                echo '<strong>'.get_lang('Legend').'</strong><div class="diff">' . "\n";
-                echo '<table><tr>';
-                echo  '<td>';
-                echo '</td><td>';
-                echo '<span class="diffEqual" >'.get_lang('WikiDiffUnchangedLine').'</span><br />';
-                echo '<span class="diffAdded" >'.get_lang('WikiDiffAddedLine').'</span><br />';
-                echo '<span class="diffDeleted" >'.get_lang('WikiDiffDeletedLine').'</span><br />';
-                echo '<span class="diffMoved" >'.get_lang('WikiDiffMovedLine').'</span><br />';
-                echo '</td>';
-                echo '</tr></table>';
-            }
-
-            if (isset($_POST['HistoryDifferences2'])) {
-                $lines1 = array(strip_tags($version_old['content'])); //without <> tags
-                $lines2 = array(strip_tags($version_new['content'])); //without <> tags
-                $diff = new Text_Diff($lines1, $lines2);
-                $renderer = new Text_Diff_Renderer_inline();
-                echo '<style>del{background:#fcc}ins{background:#cfc}</style>'.$renderer->render($diff); // Code inline
-                echo '<br />';
-                echo '<strong>'.get_lang('Legend').'</strong><div class="diff">' . "\n";
-                echo '<table><tr>';
-                echo  '<td>';
-                echo '</td><td>';
-                echo '<span class="diffAddedTex" >'.get_lang('WikiDiffAddedTex').'</span><br />';
-                echo '<span class="diffDeletedTex" >'.get_lang('WikiDiffDeletedTex').'</span><br />';
-                echo '</td>';
-                echo '</tr></table>';
-            }
-        }
-    }
-}
+Display::display_header($tool_name, 'Wiki');
 
-// Recent changes
-// @todo rss feed
-if ($action =='recentchanges') {
-    $wiki->recentChanges($page, $action);
+// check last version
+if (!empty($view)) {
+    $wiki->setWikiData($view);
+    $wiki->checkLastVersion($view);
 }
 
-// All pages
-if ($action == 'allpages') {
-    $wiki->allPages($action);
-}
+// Tool introduction
+Display::display_introduction_section(TOOL_WIKI);
 
-// Discuss pages
-if ($action == 'discuss') {
-    $wiki->getDiscuss($page);
-}
+$wiki->showActionBar();
+echo $wiki->getMessages();
+echo $content;
 
 Display::display_footer();

File diff suppressed because it is too large
+ 313 - 342
main/wiki/wiki.inc.php


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