Browse Source

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

Yannick Warnier 10 years ago
parent
commit
f6b9a55947
33 changed files with 1291 additions and 1086 deletions
  1. 5 5
      main/auth/courses.php
  2. 13 13
      main/auth/courses_controller.php
  3. 6 5
      main/chat/chat.php
  4. 12 2
      main/gradebook/gradebook_add_link.php
  5. 8 5
      main/gradebook/gradebook_edit_cat.php
  6. 30 10
      main/gradebook/gradebook_edit_link.php
  7. 16 6
      main/gradebook/lib/be/abstractlink.class.php
  8. 3 0
      main/gradebook/lib/be/category.class.php
  9. 30 1
      main/gradebook/lib/be/evaluation.class.php
  10. 24 22
      main/gradebook/lib/be/exerciselink.class.php
  11. 4 4
      main/gradebook/lib/fe/displaygradebook.php
  12. 6 7
      main/gradebook/lib/fe/gradebooktable.class.php
  13. 25 7
      main/gradebook/lib/fe/linkform.class.php
  14. 21 15
      main/gradebook/lib/gradebook_functions.inc.php
  15. 0 1
      main/inc/ajax/model.ajax.php
  16. 7 0
      main/inc/lib/course.lib.php
  17. 35 39
      main/inc/lib/database.lib.php
  18. 5 4
      main/inc/lib/link.lib.php
  19. 1 1
      main/inc/lib/pear/HTML/QuickForm.php
  20. 17 15
      main/inc/lib/usermanager.lib.php
  21. 2 0
      main/link/link.php
  22. 1 1
      main/newscorm/aiccBlock.class.php
  23. 1 1
      main/newscorm/aiccObjective.class.php
  24. 219 204
      main/newscorm/learnpath.class.php
  25. 231 252
      main/newscorm/learnpathItem.class.php
  26. 1 1
      main/newscorm/resourcelinker.inc.php
  27. 1 1
      main/newscorm/scorm.class.php
  28. 95 93
      main/newscorm/scormItem.class.php
  29. 299 298
      main/template/default/auth/courses_categories.php
  30. 13 7
      main/template/default/export/table_pdf.tpl
  31. 1 1
      main/work/edit.php
  32. 154 26
      main/work/work.lib.php
  33. 5 39
      main/work/work_list_all.php

+ 5 - 5
main/auth/courses.php

@@ -1,13 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
-* Template (front controller in MVC pattern) used for distpaching to the controllers depend on the current action
+* Template (front controller in MVC pattern) used for distpaching
+ * to the controllers depend on the current action
 * @author Christian Fasanando <christian1827@gmail.com> - Beeznest
 * @package chamilo.auth
 */
-/**
- * Code
- */
+
 // Names of the language file that needs to be included.
 $language_file = array ('courses', 'registration');
 
@@ -17,7 +17,7 @@ $cidReset = true; // Flag forcing the 'current course' reset
 // including files
 require_once '../inc/global.inc.php';
 
-$ctok = $_SESSION['sec_token'];
+$ctok = Security::get_existing_token();
 
 require_once api_get_path(LIBRARY_PATH).'auth.lib.php';
 require_once api_get_path(LIBRARY_PATH).'app_view.php';

+ 13 - 13
main/auth/courses_controller.php

@@ -1,11 +1,12 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
+ * Class CoursesController
+ *
  * This file contains class used like controller, it should be included inside a dispatcher file (e.g: index.php)
  * @author Christian Fasanando <christian1827@gmail.com> - BeezNest
  * @package chamilo.auth
- *
- * Class CoursesController
  */
 class CoursesController
 {
@@ -47,15 +48,14 @@ class CoursesController
         $this->view->set_layout('layout');
         $this->view->set_template('courses_list');
         $this->view->render();
-
     }
 
     /**
      * It's used for listing categories,
      * render to categories_list view
-     * @param string   	action
-     * @param string    confirmation message(optional)
-     * @param string    error message(optional)
+     * @param string   	$action
+     * @param string   $message confirmation message(optional)
+     * @param string   $error error message(optional)
      */
     public function categories_list($action, $message='', $error='')
     {
@@ -132,9 +132,9 @@ class CoursesController
         $data['message']          = $message;
         $data['content']          = $content;
         $data['error']            = $error;
-        
+
         $data['catalogShowCoursesSessions'] = 0;
-        
+
         if (isset($_configuration['catalog_show_courses_sessions'])) {
             $data['catalogShowCoursesSessions'] = $_configuration['catalog_show_courses_sessions'];
         }
@@ -178,10 +178,10 @@ class CoursesController
         }
 
         $data['user_coursecodes'] = $user_coursecodes;
-        $data['message']    = $message;
-        $data['content']    = $content;
-        $data['error']      = $error;
-        $data['action']     = 'display_courses';
+        $data['message'] = $message;
+        $data['content'] = $content;
+        $data['error'] = $error;
+        $data['action'] = 'display_courses';
 
         // render to the view
         $this->view->set_data($data);
@@ -493,7 +493,7 @@ class CoursesController
         $url = api_get_path(WEB_PATH) . "main/inc/email_editor.php?action=subscribe_me_to_session&session=$sessionName";
 
         return Display::url(get_lang('Subscribe'), $url, array(
-                    'class' => 'btn btn-large btn-primary',
+            'class' => 'btn btn-large btn-primary',
         ));
     }
 

+ 6 - 5
main/chat/chat.php

@@ -39,7 +39,7 @@ if (!empty($mycourseid) && $mycourseid != -1) {
 	$open_chat_window = api_get_course_setting('allow_open_chat_window');
 }
 
-$cidreq = Security::remove_XSS($_GET['cidReq']);
+$courseCode = Security::remove_XSS($_GET['cidReq']);
 
 ?>
 <!DOCTYPE html>
@@ -76,12 +76,13 @@ if (empty($open_chat_window)) {
 }
 
 $url = api_get_path(WEB_CODE_PATH).'chat/';
+$params = "cidReq=".$courseCode.'&id_session='.api_get_session_id();
 
 echo '<div class="page-chat">';
-echo '<iframe src="'.$url.'chat_whoisonline.php?cidReq='.$cidreq.'" name="chat_whoisonline" scrolling="no" style="height:550px; width:35%; border: 0px none; float:left"></iframe>';
-echo '<iframe src="'.$url.'chat_chat.php?origin='.$origin.'&target='.$target.'&amp;cidReq='.$cidreq.'" name="chat_chat" id="chat_chat" scrolling="auto" height="380" style="width:65%; border: 0px none; float:right"></iframe>';
-echo '<iframe src="'.$url.'chat_message.php?cidReq='.$cidreq.'" name="chat_message" scrolling="no" height="182px" style="width:65%; border: 0px none; float:right"></iframe>';
-echo '<iframe src="'.$url.'chat_hidden.php?cidReq='.$cidreq.'" name="chat_hidden" height="0" style="border: 0px none"></iframe>';
+echo '<iframe src="'.$url.'chat_whoisonline.php?'.$params.'" name="chat_whoisonline" scrolling="no" style="height:550px; width:35%; border: 0px none; float:left"></iframe>';
+echo '<iframe src="'.$url.'chat_chat.php?origin='.$origin.'&target='.$target.'&'.$params.'" name="chat_chat" id="chat_chat" scrolling="auto" height="380" style="width:65%; border: 0px none; float:right"></iframe>';
+echo '<iframe src="'.$url.'chat_message.php?'.$params.'" name="chat_message" scrolling="no" height="182px" style="width:65%; border: 0px none; float:right"></iframe>';
+echo '<iframe src="'.$url.'chat_hidden.php?'.$params.'" name="chat_hidden" height="0" style="border: 0px none"></iframe>';
 echo '</div>';
 
 if (empty($open_chat_window)) {

+ 12 - 2
main/gradebook/gradebook_add_link.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Script
  * @package chamilo.gradebook
@@ -35,14 +36,23 @@ if ($session_id == 0) {
 }
 $category = Category :: load($_GET['selectcat']);
 $url = api_get_self().'?selectcat='.Security::remove_XSS($_GET['selectcat']).'&newtypeselected='.$typeSelected.'&course_code='.api_get_course_id().'&'.api_get_cidreq();
-$typeform = new LinkForm(LinkForm :: TYPE_CREATE, $category[0], null, 'create_link', null, $url, $typeSelected);
+$typeform = new LinkForm(
+    LinkForm :: TYPE_CREATE,
+    $category[0],
+    null,
+    'create_link',
+    null,
+    $url,
+    $typeSelected
+);
 
 // if user selected a link type
 if ($typeform->validate() && isset($_GET['newtypeselected'])) {
     // reload page, this time with a parameter indicating the selected type
     header('Location: '.api_get_self().'?selectcat='.Security::remove_XSS($_GET['selectcat'])
         .'&typeselected='.$typeform->exportValue('select_link')
-        .'&course_code='.Security::remove_XSS($_GET['course_code'])).'&'.api_get_cidreq();
+        .'&course_code='.Security::remove_XSS($_GET['course_code']).'&'.api_get_cidreq()
+    );
     exit;
 }
 

+ 8 - 5
main/gradebook/gradebook_edit_cat.php

@@ -21,7 +21,7 @@ $edit_cat = isset($_REQUEST['editcat']) ? intval($_REQUEST['editcat']) : '';
 $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
 $htmlHeadXtra[] = '<link  href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
 
-$htmlHeadXtra[] = '<script type="text/javascript">
+$htmlHeadXtra[] = '<script>
 $(document).ready(function() {
     $("#skills").fcbkcomplete({
         json_url: "'.api_get_path(WEB_AJAX_PATH).'skill.ajax.php?a=find_skills",
@@ -72,7 +72,7 @@ function check_skills() {
                             }
                         });
                     }
-                },
+                }
             });
         }
     });
@@ -99,7 +99,7 @@ if ($form->validate()) {
 
     if (empty ($values['course_code'])) {
         $cat->set_course_code(null);
-    }else {
+    } else {
         $cat->set_course_code($values['course_code']);
     }
 
@@ -122,11 +122,14 @@ if ($form->validate()) {
 
     $cat->set_visible($visible);
     $cat->save();
-    header('Location: '.Security::remove_XSS($_SESSION['gradebook_dest']).'?editcat=&selectcat=' . $cat->get_parent_id());
+    header('Location: '.Security::remove_XSS($_SESSION['gradebook_dest']).'?editcat=&selectcat=' . $cat->get_parent_id().'&'.api_get_cidreq());
     exit;
 }
 $selectcat = isset($_GET['selectcat']) ? Security::remove_XSS($_GET['selectcat']) : '';
-$interbreadcrumb[] = array ('url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat='.$selectcat,'name' => get_lang('Gradebook'));
+$interbreadcrumb[] = array(
+    'url' => Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $selectcat . '&' . api_get_cidreq(),
+    'name' => get_lang('Gradebook')
+);
 $this_section = SECTION_COURSES;
 Display :: display_header(get_lang('EditCategory'));
 $form->display();

+ 30 - 10
main/gradebook/gradebook_edit_link.php

@@ -39,7 +39,14 @@ if ($session_id == 0) {
     $cats = Category :: load_session_categories(null, $session_id);
 }
 
-$form = new LinkAddEditForm(LinkAddEditForm :: TYPE_EDIT, $cats, null, $link, 'edit_link_form', api_get_self() . '?selectcat=' . $linkcat. '&editlink=' . $linkedit);
+$form = new LinkAddEditForm(
+    LinkAddEditForm :: TYPE_EDIT,
+    $cats,
+    null,
+    $link,
+    'edit_link_form',
+    api_get_self() . '?selectcat=' . $linkcat. '&editlink=' . $linkedit.'&'.api_get_cidreq()
+);
 if ($form->validate()) {
     $values = $form->exportValues();
     $parent_cat = Category :: load($values['select_gradebook']);
@@ -65,31 +72,44 @@ if ($form->validate()) {
     $link->save();
 
     //Update weight for attendance
-    $sql = 'SELECT ref_id FROM '.$tbl_grade_links.' WHERE id = '.intval($_GET['editlink']).' AND type='.LINK_ATTENDANCE;
+    $sql = 'SELECT ref_id FROM '.$tbl_grade_links.'
+            WHERE id = '.intval($_GET['editlink']).' AND type='.LINK_ATTENDANCE;
     $rs_attendance  = Database::query($sql);
     if (Database::num_rows($rs_attendance) > 0) {
         $row_attendance = Database::fetch_array($rs_attendance);
         $attendance_id  = $row_attendance['ref_id'];
-        $upd_attendance = 'UPDATE '.$tbl_attendance.' SET attendance_weight ='.floatval($final_weight).' WHERE c_id = '.$course_id.' AND  id = '.intval($attendance_id);
-        Database::query($upd_attendance);
+        $sql = 'UPDATE '.$tbl_attendance.' SET
+                    attendance_weight ='.floatval($final_weight).'
+                WHERE c_id = '.$course_id.' AND id = '.intval($attendance_id);
+        Database::query($sql);
     }
 
     //Update weight into forum thread
     $sql_t = 'UPDATE '.$tbl_forum_thread.' SET thread_weight='.$final_weight.'
-			  WHERE c_id = '.$course_id.' AND thread_id=(SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.intval($_GET['editlink']).' and type=5) ';
-
+			  WHERE c_id = '.$course_id.' AND thread_id=(
+                    SELECT ref_id FROM '.$tbl_grade_links.'
+			        WHERE id='.intval($_GET['editlink']).' and type=5
+              ) ';
     Database::query($sql_t);
 
     //Update weight into student publication(work)
-    $sql_t = 'UPDATE '.$tbl_work.' SET weight='.$final_weight.'
-			  WHERE c_id = '.$course_id.' AND id = (SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.intval($_GET['editlink'] ).' AND type=3 )';
+    $sql_t = 'UPDATE '.$tbl_work.' SET
+              weight='.$final_weight.'
+			  WHERE c_id = '.$course_id.' AND id = (
+			    SELECT ref_id FROM '.$tbl_grade_links.'
+			    WHERE id='.intval($_GET['editlink'] ).' AND type=3
+              )';
 
     Database::query($sql_t);
-    header('Location: '.$_SESSION['gradebook_dest'].'?linkedited=&selectcat=' . $link->get_category_id());
+    header('Location: '.$_SESSION['gradebook_dest'].'?linkedited=&selectcat=' . $link->get_category_id().'&'.api_get_cidreq());
     exit;
 }
 
-$interbreadcrumb[] = array ('url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat='.$linkcat,'name' => get_lang('Gradebook'));
+$interbreadcrumb[] = array(
+    'url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat='.$linkcat,
+    'name' => get_lang('Gradebook')
+);
+
 $htmlHeadXtra[] = '<script type="text/javascript">
 $(document).ready( function() {
     $("#hide_category_id").change(function() {

+ 16 - 6
main/gradebook/lib/be/abstractlink.class.php

@@ -106,7 +106,10 @@ abstract class AbstractLink implements GradebookItem
         $this->user_id = $user_id;
     }
 
-    public function set_course_code ($course_code)
+    /**
+     * @param string $course_code
+     */
+    public function set_course_code($course_code)
     {
         $this->course_code = $course_code;
         $course_info = api_get_course_info($course_code);
@@ -263,8 +266,15 @@ abstract class AbstractLink implements GradebookItem
     public function add()
     {
         $this->add_linked_data();
-        if (isset($this->type) && isset($this->ref_id) && isset($this->user_id) && isset($this->course_code) && isset($this->category) && isset($this->weight) && isset($this->visible)) {
-            $tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+        if (isset($this->type) &&
+            isset($this->ref_id) &&
+            isset($this->user_id) &&
+            isset($this->course_code) &&
+            isset($this->category) &&
+            isset($this->weight) &&
+            isset($this->visible)
+        ) {
+            $tbl_grade_links = Database:: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
             $sql = "SELECT count(*) FROM ".$tbl_grade_links."
                     WHERE
                         ref_id=".$this->get_ref_id()." AND
@@ -275,7 +285,7 @@ abstract class AbstractLink implements GradebookItem
             $result = Database::query($sql);
             $row_testing = Database::fetch_array($result);
 
-            if ($row_testing[0]==0) {
+            if ($row_testing[0] == 0) {
                 $sql = 'INSERT INTO '.$tbl_grade_links.' (type, ref_id, user_id, course_code, category_id, weight, visible, created_at) VALUES ('
                     .intval($this->get_type())
                     .','.intval($this->get_ref_id())
@@ -501,14 +511,14 @@ abstract class AbstractLink implements GradebookItem
     {
     }
 
-    public function get_view_url ($stud_id)
+    public function get_view_url($stud_id)
     {
         return null;
     }
 
     /**
      * Locks a link
-     * @param int locked 1 or unlocked 0
+     * @param int $locked 1 or unlocked 0
      *
      * */
     public function lock($locked)

+ 3 - 0
main/gradebook/lib/be/category.class.php

@@ -58,6 +58,9 @@ class Category implements GradebookItem
         }
     }
 
+    /**
+     * @return string
+     */
     public function get_course_code()
     {
         return $this->course_code;

+ 30 - 1
main/gradebook/lib/be/evaluation.class.php

@@ -17,16 +17,23 @@ class Evaluation implements GradebookItem
 	private $weight;
 	private $eval_max;
 	private $visible;
+	private $sessionId;
 
 	public function __construct()
 	{
 	}
 
+	/**
+	 * @return int
+	 */
 	public function get_id()
 	{
 		return $this->id;
 	}
 
+	/**
+	 * @return string
+	 */
 	public function get_name()
 	{
 		return $this->name;
@@ -47,6 +54,22 @@ class Evaluation implements GradebookItem
 		return $this->course_code;
 	}
 
+	/**
+	 * @return int
+	 */
+	public function getSessionId()
+	{
+		return $this->sessionId;
+	}
+
+	/**
+	 * @param int $sessionId
+	 */
+	public function setSessionId($sessionId)
+	{
+		$this->sessionId = intval($sessionId);
+	}
+
 	public function get_category_id()
 	{
 		return $this->category;
@@ -206,6 +229,10 @@ class Evaluation implements GradebookItem
 		return $alleval;
 	}
 
+	/**
+	 * @param array $result
+	 * @return array
+	 */
 	private static function create_evaluation_objects_from_sql_result($result)
 	{
 		$alleval=array();
@@ -224,10 +251,12 @@ class Evaluation implements GradebookItem
 				$eval->set_visible($data['visible']);
 				$eval->set_type($data['type']);
 				$eval->set_locked($data['locked']);
+				$eval->setSessionId(api_get_session_id());
 
-				$alleval[]=$eval;
+				$alleval[] = $eval;
 			}
 		}
+
 		return $alleval;
 	}
 

+ 24 - 22
main/gradebook/lib/be/exerciselink.class.php

@@ -1,6 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
+ * Class ExerciseLink
  * Defines a gradebook ExerciseLink object.
  * @author Bert Steppé
  * @package chamilo.gradebook
@@ -81,15 +83,15 @@ class ExerciseLink extends AbstractLink
 
         $sql2 = "SELECT d.path as path, d.comment as comment, ip.visibility as visibility, d.id
                 FROM $TBL_DOCUMENT d, $TBL_ITEM_PROPERTY ip
-                WHERE d.c_id = $this->course_id AND
-                      ip.c_id = $this->course_id AND
-                d.id = ip.ref AND ip.tool = '".TOOL_DOCUMENT."' AND (d.path LIKE '%htm%')AND (d.path LIKE '%HotPotatoes_files%')
-                AND   d.path  LIKE '".Database :: escape_string($uploadPath)."/%/%' AND ip.visibility='1'";
-
-        /*
-        $sql = 'SELECT id,title from '.$this->get_exercise_table().'
-				WHERE c_id = '.$this->course_id.' AND active=1 AND session_id='.api_get_session_id().'';
-        */
+                WHERE
+                    d.c_id = $this->course_id AND
+                    ip.c_id = $this->course_id AND
+                    d.id = ip.ref AND
+                    ip.tool = '".TOOL_DOCUMENT."' AND
+                    (d.path LIKE '%htm%')AND (d.path LIKE '%HotPotatoes_files%') AND
+                    d.path  LIKE '".Database :: escape_string($uploadPath.'/%/%')."' AND
+                    ip.visibility='1'
+                ";
         require_once api_get_path(SYS_CODE_PATH).'exercice/hotpotatoes.lib.php';
         if (!$this->is_hp) {
             $result = Database::query($sql);
@@ -116,9 +118,7 @@ class ExerciseLink extends AbstractLink
                     $attribute['id'] = $row['id'];
 
                     if (isset($attribute['path']) && is_array($attribute['path'])) {
-                        $hotpotatoes_exist = true;
                         while (list($key, $path) = each($attribute['path'])) {
-                            $item = '';
                             $title = GetQuizName($path, $documentPath);
                             if ($title == '') {
                                 $title = basename($path);
@@ -129,6 +129,7 @@ class ExerciseLink extends AbstractLink
                 }
             }
         }
+
         return $cats;
     }
 
@@ -137,12 +138,13 @@ class ExerciseLink extends AbstractLink
      */
     public function has_results()
     {
-        $tbl_stats = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $tbl_stats = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $session_id = api_get_session_id();
         $sql = 'SELECT count(exe_id) AS number FROM '.$tbl_stats."
-                    WHERE   session_id = $session_id AND
-                            exe_cours_id = '".$this->get_course_code()."'".' AND
-                            exe_exo_id   = '.(int)$this->get_ref_id();
+                WHERE
+                    session_id = $session_id AND
+                    exe_cours_id = '".Database::escape_string($this->get_course_code())."'".' AND
+                    exe_exo_id   = '.(int)$this->get_ref_id();
         $result = Database::query($sql);
         $number=Database::fetch_row($result);
         return ($number[0] != 0);
@@ -150,15 +152,15 @@ class ExerciseLink extends AbstractLink
 
     /**
      * Get the score of this exercise. Only the first attempts are taken into account.
-     * @param $stud_id student id (default: all students who have results - then the average is returned)
+     * @param int $stud_id student id (default: all students who have results - then the average is returned)
      * @return	array (score, max) if student is given
      * 			array (sum of scores, number of scores) otherwise
      * 			or null if no scores available
      */
     public function calc_score($stud_id = null)
     {
-        $tblStats = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $tblHp = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+        $tblStats = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $tblHp = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
         $tblDoc = Database::get_course_table(TABLE_DOCUMENT);
 
         /* the following query should be similar (in conditions) to the one used
@@ -196,7 +198,7 @@ class ExerciseLink extends AbstractLink
         if (isset($stud_id)) {
             // for 1 student
             if ($data = Database::fetch_array($scores)) {
-                return array ($data['exe_result'], $data['exe_weighting']);
+                return array($data['exe_result'], $data['exe_weighting']);
             } else {
                 return null;
             }
@@ -254,8 +256,6 @@ class ExerciseLink extends AbstractLink
         $data = $this->get_exercise_data();
         if ($this->is_hp == 1) {
             if (isset($data['path'])) {
-                $hotpotatoes_exist = true;
-                $item = '';
                 $title = GetQuizName($data['path'], $documentPath);
                 if ($title == '') {
                     $title = basename($data['path']);
@@ -333,9 +333,10 @@ class ExerciseLink extends AbstractLink
      */
     private function get_exercise_data()
     {
+        $TBL_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+
         if ($this->is_hp == 1) {
             $tbl_exercise = Database :: get_course_table(TABLE_DOCUMENT);
-            $TBL_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
         } else {
             $tbl_exercise = $this->get_exercise_table();
         }
@@ -363,6 +364,7 @@ class ExerciseLink extends AbstractLink
             $result = Database::query($sql);
             $this->exercise_data=Database::fetch_array($result);
         }
+
         return $this->exercise_data;
     }
 

+ 4 - 4
main/gradebook/lib/fe/displaygradebook.php

@@ -348,7 +348,7 @@ class DisplayGradebook
                     $visibility_command = ($catobj->is_visible() == 0) ? 'set_visible' : 'set_invisible';
 
                     //Right icons
-                    $modify_icons = '<a href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&cidReq=' . $catobj->get_course_code() . '">' . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_MEDIUM) . '</a>';
+                    $modify_icons = '<a href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&cidReq=' . $catobj->get_course_code() . '&id_session='.$catobj->get_session_id(). '">' . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_MEDIUM) . '</a>';
                     //$modify_icons .= '<a href="../document/document.php?curdirpath=/certificates&'.$my_api_cidreq.'&origin=gradebook&selectcat=' . $catobj->get_id() . '">'.
                     //Display::return_icon('certificate.png', get_lang('AttachCertificate'),'',ICON_SIZE_MEDIUM).'</a>';
                     //hide or delete are not options available
@@ -368,7 +368,7 @@ class DisplayGradebook
 
     /**
      * Displays the header for the gradebook containing the navigation tree and links
-     * @param Category $currentcat
+     * @param Category $catobj
      * @param int $showtree '1' will show the browse tree and naviation buttons
      * @param boolean $is_course_admin
      * @param boolean $is_platform_admin
@@ -553,7 +553,7 @@ class DisplayGradebook
                     $header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?' . $my_api_cidreq . '&amp;cat_id=' . (int) $_GET['selectcat'] . '">' .
                         Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'), '', ICON_SIZE_MEDIUM) . '</a>';
                     // Right icons
-                    $modify_icons = '<a href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&amp;cidReq=' . $catobj->get_course_code() . '">' .
+                    $modify_icons = '<a href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&amp;cidReq=' . $catobj->get_course_code() . '&id_session='.$catobj->get_session_id(). '">' .
                         Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_MEDIUM) . '</a>';
                     $modify_icons .= '<a href="../document/document.php?curdirpath=/certificates&' . $my_api_cidreq . '&origin=gradebook&selectcat=' . $catobj->get_id() . '">' .
                             Display::return_icon('certificate.png', get_lang('AttachCertificate'), '', ICON_SIZE_MEDIUM) . '</a>';
@@ -596,7 +596,7 @@ class DisplayGradebook
 
             $min_certification = (intval($catobj->get_certificate_min_score() > 0) ? $catobj->get_certificate_min_score() : 0);
             $min_certification = get_lang('CertificateMinScore') . ' : ' . $min_certification;
-            $edit_icon = '<a class="right_link" href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&amp;cidReq=' . $catobj->get_course_code() . '">' .
+            $edit_icon = '<a class="right_link" href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . '&amp;cidReq=' . $catobj->get_course_code() . '&id_session='.$catobj->get_session_id(). '">' .
                 Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>';
             //$msg = Display::tag('h3', $weight.' - '.$min_certification);
             $msg = Display::tag('h4', $weight . ' - ' . $min_certification . $edit_icon);

+ 6 - 7
main/gradebook/lib/fe/gradebooktable.class.php

@@ -407,13 +407,17 @@ class GradebookTable extends SortableTable
                     $weight_total_links > $weight_category
                 ) {
                     $warning_message = sprintf(get_lang('TotalWeightMustBeX'), $weight_category);
-                    $modify_icons  = '<a class="right_link" href="gradebook_edit_cat.php?editcat='.$id_cat.'&cidReq='.$course_code.'">'.
+                    $modify_icons  = '<a class="right_link" href="gradebook_edit_cat.php?editcat='.$id_cat.'&cidReq='.$course_code.'&id_session='.api_get_session_id().'">'.
                             Display::return_icon('edit.png', $warning_message, array(), ICON_SIZE_SMALL).'</a>';
                     $warning_message .= $modify_icons;
                     Display::display_warning_message($warning_message, false);
                 }
 
-                $content_html = DocumentManager::replace_user_info_into_html(api_get_user_id(), $course_code);
+                $content_html = DocumentManager::replace_user_info_into_html(
+                    api_get_user_id(),
+                    $course_code
+                );
+
                 if (!empty($content_html)) {
                     $new_content = explode('</head>',$content_html['content']);
                 }
@@ -422,11 +426,6 @@ class GradebookTable extends SortableTable
                     // Set default certificate
                     $courseData = api_get_course_info($course_code);
                     DocumentManager::generateDefaultCertificate($courseData);
-
-                    //$warning_message = get_lang('ThereIsNotACertificateAvailableByDefault');
-                    //$cert_icon = '<a class="right_link" href="../document/document.php?curdirpath=/certificates&'.$course_code.'&origin=gradebook&selectcat=' . $id_cat . '">'.Display::return_icon('certificate.png', get_lang('AttachCertificate'), array(), ICON_SIZE_SMALL).'</a>';
-
-                    //Display::display_warning_message($warning_message.$cert_icon,false);
                 }
             }
 

+ 25 - 7
main/gradebook/lib/fe/linkform.class.php

@@ -17,7 +17,7 @@ class LinkForm extends FormValidator
 {
 	const TYPE_CREATE = 1;
 	const TYPE_MOVE = 2;
-
+	/** @var Category */
 	private $category_object;
 	private $link_object;
 	private $extra;
@@ -30,15 +30,25 @@ class LinkForm extends FormValidator
 	 * @param method
 	 * @param action
 	 */
-	function LinkForm($form_type, $category_object,$link_object, $form_name, $method = 'post', $action = null, $extra = null)
-	{
+	public function LinkForm(
+		$form_type,
+		$category_object,
+		$link_object,
+		$form_name,
+		$method = 'post',
+		$action = null,
+		$extra = null
+	) {
 		parent :: __construct($form_name, $method, $action);
 
 		if (isset ($category_object)) {
 			$this->category_object = $category_object;
-		} if (isset ($link_object)) {
-			$this->link_object = $link_object;
+		} else {
+			if (isset($link_object)) {
+				$this->link_object = $link_object;
+			}
 		}
+
 		if (isset ($extra)) {
 			$this->extra = $extra;
 		}
@@ -47,7 +57,6 @@ class LinkForm extends FormValidator
 		} elseif ($form_type == self :: TYPE_MOVE) {
 			$this->build_move();
 		}
-		//$this->setDefaults();
 	}
 
 	protected function build_move()
@@ -68,10 +77,19 @@ class LinkForm extends FormValidator
 		$this->addElement('submit', null, get_lang('Ok'));
 	}
 
+	/**
+	 * Builds the form
+	 */
 	protected function build_create()
 	{
 		$this->addElement('header', get_lang('MakeLink'));
-		$select = $this->addElement('select', 'select_link', get_lang('ChooseLink'), null, array('onchange' => 'document.create_link.submit()'));
+		$select = $this->addElement(
+			'select',
+			'select_link',
+			get_lang('ChooseLink'),
+			null,
+			array('onchange' => 'document.create_link.submit()')
+		);
 
 		$linkTypes = LinkFactory::get_all_types();
 

+ 21 - 15
main/gradebook/lib/gradebook_functions.inc.php

@@ -241,7 +241,7 @@ function build_edit_icons_cat($cat, $selectcat)
                 if ($cat->is_locked() && !api_is_platform_admin()) {
                     $modify_icons .= Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
                 } else {
-                    $modify_icons .= '<a href="gradebook_edit_cat.php?' .'editcat=' . $cat->get_id() . '&cidReq=' .$cat->get_course_code() . '">' .
+                    $modify_icons .= '<a href="gradebook_edit_cat.php?' .'editcat=' . $cat->get_id() . '&cidReq=' .$cat->get_course_code() . '&id_session='.$cat->get_session_id().'">' .
                         Display::return_icon(
                             'edit.png',
                             get_lang('Modify'),
@@ -251,21 +251,21 @@ function build_edit_icons_cat($cat, $selectcat)
                 }
             }
 
-            $modify_icons .= '<a href="gradebook_edit_all.php?selectcat=' .$cat->get_id() . '&cidReq=' . $cat->get_course_code() . '">' .
+            $modify_icons .= '<a href="gradebook_edit_all.php?selectcat=' .$cat->get_id() . '&cidReq=' . $cat->get_course_code() . '&id_session='.$cat->get_session_id().'">' .
                 Display::return_icon(
                     'percentage.png',
                     get_lang('EditAllWeights'),
                     '',
                     ICON_SIZE_SMALL
                 ) . '</a>';
-            $modify_icons .= '<a href="gradebook_flatview.php?selectcat=' .$cat->get_id() . '&cidReq=' . $cat->get_course_code() . '">' .
+            $modify_icons .= '<a href="gradebook_flatview.php?selectcat=' .$cat->get_id() . '&cidReq=' . $cat->get_course_code() . '&id_session='.$cat->get_session_id(). '">' .
                 Display::return_icon(
                     'stats.png',
                     get_lang('FlatView'),
                     '',
                     ICON_SIZE_SMALL
                 ) . '</a>';
-            $modify_icons .= '&nbsp;<a href="' . api_get_self() .'?visiblecat=' . $cat->get_id() . '&' .$visibility_command . '=&selectcat=' . $selectcat .'&cidReq=' . $cat->get_course_code() . '">' .
+            $modify_icons .= '&nbsp;<a href="' . api_get_self() .'?visiblecat=' . $cat->get_id() . '&' .$visibility_command . '=&selectcat=' . $selectcat .'&cidReq=' . $cat->get_course_code() . '&id_session='.$cat->get_session_id(). '">' .
                 Display::return_icon(
                     $visibility_icon . '.png',
                     get_lang('Visible'),
@@ -283,7 +283,7 @@ function build_edit_icons_cat($cat, $selectcat)
             if ($cat->is_locked() && !api_is_platform_admin()) {
                 $modify_icons .= Display::return_icon('delete_na.png', get_lang('DeleteAll'), '', ICON_SIZE_SMALL);
             } else {
-                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . '&amp;cidReq=' . $cat->get_course_code() . '" onclick="return confirmation();">' .
+                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . '&amp;cidReq=' . $cat->get_course_code() . '&id_session='.$cat->get_session_id(). '" onclick="return confirmation();">' .
                     Display::return_icon('delete.png', get_lang('DeleteAll'), '', ICON_SIZE_SMALL) . '</a>';
             }
         }
@@ -294,7 +294,7 @@ function build_edit_icons_cat($cat, $selectcat)
 
 /**
  * Builds the course or platform admin icons to edit an evaluation
- * @param object $eval evaluation object
+ * @param  Evaluation $eval evaluation object
  * @param int $selectcat id of selected category
  */
 function build_edit_icons_eval($eval, $selectcat)
@@ -311,12 +311,15 @@ function build_edit_icons_eval($eval, $selectcat)
         if ($is_locked && !api_is_platform_admin()) {
             $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
         } else {
-            $modify_icons = '<a href="gradebook_edit_eval.php?editeval=' . $eval->get_id() . ' &amp;cidReq=' . $eval->get_course_code() . '">' . Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
+            $modify_icons = '<a href="gradebook_edit_eval.php?editeval=' . $eval->get_id() . ' &amp;cidReq=' . $eval->get_course_code() . '&id_session='.$eval->getSessionId(). '">' .
+                Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
         }
 
-        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visibleeval=' . $eval->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . ' ">' . Display::return_icon($visibility_icon . '.png', get_lang('Visible'), '', ICON_SIZE_SMALL) . '</a>';
+        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visibleeval=' . $eval->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . '&id_session='.$eval->getSessionId(). ' ">' .
+            Display::return_icon($visibility_icon . '.png', get_lang('Visible'), '', ICON_SIZE_SMALL) . '</a>';
         if (api_is_allowed_to_edit(null, true)) {
-            $modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog=' . $eval->get_id() . '&amp;selectcat=' . $selectcat . ' &amp;cidReq=' . $eval->get_course_code() . '">' . Display::return_icon('history.png', get_lang('GradebookQualifyLog'), '', ICON_SIZE_SMALL) . '</a>';
+            $modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog=' . $eval->get_id() . '&amp;selectcat=' . $selectcat . ' &amp;cidReq=' . $eval->get_course_code() . '&id_session='.$eval->getSessionId(). '">' .
+                Display::return_icon('history.png', get_lang('GradebookQualifyLog'), '', ICON_SIZE_SMALL) . '</a>';
         }
 
         /*
@@ -332,7 +335,7 @@ function build_edit_icons_eval($eval, $selectcat)
         if ($is_locked && !api_is_platform_admin()) {
             $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
         } else {
-            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deleteeval=' . $eval->get_id() . '&selectcat=' . $selectcat . ' &amp;cidReq=' . $eval->get_course_code() . '" onclick="return confirmation();">' . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
+            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deleteeval=' . $eval->get_id() . '&selectcat=' . $selectcat . ' &amp;cidReq=' . $eval->get_course_code() . '&id_session='.$eval->getSessionId(). '" onclick="return confirmation();">' . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
         }
         return $modify_icons;
     }
@@ -340,7 +343,7 @@ function build_edit_icons_eval($eval, $selectcat)
 
 /**
  * Builds the course or platform admin icons to edit a link
- * @param object $linkobject
+ * @param AbstractLink $link
  * @param int $selectcat id of selected category
  */
 function build_edit_icons_link($link, $selectcat)
@@ -362,20 +365,23 @@ function build_edit_icons_link($link, $selectcat)
         if ($is_locked && !api_is_platform_admin()) {
             $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
         } else {
-            $modify_icons = '<a href="gradebook_edit_link.php?editlink=' . $link->get_id() . '&amp;cidReq=' . $link->get_course_code() . '">' .
+            $modify_icons = '<a href="gradebook_edit_link.php?editlink=' . $link->get_id() . '&amp;cidReq=' . $link->get_course_code() . '&id_session='.$link->get_session_id().'">' .
                 Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
         }
 
         //$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?movelink=' . $link->get_id() . '&selectcat=' . $selectcat . '"><img src="../img/deplacer_fichier.gif" border="0" title="' . get_lang('Move') . '" alt="" /></a>';
-        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visiblelink=' . $link->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . ' ">' . Display::return_icon($visibility_icon . '.png', get_lang('Visible'), '', ICON_SIZE_SMALL) . '</a>';
-        $modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink=' . $link->get_id() . '&amp;selectcat=' . $selectcat . '&amp;cidReq=' . $link->get_course_code() . '">' . Display::return_icon('history.png', get_lang('GradebookQualifyLog'), '', ICON_SIZE_SMALL) . '</a>';
+        $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visiblelink=' . $link->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . '&id_session='.$link->get_session_id(). ' ">' .
+            Display::return_icon($visibility_icon . '.png', get_lang('Visible'), '', ICON_SIZE_SMALL) . '</a>';
+        $modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink=' . $link->get_id() . '&amp;selectcat=' . $selectcat . '&amp;cidReq=' . $link->get_course_code() . '&id_session='.$link->get_session_id(). '">' .
+            Display::return_icon('history.png', get_lang('GradebookQualifyLog'), '', ICON_SIZE_SMALL) . '</a>';
 
         //If a work is added in a gradebook you can only delete the link in the work tool
 
         if ($is_locked && !api_is_platform_admin()) {
             $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
         } else {
-            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletelink=' . $link->get_id() . '&selectcat=' . $selectcat . ' &amp;cidReq=' . $link->get_course_code() . '" onclick="return confirmation();">' . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
+            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletelink=' . $link->get_id() . '&selectcat=' . $selectcat . ' &amp;cidReq=' . $link->get_course_code() . '&id_session='.$link->get_session_id(). '" onclick="return confirmation();">' .
+                Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
         }
         return $modify_icons;
     }

+ 0 - 1
main/inc/ajax/model.ajax.php

@@ -81,7 +81,6 @@ function getWhereClause($col, $oper, $val)
         'nc' => 'NOT LIKE'  //doesn't contain
     );
 
-
     if (empty($col)) {
         return '';
     }

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

@@ -1379,6 +1379,13 @@ class CourseManager
         $session_id = intval($session_id);
         $course_code = Database::escape_string($course_code);
         $where = array();
+        
+        if (empty($order_by)) {
+            $order_by = 'user.lastname, user.firstname';
+            if (api_is_western_name_order()) {
+                $order_by = 'user.firstname, user.lastname';
+            }
+        }
 
         // if the $order_by does not contain 'ORDER BY' we have to check if it is a valid field that can be sorted on
         if (!strstr($order_by,'ORDER BY')) {

+ 35 - 39
main/inc/lib/database.lib.php

@@ -1,6 +1,12 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
+ * Constants definition
+ */
+require_once 'database.constants.inc.php';
+
+/**
+ * Class Database
  *  This is the main database library for Chamilo.
  *  Include/require it in your code to use its functionality.
  *  Because this library contains all the basic database calls, it could be
@@ -13,20 +19,10 @@
  *
  *  @package chamilo.library
  */
-/**
- * Constants definition
- */
-require_once 'database.constants.inc.php';
-
-/**
- * Database class definition
- * @package chamilo.database
- */
 class Database
 {
     /* Variable use only in the installation process to log errors. See the Database::query function */
     static $log_queries = false;
-
     /*
         Accessor methods
         Usually, you won't need these directly but instead
@@ -158,7 +154,6 @@ class Database
     }
 
     /**
-
      * A more generic method than the older get_course_xxx_table methods,
      * This one can return the correct complete name of any course table of
      * which you pass the short name as a parameter.
@@ -169,7 +164,8 @@ class Database
      * @param string $database_name, optional, name of the course database
      * - if you don't specify this, you work on the current course.
      */
-    public static function get_course_table($short_table_name, $extra = null) {
+    public static function get_course_table($short_table_name, $extra = null)
+    {
         //forces fatal errors so we can debug more easily
         if (!empty($extra)) {
             var_dump($extra);
@@ -186,7 +182,7 @@ class Database
      * statistic table of which you pass the short name as a parameter.
      * Please, define table names as constants in this library and use them
      * instead of directly using magic words in your tool code.
-     *
+     * @deprecated use get_main_table
      * @param string $short_table_name, the name of the table
      */
     public static function get_statistic_table($short_table_name)
@@ -218,7 +214,7 @@ class Database
     */
 
     /**
-     *  @return a list (array) of all courses.
+     *  @return array a list (array) of all courses.
      *  @todo shouldn't this be in the course.lib.php script?
      */
     public static function get_course_list()
@@ -1183,13 +1179,12 @@ class Database
         return null;
     }
 
-    /*
-        New useful DB functions
-    */
-
     /**
-     * Experimental useful database insert
-     * @todo lot of stuff to do here
+     * Database insert
+     * @param string $table_name
+     * @param array $attributes
+     * @param bool $show_query
+     * @return bool|int
      */
     public static function insert($table_name, $attributes, $show_query = false)
     {
@@ -1363,7 +1358,7 @@ class Database
      */
     public static function parse_where_conditions($conditions)
     {
-        return self::parse_conditions(array('where'=>$conditions));
+        return self::parse_conditions(array('where' => $conditions));
     }
 
     /**
@@ -1381,25 +1376,28 @@ class Database
         return $affected_rows;
     }
 
-
     /**
-     * Experimental useful database update
-     * @param   string  table name use Database::get_main_table
-     * @param   array   array with values to updates, keys are the fields in the database: Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya';
-     * @param   array   where conditions i.e array('id = ?' =>'4')
-     * @todo lot of stuff to do here
+     * @param string $table_name use Database::get_main_table
+     * @param array $attributes Values to updates
+     * Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya';
+     * @param array $where_conditions where conditions i.e array('id = ?' =>'4')
+     * @param bool $show_query
+     * @return bool|int
      */
-    public static function update($table_name, $attributes, $where_conditions = array(), $show_query = false) {
-
+    public static function update(
+        $table_name,
+        $attributes,
+        $where_conditions = array(),
+        $show_query = false
+    ) {
         if (!empty($table_name) && !empty($attributes)) {
             $update_sql = '';
             //Cleaning attributes
             $count = 1;
             foreach ($attributes as $key=>$value) {
-
-                if (!is_array($value))
-
-                $value = self::escape_string($value);
+                if (!is_array($value)) {
+                    $value = self::escape_string($value);
+                }
                 $update_sql .= "$key = '$value' ";
                 if ($count < count($attributes)) {
                     $update_sql.=', ';
@@ -1410,8 +1408,10 @@ class Database
                 //Parsing and cleaning the where conditions
                 $where_return = self::parse_where_conditions($where_conditions);
                 $sql    = "UPDATE $table_name SET $update_sql $where_return ";
-                if ($show_query) { var_dump($sql); }
-                $result = self::query($sql);
+                if ($show_query) {
+                    var_dump($sql);
+                }
+                self::query($sql);
                 $affected_rows = self::affected_rows();
                 return $affected_rows;
             }
@@ -1419,10 +1419,6 @@ class Database
         return false;
     }
 
-     /*
-        DEPRECATED METHODS
-    */
-
     /**
      * @deprecated Use api_get_language_isocode($language) instead.
      */

+ 5 - 4
main/inc/lib/link.lib.php

@@ -942,7 +942,7 @@ function showlinksofcategory($catid)
 
             if ($myrow['visibility'] == '1') {
                 echo '<tr class="' . $css_class . '">';
-                echo '<td align="center" valign="middle" width="15">';
+                echo '<td align="center" valign="middle" width="5%">';
                 echo '<a href="link_goto.php?' . api_get_cidreq() .
                     '&amp;link_id=' . $myrow['id'] .
                     '&amp;link_url=' . urlencode($myrow['url']) . '" target="_blank">
@@ -958,7 +958,7 @@ function showlinksofcategory($catid)
             } else {
                 if (api_is_allowed_to_edit(null, true)) {
                     echo '<tr class="' . $css_class . '">';
-                    echo '<td align="center" valign="middle" width="15">
+                    echo '<td align="center" valign="middle" width="5%">
                         <a href="link_goto.php?' . api_get_cidreq() .
                         '&amp;link_id=' . $myrow['id'] . "
                         &amp;link_url=" . urlencode($myrow['url']) . '"
@@ -978,8 +978,8 @@ function showlinksofcategory($catid)
                 }
             }
 
-            echo '<td style="text-align:center;">';
             if (api_is_allowed_to_edit(null, true)) {
+                echo '<td style="text-align:center;">';
                 if ($session_id == $myrow['session_id']) {
                     echo '<a href="' . api_get_self() . '?' . api_get_cidreq() .
                         '&amp;sec_token=' . $token .
@@ -1053,8 +1053,9 @@ function showlinksofcategory($catid)
                         ICON_SIZE_SMALL
                     ); //get_lang('EditionNotAvailableFromSession');
                 }
+                echo '</td>';
             }
-            echo '</td></tr>';
+            echo '</tr>';
             $i++;
         }
         echo '</table>';

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

@@ -644,7 +644,7 @@ class HTML_QuickForm extends HTML_Common
      *
      * @param    mixed      $element        element object or type of element to add (text, textarea, file...)
      * @since    1.0
-     * @return   HTML_QuickForm_Element     a reference to newly added element
+     * @return   HTML_QuickForm_element     a reference to newly added element
      * @access   public
      * @throws   HTML_QuickForm_Error
      */

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

@@ -1530,8 +1530,6 @@ class UserManager
             $fvalues = $fvalue;
         }
 
-        $fvalues = Database::escape_string($fvalues);
-
         $sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
         $resuf = Database::query($sqluf);
         $is_extra_file = false;
@@ -1546,9 +1544,9 @@ class UserManager
                     UserManager::process_tags(explode(';', $fvalues), $user_id, $rowuf['id']);
                     return true;
                     break;
-                case self::USER_FIELD_TYPE_SELECT_MULTIPLE :
+                /*case self::USER_FIELD_TYPE_SELECT_MULTIPLE :
                     // check code from UserManager::update_user_picture() to use something similar here
-                    break;
+                    break;*/
                 case self::USER_FIELD_TYPE_RADIO:
                 case self::USER_FIELD_TYPE_SELECT:
                 case self::USER_FIELD_TYPE_SELECT_MULTIPLE:
@@ -1610,7 +1608,7 @@ class UserManager
                     $rowufv = Database::fetch_array($resufv);
                     if ($rowufv['field_value'] != $fvalues) {
                         $sqlu = "UPDATE $t_ufv SET
-                                    field_value = '$fvalues',
+                                    field_value = '".Database::escape_string($fvalues)."',
                                     tms = FROM_UNIXTIME($tms)
                                 WHERE id = ".$rowufv['id'];
                         $resu = Database::query($sqlu);
@@ -1624,7 +1622,11 @@ class UserManager
                 if ($rowufv['field_value'] != $fvalues) {
                     if ($is_extra_file) {
                         // To remove from user folder
-                        self::remove_user_extra_file($user_id, $fname, $rowufv['field_value']);
+                        self::remove_user_extra_file(
+                            $user_id,
+                            $fname,
+                            $rowufv['field_value']
+                        );
                     }
                     // If the new field is empty, delete it
                     if ($fvalues == '') {
@@ -1633,7 +1635,7 @@ class UserManager
                     } else {
                         // Otherwise update it
                         $sql_query = "UPDATE $t_ufv SET
-                                        field_value = '$fvalues',
+                                        field_value = '".Database::escape_string($fvalues)."',
                                         tms = FROM_UNIXTIME($tms)
                                       WHERE id = ".$rowufv['id'];
                     }
@@ -1644,10 +1646,10 @@ class UserManager
 
                 return true;
             } else {
-                $sqli = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms)
-                         VALUES ( $user_id, ".$rowuf['id'].", '$fvalues', FROM_UNIXTIME($tms))";
-                $resi = Database::query($sqli);
-                return ($resi ? true : false);
+                $sql = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms)
+                        VALUES ( $user_id, ".$rowuf['id'].", '".Database::escape_string($fvalues)."', FROM_UNIXTIME($tms))";
+                $res = Database::query($sql);
+                return $res ? true : false;
             }
         } else {
             // Field not found
@@ -3491,12 +3493,12 @@ class UserManager
         if ($tag_id == 0) {
             //the tag doesn't exist
             $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
-            $result = Database::query($sql);
-            $last_insert_id = Database::get_last_insert_id();
+             Database::query($sql);
+            $last_insert_id = Database::insert_id();
         } else {
             //the tag exists we update it
             $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id  = $tag_id";
-            $result = Database::query($sql);
+             Database::query($sql);
             $last_insert_id = $tag_id;
         }
 
@@ -3507,7 +3509,7 @@ class UserManager
             //if the relationship does not exist we create it
             if (Database::num_rows($result) == 0) {
                 $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id";
-                $result = Database::query($sql);
+                Database::query($sql);
             }
         }
     }

+ 2 - 0
main/link/link.php

@@ -465,6 +465,8 @@ if (empty($_GET['action']) || ($_GET['action'] != 'editlink' && $_GET['action']
         // - instead of a +, the category is no longer clickable and all the links of this category are displayed
         $myrow['description'] = text_filter($myrow['description']);
 
+        // Link categories are always visible.
+        $myrow['visibility'] = 1;
 
         $strVisibility = '';
         if ($myrow['visibility'] == '1') {

+ 1 - 1
main/newscorm/aiccBlock.class.php

@@ -39,7 +39,7 @@ class aiccBlock extends learnpathItem
                                 break;
                             case 'member':
                                 if (strstr($value, ',') !== false) {
-                                    $temp = split(',', $value);
+                                    $temp = explode(',', $value);
                                     foreach ($temp as $val) {
                                         if (!empty($val)) {
                                             $this->members[] = $val;

+ 1 - 1
main/newscorm/aiccObjective.class.php

@@ -38,7 +38,7 @@ class aiccObjective extends learnpathItem
                                 break;
                             case 'member':
                                 if (strstr($value, ',') !== false) {
-                                    $temp = split(',', $value);
+                                    $temp = explode(',', $value);
                                     foreach ($temp as $val) {
                                         if (!empty($val)) {
                                             $this->members[] = $val;

+ 219 - 204
main/newscorm/learnpath.class.php

@@ -209,9 +209,9 @@ class learnpath
                 error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - NOT Found previous view', 0);
             }
             $this->attempt = 1;
-            $sql_ins = "INSERT INTO $lp_table (c_id, lp_id, user_id, view_count, session_id)
-                        VALUES ($course_id, $lp_id, $user_id, 1, $session_id)";
-            Database::query($sql_ins);
+            $sql = "INSERT INTO $lp_table (c_id, lp_id, user_id, view_count, session_id)
+                    VALUES ($course_id, $lp_id, $user_id, 1, $session_id)";
+            Database::query($sql);
             $this->lp_view_id = Database::insert_id();
             if ($this->debug > 2) {
                 error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - inserting new lp_view: ' . $sql_ins, 0);
@@ -263,6 +263,7 @@ class learnpath
                         // Don't use reference here as the next loop will make the pointed object change.
 
                         $this->items[$my_item_id] = $oItem;
+
                         $this->refs_list[$oItem->ref] = $my_item_id;
                         if ($this->debug > 2) {
                             error_log('New LP - object with id ' . $my_item_id . ' set in items[]', 0);
@@ -354,12 +355,13 @@ class learnpath
                         $this->items[$item_id]->set_status($this->default_status);
                     }
                     // Add that row to the lp_item_view table so that we have something to show in the stats page.
-                    $sql_ins = "INSERT INTO $lp_item_view_table (c_id, lp_item_id, lp_view_id, view_count, status)
-                                VALUES ($course_id, ".$item_id . "," . $this->lp_view_id . ", 1, 'not attempted')";
+                    $sql = "INSERT INTO $lp_item_view_table (c_id, lp_item_id, lp_view_id, view_count, status)
+                            VALUES ($course_id, ".$item_id . "," . $this->lp_view_id . ", 1, 'not attempted')";
                     if ($this->debug > 2) {
-                        error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - Inserting blank item_view : ' . $sql_ins, 0);
+                        error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - Inserting blank item_view : ' . $sql, 0);
                     }
-                    Database::query($sql_ins);
+                    $this->items[$item_id]->set_lp_view($this->lp_view_id, $course_id);
+                    Database::query($sql);
                 }
             }
         }
@@ -454,16 +456,13 @@ class learnpath
             error_log('New LP - In learnpath::add_item(' . $parent . ',' . $previous . ',' . $type . ',' . $id . ',' . $title . ')', 0);
         }
         $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
-
         $parent = intval($parent);
         $previous = intval($previous);
         $id = intval($id);
-        $max_time_allowed = Database::escape_string(htmlentities($max_time_allowed));
-        if (empty ($max_time_allowed)) {
+        $max_time_allowed = htmlentities($max_time_allowed);
+        if (empty($max_time_allowed)) {
             $max_time_allowed = 0;
         }
-        $title       = Database::escape_string($title);
-        $description = Database::escape_string($description);
         $sql_count = "	SELECT COUNT(id) AS num
                         FROM $tbl_lp_item
                         WHERE
@@ -478,12 +477,13 @@ class learnpath
         if ($num > 0) {
             if ($previous == 0) {
                 $sql = "SELECT id, next_item_id, display_order
-                       FROM " . $tbl_lp_item . "
-                       WHERE   c_id = $course_id AND
-                               lp_id = " . $this->get_id() . " AND
-                               parent_item_id = " . $parent . " AND
-                               previous_item_id = 0 OR
-                               previous_item_id=" . $parent;
+                        FROM " . $tbl_lp_item . "
+                        WHERE
+                            c_id = $course_id AND
+                            lp_id = " . $this->get_id() . " AND
+                            parent_item_id = " . $parent . " AND
+                            previous_item_id = 0 OR
+                            previous_item_id=" . $parent;
                 $result = Database::query($sql);
                 $row = Database :: fetch_array($result);
 
@@ -500,7 +500,7 @@ class learnpath
                             id = " . $previous;
 
                 $result = Database::query($sql);
-                $row 	= Database :: fetch_array($result);
+                $row = Database:: fetch_array($result);
 
                 $tmp_previous = $row['id'];
                 $next = $row['next_item_id'];
@@ -512,7 +512,6 @@ class learnpath
             $display_order = 0;
         }
 
-        $new_item_id = -1;
         $id = Database::escape_string($id);
         $typeCleaned = Database::escape_string($type);
         if ($type == 'quiz') {
@@ -535,79 +534,34 @@ class learnpath
             $max_score = 100;
         }
 
+        $params = array(
+            "c_id" => $course_id,
+            "lp_id" => $this->get_id(),
+            "item_type" =>$typeCleaned ,
+            "ref" => '',
+            "title" =>$title ,
+            "description" => $description,
+            "path" => $id,
+            "max_score" => $max_score,
+            "parent_item_id" => $parent,
+            "previous_item_id" => $previous,
+            "next_item_id" => $next,
+            "display_order" => $display_order +1,
+            "prerequisite" => $prerequisites,
+            "max_time_allowed" => $max_time_allowed
+        );
+
         if ($prerequisites != 0) {
-            $sql_ins = "INSERT INTO " . $tbl_lp_item . " (
-                            c_id,
-                            lp_id, ".
-                "item_type, ".
-                "ref, ".
-                "title, ".
-                "description, ".
-                "path, ".
-                "max_score, ".
-                "parent_item_id, ".
-                "previous_item_id, ".
-                "next_item_id, ".
-                "display_order, ".
-                "prerequisite, ".
-                "max_time_allowed ".
-                ") VALUES (
-                            $course_id ,
-                            ".$this->get_id() . ", ".
-                "'" . $typeCleaned . "', ".
-                "'', ".
-                "'" . $title . "', ".
-                "'" . $description . "', ".
-                "'" . $id . "', ".
-                "'" . $max_score . "', ".
-                $parent . ", ".
-                $previous . ", ".
-                $next . ", ".
-                ($display_order +1) . ", ".
-                $prerequisites . ", ".
-                $max_time_allowed .
-                ")";
-        } else {
-            // Insert new item.
-            $sql_ins = "INSERT INTO " . $tbl_lp_item . " ( ".
-                "c_id, ".
-                "lp_id, ".
-                "item_type, ".
-                "ref, ".
-                "title, ".
-                "description, ".
-                "path, ".
-                "max_score, ".
-                "parent_item_id, ".
-                "previous_item_id, ".
-                "next_item_id, ".
-                "display_order, ".
-                "max_time_allowed ".
-                ") VALUES (".
-                $course_id. ",".
-                $this->get_id() . ",".
-                "'" . $typeCleaned . "',".
-                "'',".
-                "'" . $title . "',".
-                "'" . $description . "',".
-                "'" . $id . "',".
-                "'" . $max_score . "',".
-                $parent . ",".
-                $previous . ",".
-                $next . ",".
-                ($display_order +1) . ",".
-                $max_time_allowed .
-                ")";
+            $params['prerequisite'] = $prerequisites;
         }
 
+        $new_item_id = Database::insert($tbl_lp_item, $params);
+
         if ($this->debug > 2) {
-            error_log('New LP - Inserting dokeos_chapter: ' . $sql_ins, 0);
+            error_log('New LP - Inserting dokeos_chapter: ' . $new_item_id, 0);
         }
 
-        $res_ins = Database::query($sql_ins);
-
-        if ($res_ins > 0) {
-            $new_item_id = Database :: insert_id($res_ins);
+        if ($new_item_id) {
 
             // Update the item that should come after the new item.
             $sql_update_next = "
@@ -628,7 +582,7 @@ class learnpath
             // Update all the items after the new item.
             $sql_update_order = "
                             UPDATE " . $tbl_lp_item . "
-                            SET display_order = display_order + 1
+                                SET display_order = display_order + 1
                             WHERE
                                 c_id = $course_id AND
                                 lp_id = " . $this->get_id() . " AND
@@ -643,72 +597,72 @@ class learnpath
                                SET ref = " . $new_item_id . "
                                WHERE c_id = $course_id AND id = " . $new_item_id;
             Database::query($sql_update_ref);
-        }
 
-        // Upload audio.
-        if (!empty ($_FILES['mp3']['name'])) {
-            // Create the audio folder if it does not exist yet.
-            global $_course;
-            $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/';
-            if (!is_dir($filepath . 'audio')) {
-                mkdir($filepath . 'audio', api_get_permissions_for_new_directories());
-                $audio_id = add_document(
+            // Upload audio.
+            if (!empty($_FILES['mp3']['name'])) {
+                // Create the audio folder if it does not exist yet.
+                global $_course;
+                $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/';
+                if (!is_dir($filepath . 'audio')) {
+                    mkdir($filepath . 'audio', api_get_permissions_for_new_directories());
+                    $audio_id = add_document(
+                        $_course,
+                        '/audio',
+                        'folder',
+                        0,
+                        'audio'
+                    );
+                    api_item_property_update(
+                        $_course,
+                        TOOL_DOCUMENT,
+                        $audio_id,
+                        'FolderCreated',
+                        api_get_user_id(),
+                        null,
+                        null,
+                        null,
+                        null,
+                        api_get_session_id()
+                    );
+                    api_item_property_update(
+                        $_course,
+                        TOOL_DOCUMENT,
+                        $audio_id,
+                        'invisible',
+                        api_get_user_id(),
+                        null,
+                        null,
+                        null,
+                        null,
+                        api_get_session_id()
+                    );
+                }
+
+                // Upload the file in the documents tool.
+                include_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+                $file_path = handle_uploaded_document(
                     $_course,
+                    $_FILES['mp3'],
+                    api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document',
                     '/audio',
-                    'folder',
-                    0,
-                    'audio'
-                );
-                api_item_property_update(
-                    $_course,
-                    TOOL_DOCUMENT,
-                    $audio_id,
-                    'FolderCreated',
-                    api_get_user_id(),
-                    null,
-                    null,
-                    null,
-                    null,
-                    api_get_session_id()
-                );
-                api_item_property_update(
-                    $_course,
-                    TOOL_DOCUMENT,
-                    $audio_id,
-                    'invisible',
                     api_get_user_id(),
-                    null,
-                    null,
-                    null,
-                    null,
-                    api_get_session_id()
+                    '',
+                    '',
+                    '',
+                    '',
+                    false
                 );
-            }
 
-            // Upload the file in the documents tool.
-            include_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
-            $file_path = handle_uploaded_document(
-                $_course,
-                $_FILES['mp3'],
-                api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document',
-                '/audio',
-                api_get_user_id(),
-                '',
-                '',
-                '',
-                '',
-                false
-            );
+                // Getting the filename only.
+                $file_components = explode('/', $file_path);
+                $file = $file_components[count($file_components) - 1];
 
-            // Getting the filename only.
-            $file_components = explode('/', $file_path);
-            $file = $file_components[count($file_components) - 1];
-
-            // Store the mp3 file in the lp_item table.
-            $sql = "UPDATE $tbl_lp_item SET
+                // Store the mp3 file in the lp_item table.
+                $sql = "UPDATE $tbl_lp_item SET
                         audio = '" . Database::escape_string($file) . "'
                     WHERE id = '" . Database::escape_string($new_item_id) . "'";
-            Database::query($sql);
+                Database::query($sql);
+            }
         }
 
         return $new_item_id;
@@ -842,66 +796,102 @@ class learnpath
     public function autocomplete_parents($item)
     {
         $debug = $this->debug;
+
         if ($debug) {
             error_log('Learnpath::autocomplete_parents()', 0);
         }
+
         if (empty($item)) {
             $item = $this->current;
         }
-        $parent_id = $this->items[$item]->get_parent();
 
-        if (isset($this->items[$item]) && is_object($this->items[$item]) and !empty($parent_id)) {
-            // if $item points to an object and there is a parent.
-            if ($debug) {
-                error_log('Autocompleting parent of item ' . $item . ' (item ' . $parent_id . ')', 0);
-            }
-            $current_item = $this->items[$item];
-            $parent = $this->items[$parent_id]; // Get the parent.
-            // New experiment including failed and browsed in completed status.
-            $current_status = $current_item->get_status();
-            //if ($current_item->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
-            // Fixes chapter autocomplete
-            if (true) {
-                // If the current item is completed or passes or succeeded.
-                $completed = true;
+        $currentItem = $this->getItem($item);
+        if ($currentItem) {
+            $parent_id = $currentItem->get_parent();
+            $parent = $this->getItem($parent_id);
+            if ($parent) {
+                // if $item points to an object and there is a parent.
                 if ($debug) {
-                    error_log('Status of current item is alright', 0);
+                    error_log(
+                        'Autocompleting parent of item ' . $item . ' "'.$currentItem->get_title().'" (item ' . $parent_id . ' "'.$parent->get_title().'") ',
+                        0
+                    );
                 }
 
-                foreach ($parent->get_children() as $child) {
-                    // Check all his brothers (parent's children) for completion status.
-                    if ($child != $item) {
-                        if ($debug) {
-                            error_log('Looking at brother with ID ' . $child . ', status is ' . $this->items[$child]->get_status(), 0);
+                // New experiment including failed and browsed in completed status.
+                //$current_status = $currentItem->get_status();
+                //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
+                // Fixes chapter auto complete
+                if (true) {
+                    // If the current item is completed or passes or succeeded.
+                    $updateParentStatus = true;
+                    if ($debug) {
+                        error_log('Status of current item is alright', 0);
+                    }
+
+                    foreach ($parent->get_children() as $childItemId) {
+                        $childItem = $this->getItem($childItemId);
+
+                        // If children was not set try to get the info
+                        if (empty($childItem->db_item_view_id)) {
+                            $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
                         }
-                        //if($this->items[$child]->status_is(array('completed','passed','succeeded')))
-                        // Trying completing parents of failed and browsed items as well.
-                        if ($this->items[$child]->status_is(array(
-                            'completed',
-                            'passed',
-                            'succeeded',
-                            'browsed',
-                            'failed'
-                        ))) {
-                            // Keep completion status to true.
-                        } else {
-                            if ($this->debug > 2) {
-                                error_log('Found one incomplete child of ' . $parent_id . ': ' . $child . ' is ' . $this->items[$child]->get_status(), 0);
+
+                        // Check all his brothers (parent's children) for completion status.
+                        if ($childItemId != $item) {
+                            if ($debug) {
+                                error_log(
+                                    'Looking at brother #'.$childItemId . ' "' . $childItem->get_title() . '", status is ' . $childItem->get_status(),
+                                    0
+                                );
+                            }
+                            // Trying completing parents of failed and browsed items as well.
+                            if ($childItem->status_is(
+                                array(
+                                    'completed',
+                                    'passed',
+                                    'succeeded',
+                                    'browsed',
+                                    'failed'
+                                )
+                            )
+                            ) {
+                                // Keep completion status to true.
+                                continue;
+                            } else {
+                                if ($debug > 2) {
+                                    error_log(
+                                        'Found one incomplete child of parent #' . $parent_id . ': child #'.$childItemId . ' "' . $childItem->get_title() . '", is ' . $childItem->get_status().' db_item_view_id:#'.$childItem->db_item_view_id,
+                                        0
+                                    );
+                                }
+                                $updateParentStatus = false;
+                                break;
                             }
-                            $completed = false;
-                            break;
                         }
                     }
-                }
 
-                if ($completed) { // If all the children were completed:
-                    $parent->set_status('completed');
-                    $parent->save(false, $this->prerequisites_match($parent->get_id()));
-                    $this->update_queue[$parent->get_id()] = $parent->get_status();
-                    if ($debug) {
-                        error_log('Added parent to update queue ' . print_r($this->update_queue, true), 0);
+                    if ($updateParentStatus) {
+                        // If all the children were completed:
+                        $parent->set_status('completed');
+                        $parent->save(false, $this->prerequisites_match($parent->get_id()));
+                        // Force the status to "completed"
+                        //$this->update_queue[$parent->get_id()] = $parent->get_status();
+                        $this->update_queue[$parent->get_id()] = 'completed';
+                        if ($debug) {
+                            error_log(
+                                'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
+                                print_r($this->update_queue, 1),
+                                0
+                            );
+                        }
+                        // Recursive call.
+                        $this->autocomplete_parents($parent->get_id());
                     }
-                    $this->autocomplete_parents($parent->get_id()); // Recursive call.
+                }
+            } else {
+                if ($debug) {
+                    error_log("Parent #$parent_id does not exists");
                 }
             }
         } else {
@@ -4012,49 +4002,61 @@ class learnpath
      * and the prerequisite string on error.
      * This function is based on the rules for aicc_script language as
      * described in the SCORM 1.2 CAM documentation page 108.
-     * @param	integer	Optional item ID. If none given, uses the current open item.
+     * @param	integer	$itemId Optional item ID. If none given, uses the current open item.
      * @return	boolean	True if prerequisites are matched, false otherwise -
      * Empty string if true returned, prerequisites string otherwise.
      */
-    public function prerequisites_match($item = null)
+    public function prerequisites_match($itemId = null)
     {
-        if ($this->debug > 0) {
+        $debug = $this->debug;
+        if ($debug > 0) {
             error_log('In learnpath::prerequisites_match()', 0);
         }
-        if (empty($item)) {
-            $item = $this->current;
+
+        if (empty($itemId)) {
+            $itemId = $this->current;
         }
-        if (isset($this->items[$item]) && is_object($this->items[$item])) {
 
+        $currentItem = $this->getItem($itemId);
+
+        if ($currentItem) {
             if ($this->type == 2) {
-                //Getting prereq from scorm
-                $prereq_string = $this->get_scorm_prereq_string($item);
+                // Getting prereq from scorm
+                $prereq_string = $this->get_scorm_prereq_string($itemId);
             } else {
-                $prereq_string = $this->items[$item]->get_prereq_string();
+                $prereq_string = $currentItem->get_prereq_string();
             }
 
             if (empty($prereq_string)) {
+                if ($debug > 0) {
+                    error_log('Found prereq_string is empty return true');
+                }
                 return true;
             }
             // Clean spaces.
             $prereq_string = str_replace(' ', '', $prereq_string);
-            if ($this->debug > 0) {
+            if ($debug > 0) {
                 error_log('Found prereq_string: ' . $prereq_string, 0);
             }
             // Now send to the parse_prereq() function that will check this component's prerequisites.
-            $result = $this->items[$item]->parse_prereq($prereq_string, $this->items, $this->refs_list, $this->get_user_id());
+            $result = $currentItem->parse_prereq(
+                $prereq_string,
+                $this->items,
+                $this->refs_list,
+                $this->get_user_id()
+            );
 
             if ($result === false) {
-                $this->set_error_msg($this->items[$item]->prereq_alert);
+                $this->set_error_msg($currentItem->prereq_alert);
             }
         } else {
             $result = true;
-            if ($this->debug > 1) {
-                error_log('$this->items[' . $item . '] was not an object', 0);
+            if ($debug > 1) {
+                error_log('$this->items[' . $itemId . '] was not an object', 0);
             }
         }
 
-        if ($this->debug > 1) {
+        if ($debug > 1) {
             error_log('End of prerequisites_match(). Error message is now ' . $this->error, 0);
         }
         return $result;
@@ -9839,6 +9841,19 @@ EOD;
 
         return $learnPath;
     }
+
+    /**
+     * @param int $itemId
+     * @return learnpathItem|false
+     */
+    public function getItem($itemId)
+    {
+        if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
+            return $this->items[$itemId];
+        }
+
+        return false;
+    }
 }
 
 if (!function_exists('trim_value')) {

+ 231 - 252
main/newscorm/learnpathItem.class.php

@@ -379,7 +379,7 @@ class learnpathItem
         }
         $res = 1;
         if (!empty($this->attempt_id)) {
-            $res = $this->attempt_id;
+            $res = intval($this->attempt_id);
         }
         if (self::debug > 0) {
             error_log(
@@ -403,10 +403,10 @@ class learnpathItem
         $list = array();
         foreach ($this->children as $child) {
             if (!empty($child)) {
-                //error_log('New LP - Found '.$child, 0);
                 $list[] = $child;
             }
         }
+
         return $list;
     }
 
@@ -632,8 +632,9 @@ class learnpathItem
                 $iva_table = Database::get_course_table(
                     TABLE_LP_IV_INTERACTION
                 );
-                $iva_sql = "SELECT count(id) as mycount FROM $iva_table " .
-                    "WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id ";
+                $iva_sql = "SELECT count(id) as mycount
+                            FROM $iva_table
+                            WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id ";
                 $res_sql = Database::query($iva_sql);
                 if (Database::num_rows($res_sql) > 0) {
                     $row = Database::fetch_array($res_sql);
@@ -1690,11 +1691,12 @@ class learnpathItem
     public function get_status($check_db = true, $update_local = false)
     {
         $course_id = api_get_course_int_id();
-        if (self::debug > 0) {
+        $debug = self::debug;
+        if ($debug > 0) {
             error_log('learnpathItem::get_status() on item ' . $this->db_id, 0);
         }
         if ($check_db) {
-            if (self::debug > 2) {
+            if ($debug > 2) {
                 error_log('learnpathItem::get_status(): checking db', 0);
             }
             if (!empty($this->db_item_view_id)) {
@@ -1704,7 +1706,8 @@ class learnpathItem
                             c_id = $course_id AND
                             id = '" . $this->db_item_view_id . "' AND
                             view_count = '" . $this->get_attempt_id() . "'";
-                if (self::debug > 2) {
+
+                if ($debug > 2) {
                     error_log(
                         'learnpathItem::get_status() - Checking DB: ' . $sql,
                         0
@@ -1715,9 +1718,15 @@ class learnpathItem
                 if (Database::num_rows($res) == 1) {
                     $row = Database::fetch_array($res);
                     if ($update_local) {
+                        if ($debug > 2) {
+                            error_log(
+                                'learnpathItem::set_status() :' . $row['status'],
+                                0
+                            );
+                        }
                         $this->set_status($row['status']);
                     }
-                    if (self::debug > 2) {
+                    if ($debug > 2) {
                         error_log(
                             'learnpathItem::get_status() - Returning db value ' . $row['status'],
                             0
@@ -1727,14 +1736,14 @@ class learnpathItem
                 }
             }
         } else {
-            if (self::debug > 2) {
+            if ($debug > 2) {
                 error_log(
                     'learnpathItem::get_status() - in get_status: using attrib',
                     0
                 );
             }
             if (!empty($this->status)) {
-                if (self::debug > 2) {
+                if ($debug > 2) {
                     error_log(
                         'learnpathItem::get_status() - Returning attrib: ' . $this->status,
                         0
@@ -1743,12 +1752,14 @@ class learnpathItem
                 return $this->status;
             }
         }
-        if (self::debug > 2) {
+
+        if ($debug > 2) {
             error_log(
                 'learnpathItem::get_status() - Returning default ' . $this->possible_status[0],
                 0
             );
         }
+
         return $this->possible_status[0];
     }
 
@@ -1886,7 +1897,7 @@ class learnpathItem
         $sql = "SELECT * FROM $lp_item
                 WHERE
                     c_id = $course_id AND
-                    id='" . Database::escape_string($this->db_id) . "'";
+                    id='" . intval($this->db_id) . "'";
         $res = Database::query($sql);
         $row = Database::fetch_array($res);
         return $row['terms'];
@@ -2005,14 +2016,19 @@ class learnpathItem
 
     /**
      * Tells if an item is done ('completed','passed','succeeded') or not
-     * @return    bool    True if the item is done ('completed','passed','succeeded'), false otherwise
+     * @return bool True if the item is done ('completed','passed','succeeded'),
+     * false otherwise
      */
-    function is_done()
+    public function is_done()
     {
-        if ($this->status_is(
-            array('completed', 'passed', 'succeeded', 'failed')
-        )
-        ) {
+        $completedStatusList = array(
+            'completed',
+            'passed',
+            'succeeded',
+            'failed'
+        );
+
+        if ($this->status_is($completedStatusList)) {
             if (self::debug > 2) {
                 error_log(
                     'learnpath::is_done() - Item ' . $this->get_id(
@@ -2020,6 +2036,7 @@ class learnpathItem
                     0
                 );
             }
+
             return true;
         } else {
             if (self::debug > 2) {
@@ -2029,6 +2046,7 @@ class learnpathItem
                     0
                 );
             }
+
             return false;
         }
     }
@@ -2125,11 +2143,16 @@ class learnpathItem
 
     /**
      * Parses the prerequisites string with the AICC logic language
-     * @param    string    The prerequisites string as it figures in imsmanifest.xml
-     * @param    Array    Array of items in the current learnpath object. Although we're in the learnpathItem object, it's necessary to have a list of all items to be able to check the current item's prerequisites
-     * @param    Array    List of references (the "ref" column in the lp_item table) that are strings used in the expression of prerequisites.
-     * @param    integer    The user ID. In some cases like Chamilo quizzes, it's necessary to have the user ID to query other tables (like the results of quizzes)
-     * @return    boolean    True if the list of prerequisites given is entirely satisfied, false otherwise
+     * @param    string   $prereqs_string The prerequisites string as it figures in imsmanifest.xml
+     * @param    Array    $items Array of items in the current learnpath object.
+     * Although we're in the learnpathItem object, it's necessary to have
+     * a list of all items to be able to check the current item's prerequisites
+     * @param    Array    $refs_list List of references
+     * (the "ref" column in the lp_item table) that are strings used in the
+     * expression of prerequisites.
+     * @param    integer  $user_id The user ID. In some cases like Chamilo quizzes,
+     * it's necessary to have the user ID to query other tables (like the results of quizzes)
+     * @return boolean True if the list of prerequisites given is entirely satisfied, false otherwise
      */
     public function parse_prereq($prereqs_string, $items, $refs_list, $user_id)
     {
@@ -2195,16 +2218,16 @@ class learnpathItem
                 error_log('New LP - Didnt find any OR, looking for AND', 0);
             }
             if (strpos($prereqs_string, '&') !== false) {
-                $list = split('&', $prereqs_string);
+                $list = explode('&', $prereqs_string);
                 if (count($list) > 1) {
                     $andstatus = true;
                     foreach ($list as $condition) {
                         $andstatus = $andstatus && $this->parse_prereq(
-                                $condition,
-                                $items,
-                                $refs_list,
-                                $user_id
-                            );
+                            $condition,
+                            $items,
+                            $refs_list,
+                            $user_id
+                        );
                         if (!$andstatus) {
                             if (self::debug > 1) {
                                 error_log(
@@ -2223,22 +2246,14 @@ class learnpathItem
                     return $andstatus;
                 } else {
                     if (isset($items[$refs_list[$list[0]]])) {
-                        $status = $items[$refs_list[$list[0]]]->get_status(
-                            true
-                        );
-                        $returnstatus =
-                            ($status == $this->possible_status[2])
-                                OR ($status == $this->possible_status[3]);
+                        $status = $items[$refs_list[$list[0]]]->get_status(true);
+                        $returnstatus = ($status == $this->possible_status[2]) OR ($status == $this->possible_status[3]);
                         if (empty($this->prereq_alert) && !$returnstatus) {
-                            $this->prereq_alert = get_lang(
-                                'LearnpathPrereqNotCompleted'
-                            );
+                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
                         }
                         return $returnstatus;
                     }
-                    $this->prereq_alert = get_lang(
-                        'LearnpathPrereqNotCompleted'
-                    );
+                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
                     return false;
                 }
             } else {
@@ -2252,24 +2267,19 @@ class learnpathItem
                         error_log('New LP - Found =, looking into it', 0);
                     }
                     // We assume '=' signs only appear when there's nothing else around.
-                    $params = split('=', $prereqs_string);
+                    $params = explode('=', $prereqs_string);
                     if (count($params) == 2) {
                         // Right number of operands.
                         if (isset($items[$refs_list[$params[0]]])) {
-                            $status = $items[$refs_list[$params[0]]]->get_status(
-                                true
-                            );
+                            $status = $items[$refs_list[$params[0]]]->get_status(true);
                             $returnstatus = ($status == $params[1]);
                             if (empty($this->prereq_alert) && !$returnstatus) {
-                                $this->prereq_alert = get_lang(
-                                    'LearnpathPrereqNotCompleted'
-                                );
+                                $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
                             }
                             return $returnstatus;
                         }
-                        $this->prereq_alert = get_lang(
-                            'LearnpathPrereqNotCompleted'
-                        );
+                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
+
                         return false;
                     }
                 } else {
@@ -2286,24 +2296,19 @@ class learnpathItem
                             error_log('New LP - Found <>, looking into it', 0);
                         }
                         // We assume '<>' signs only appear when there's nothing else around.
-                        $params = split('<>', $prereqs_string);
+                        $params = explode('<>', $prereqs_string);
                         if (count($params) == 2) {
                             // Right number of operands.
                             if (isset($items[$refs_list[$params[0]]])) {
-                                $status = $items[$refs_list[$params[0]]]->get_status(
-                                    true
-                                );
+                                $status = $items[$refs_list[$params[0]]]->get_status(true);
                                 $returnstatus = ($status != $params[1]);
                                 if (empty($this->prereq_alert) && !$returnstatus) {
-                                    $this->prereq_alert = get_lang(
-                                        'LearnpathPrereqNotCompleted'
-                                    );
+                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
                                 }
+
                                 return $returnstatus;
                             }
-                            $this->prereq_alert = get_lang(
-                                'LearnpathPrereqNotCompleted'
-                            );
+                            $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
                             return false;
                         }
                     } else {
@@ -2337,9 +2342,7 @@ class learnpathItem
                                     $user_id
                                 );
                                 if (empty($this->prereq_alert) && !$returnstatus) {
-                                    $this->prereq_alert = get_lang(
-                                        'LearnpathPrereqNotCompleted'
-                                    );
+                                    $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
                                 }
                                 return $returnstatus;
                             } else {
@@ -2393,14 +2396,14 @@ class learnpathItem
                                             );
                                         }
                                         $count = $multi[1];
-                                        $list = split(',', $multi[2]);
+                                        $list = explode(',', $multi[2]);
                                         $mytrue = 0;
                                         foreach ($list as $cond) {
                                             if (isset($items[$refs_list[$cond]])) {
-                                                $status = $items[$refs_list[$cond]]->get_status(
-                                                    true
-                                                );
-                                                if (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3])) {
+                                                $status = $items[$refs_list[$cond]]->get_status(true);
+                                                if ($status == $this->possible_status[2] OR
+                                                    $status == $this->possible_status[3]
+                                                ) {
                                                     $mytrue++;
                                                     if (self::debug > 1) {
                                                         error_log(
@@ -2441,14 +2444,14 @@ class learnpathItem
                                                 0
                                             );
                                         }
-                                        $list = split(',', $gr);
+                                        $list = explode(',', $gr);
                                         $mycond = true;
                                         foreach ($list as $cond) {
                                             if (isset($items[$refs_list[$cond]])) {
-                                                $status = $items[$refs_list[$cond]]->get_status(
-                                                    true
-                                                );
-                                                if (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3])) {
+                                                $status = $items[$refs_list[$cond]]->get_status(true);
+                                                if ($status == $this->possible_status[2] OR
+                                                    $status == $this->possible_status[3]
+                                                ) {
                                                     $mycond = true;
                                                     if (self::debug > 1) {
                                                         error_log(
@@ -2486,9 +2489,7 @@ class learnpathItem
                                         }
                                     }
                                     if (!$mycond && empty($this->prereq_alert)) {
-                                        $this->prereq_alert = get_lang(
-                                            'LearnpathPrereqNotCompleted'
-                                        );
+                                        $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
                                     }
                                     return $mycond;
                                 }
@@ -2503,15 +2504,14 @@ class learnpathItem
                                     );
                                 }
 
-                                if (isset($refs_list[$prereqs_string]) && isset($items[$refs_list[$prereqs_string]])) {
+                                if (isset($refs_list[$prereqs_string]) &&
+                                    isset($items[$refs_list[$prereqs_string]])
+                                ) {
                                     if ($items[$refs_list[$prereqs_string]]->type == 'quiz') {
 
                                         // 1. Checking the status in current items.
-                                        $status = $items[$refs_list[$prereqs_string]]->get_status(
-                                            true
-                                        );
-                                        //error_log('hello '.$status);
-                                        $returnstatus = (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3]));
+                                        $status = $items[$refs_list[$prereqs_string]]->get_status(true);
+                                        $returnstatus = $status == $this->possible_status[2] OR $status == $this->possible_status[3];
 
                                         if (!$returnstatus) {
                                             if (self::debug > 1) {
@@ -2536,27 +2536,16 @@ class learnpathItem
                                             if ($returnstatus) {
                                                 //AND origin_lp_item_id = '.$user_id.'
                                                 $sql = 'SELECT exe_result, exe_weighting
-                                                        FROM ' . Database :: get_statistic_table(
-                                                        TABLE_STATISTIC_TRACK_E_EXERCICES
-                                                    ) . '
+                                                        FROM ' . Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES) . '
                                                     WHERE   exe_exo_id = ' . $items[$refs_list[$prereqs_string]]->path . '
                                                         AND exe_user_id = ' . $user_id . '
                                                         AND orig_lp_id = ' . $this->lp_id . ' AND orig_lp_item_id = ' . $prereqs_string . '
                                                         AND status <> "incomplete"
                                                     ORDER BY exe_date DESC
                                                     LIMIT 0, 1';
-                                                //error_log('results :'.$items[$refs_list[$prereqs_string]]->path. ':'.$user_id);
-
-                                                $rs_quiz = Database::query(
-                                                    $sql
-                                                );
-                                                if ($quiz = Database :: fetch_array(
-                                                    $rs_quiz
-                                                )
-                                                ) {
-                                                    if ($quiz['exe_result'] >= $items[$refs_list[$prereqs_string]]->get_mastery_score(
-                                                        )
-                                                    ) {
+                                                $rs_quiz = Database::query($sql);
+                                                if ($quiz = Database :: fetch_array($rs_quiz)) {
+                                                    if ($quiz['exe_result'] >= $items[$refs_list[$prereqs_string]]->get_mastery_score()) {
                                                         $returnstatus = true;
                                                     } else {
                                                         $this->prereq_alert = get_lang(
@@ -2585,16 +2574,9 @@ class learnpathItem
                                             //error_log('results 2:'.$items[$refs_list[$prereqs_string]]->path. ':'.$user_id);
 
                                             $rs_quiz = Database::query($sql);
-                                            if (Database::num_rows(
-                                                    $rs_quiz
-                                                ) > 0
-                                            ) {
-                                                while ($quiz = Database :: fetch_array(
-                                                    $rs_quiz
-                                                )) {
-                                                    if ($quiz['exe_result'] >= $items[$refs_list[$prereqs_string]]->get_mastery_score(
-                                                        )
-                                                    ) {
+                                            if (Database::num_rows($rs_quiz) > 0) {
+                                                while ($quiz = Database :: fetch_array($rs_quiz)) {
+                                                    if ($quiz['exe_result'] >= $items[$refs_list[$prereqs_string]]->get_mastery_score()) {
                                                         $returnstatus = true;
                                                         break;
                                                     } else {
@@ -2613,10 +2595,8 @@ class learnpathItem
                                         }
                                         return $returnstatus;
                                     } else {
-                                        $status = $items[$refs_list[$prereqs_string]]->get_status(
-                                            false
-                                        );
-                                        $returnstatus = (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3]));
+                                        $status = $items[$refs_list[$prereqs_string]]->get_status(false);
+                                        $returnstatus = $status == $this->possible_status[2] OR $status == $this->possible_status[3];
 
                                         if (!$returnstatus) {
                                             if (self::debug > 1) {
@@ -2701,7 +2681,7 @@ class learnpathItem
                 }
             }
         } else {
-            $list = split("\|", $prereqs_string);
+            $list = explode("\|", $prereqs_string);
             if (count($list) > 1) {
                 if (self::debug > 1) {
                     error_log('New LP - Found OR, looking into it', 0);
@@ -2844,7 +2824,8 @@ class learnpathItem
         if ($this->type == 'sco' || $this->type == 'au') {
             $status = $this->get_status(true);
             if ($this->prevent_reinit == 1 AND
-                $status != $this->possible_status[0] AND $status != $this->possible_status[1]
+                $status != $this->possible_status[0] AND
+                $status != $this->possible_status[1]
             ) {
                 if (self::debug > 1) {
                     error_log(
@@ -2870,7 +2851,6 @@ class learnpathItem
                         );
                     }
                     foreach ($_GET as $param => $value) {
-                        $value = Database::escape_string($value);
                         switch ($param) {
                             case 'score':
                                 $this->set_score($value);
@@ -3074,7 +3054,7 @@ class learnpathItem
             error_log('learnpathItem::set_lesson_location()', 0);
         }
         if (isset($location)) {
-            $this->lesson_location = Database::escape_string($location);
+            $this->lesson_location = $location;
             return true;
         }
         return false;
@@ -3099,7 +3079,7 @@ class learnpathItem
      * Sets the lp_view id this item view is registered to
      * @param int $lp_view_id   lp_view DB ID
      * @param int $course_id
-     * @return  void
+     * @return  bool
      * @todo //todo insert into lp_item_view if lp_view not exists
      */
     public function set_lp_view($lp_view_id, $course_id = null)
@@ -3121,6 +3101,7 @@ class learnpathItem
                     0
                 );
             }
+
             return false;
         }
 
@@ -3131,6 +3112,7 @@ class learnpathItem
                     0
                 );
             }
+
             return false;
         }
 
@@ -3143,9 +3125,10 @@ class learnpathItem
         $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
         // Get the lp_item_view with the highest view_count.
         $sql = "SELECT * FROM $item_view_table
-                WHERE   c_id = $course_id AND
-                        lp_item_id = " . $lpItemId . " AND
-                        lp_view_id = " . $lp_view_id . "
+                WHERE
+                    c_id = $course_id AND
+                    lp_item_id = " . $lpItemId . " AND
+                    lp_view_id = " . $lp_view_id . "
                 ORDER BY view_count DESC";
 
         if (self::debug > 2) {
@@ -3211,6 +3194,8 @@ class learnpathItem
         if (self::debug > 2) {
             error_log('New LP - End of learnpathItem::set_lp_view()', 0);
         }
+
+        return true;
     }
 
     /**
@@ -3302,7 +3287,7 @@ class learnpathItem
             error_log('learnpathItem::set_max_score(' . $score . ')', 0);
         }
         if (is_int($score) or $score == '') {
-            $this->view_max_score = Database::escape_string($score);
+            $this->view_max_score = $score;
             if (self::debug > 1) {
                 error_log(
                     'learnpathItem::set_max_score() - ' .
@@ -3336,7 +3321,7 @@ class learnpathItem
         }
 
         if ($found) {
-            $this->status = Database::escape_string($status);
+            $this->status = $status;
             if (self::debug > 1) {
                 error_log(
                     'learnpathItem::set_status() - '.
@@ -3488,7 +3473,8 @@ class learnpathItem
      * @param  array  $list  An array of status to check for.
      * If the current status is one of the strings, return true
      *
-     * @return    boolean True if the status was one of the given strings, false otherwise
+     * @return boolean True if the status was one of the given strings,
+     * false otherwise
      */
     public function status_is($list = array())
     {
@@ -3501,13 +3487,13 @@ class learnpathItem
                 0
             );
         }
-        $mystatus = $this->get_status(true);
-        if (empty($mystatus)) {
+        $currentStatus = $this->get_status(true);
+        if (empty($currentStatus)) {
             return false;
         }
         $found = false;
         foreach ($list as $status) {
-            if (preg_match('/^' . $status . '$/i', $mystatus)) {
+            if (preg_match('/^' . $status . '$/i', $currentStatus)) {
                 if (self::debug > 2) {
                     error_log(
                         'New LP - learnpathItem::status_is() - Found status ' .
@@ -3516,16 +3502,18 @@ class learnpathItem
                     );
                 }
                 $found = true;
+
                 return $found;
             }
         }
         if (self::debug > 2) {
             error_log(
                 'New LP - learnpathItem::status_is() - Status ' .
-                    $mystatus . ' did not match request',
+                    $currentStatus . ' did not match request',
                 0
             );
         }
+
         return $found;
     }
 
@@ -3725,22 +3713,17 @@ class learnpathItem
                         Database::query($ivau_sql);
                     } else {
                         // Insert new one.
-                        $ivai_sql = "INSERT INTO $iva_table " .
-                            "(c_id, lp_iv_id, order_id, objective_id, status, score_raw, score_min, score_max )" .
-                            "VALUES" .
-                            "($course_id, " . $lp_iv_id . ", " . $index . ",'" . Database::escape_string(
-                                $objective[0]
-                            ) . "','" . Database::escape_string(
-                                $objective[1]
-                            ) . "'," .
-                            "'" . Database::escape_string(
-                                $objective[2]
-                            ) . "','" . Database::escape_string(
-                                $objective[4]
-                            ) . "','" . Database::escape_string(
-                                $objective[3]
-                            ) . "')";
-                        Database::query($ivai_sql);
+                        $params = array(
+                            'c_id' => $course_id,
+                            'lp_iv_id' => $lp_iv_id,
+                            'order_id' => $index,
+                            'objective_id' => $objective[0],
+                            'status' => $objective[1],
+                            'score_raw' => $objective[2],
+                            'score_min' => $objective[4],
+                            'score_max' =>$objective[3]
+                        );
+                        Database::insert($iva_table, $params);
                     }
                 }
             }
@@ -3794,8 +3777,8 @@ class learnpathItem
         }
 
         if ((($save === false && $this->type == 'sco') ||
-           ($this->type == 'sco' && ($credit == 'no-credit' OR $mode == 'review' OR $mode == 'browse'))
-           ) && ($this->seriousgame_mode != 1 && $this->type == 'sco')
+           ($this->type == 'sco' && ($credit == 'no-credit' OR $mode == 'review' OR $mode == 'browse'))) &&
+            ($this->seriousgame_mode != 1 && $this->type == 'sco')
         ) {
             if (self::debug > 1) {
                 error_log(
@@ -3817,49 +3800,37 @@ class learnpathItem
             ) {
                 // We force the item to be restarted.
                 $this->restart();
-
-                $sql = "INSERT INTO $item_view_table " .
-                    "(c_id, total_time, " .
-                    "start_time, " .
-                    "score, " .
-                    "status, " .
-                    "max_score, " .
-                    "lp_item_id, " .
-                    "lp_view_id, " .
-                    "view_count, " .
-                    "suspend_data, " .
-                    //"max_time_allowed," .
-                    "lesson_location)" .
-                    "VALUES" .
-                    "($course_id, " . $this->get_total_time() . "," .
-                    "" . $this->current_start_time . "," .
-                    "" . $this->get_score() . "," .
-                    "'" . $this->get_status(false) . "'," .
-                    "'" . $this->get_max() . "'," .
-                    "" . $this->db_id . "," .
-                    "" . $this->view_id . "," .
-                    "" . $this->get_attempt_id() . "," .
-                    "'" . Database::escape_string($this->current_data) . "'," .
-                    //"'".$this->get_max_time_allowed()."'," .
-                    "'" . $this->lesson_location . "')";
+                $params = array(
+                    "c_id" => $course_id,
+                    "total_time" => $this->get_total_time(),
+                    "start_time" => $this->current_start_time,
+                    "score" => $this->get_score(),
+                    "status" => $this->get_status(false),
+                    "max_score" => $this->get_max(),
+                    "lp_item_id" => $this->db_id,
+                    "lp_view_id" => $this->view_id,
+                    "view_count" => $this->get_attempt_id() ,
+                    "suspend_data" => $this->current_data,
+                    //"max_time_allowed" => ,
+                    "lesson_location" => $this->lesson_location
+                );
                 if (self::debug > 2) {
                     error_log(
-                        'learnpathItem::write_to_db() - Inserting into item_view forced: ' . $sql,
+                        'learnpathItem::write_to_db() - Inserting into item_view forced: ' . print_r($params, 1),
                         0
                     );
                 }
-                Database::query($sql);
-                $this->db_item_view_id = Database::insert_id();
+                $this->db_item_view_id = Database::insert($item_view_table, $params);
                 $inserted = true;
             }
 
             $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
             $check = "SELECT * FROM $item_view_table
                       WHERE
-                            c_id = $course_id AND
-                            lp_item_id = " . $this->db_id . " AND
-                            lp_view_id = " . $this->view_id . " AND
-                            view_count = " . $this->get_attempt_id();
+                        c_id = $course_id AND
+                        lp_item_id = " . $this->db_id . " AND
+                        lp_view_id = " . $this->view_id . " AND
+                        view_count = " . intval($this->get_attempt_id());
             if (self::debug > 2) {
                 error_log(
                     'learnpathItem::write_to_db() - Querying item_view: ' . $check,
@@ -3870,54 +3841,45 @@ class learnpathItem
             // Depending on what we want (really), we'll update or insert a new row
             // now save into DB.
             if (!$inserted && Database::num_rows($check_res) < 1) {
-                $sql = "INSERT INTO $item_view_table " .
-                    "(c_id, total_time, " .
-                    "start_time, " .
-                    "score, " .
-                    "status, " .
-                    "max_score, " .
-                    "lp_item_id, " .
-                    "lp_view_id, " .
-                    "view_count, " .
-                    "suspend_data, " .
-                    //"max_time_allowed," .
-                    "lesson_location)" .
-                    "VALUES" .
-                    "($course_id, " . $this->get_total_time() . "," .
-                    "" . $this->current_start_time . "," .
-                    "" . $this->get_score() . "," .
-                    "'" . $this->get_status(false) . "'," .
-                    "'" . $this->get_max() . "'," .
-                    "" . $this->db_id . "," .
-                    "" . $this->view_id . "," .
-                    "" . $this->get_attempt_id() . "," .
-                    "'" . Database::escape_string($this->current_data) . "'," .
-                    //"'".$this->get_max_time_allowed()."'," .
-                    "'" . $this->lesson_location . "')";
+                $params = array(
+                    "c_id" => $course_id,
+                    "total_time" => $this->get_total_time(),
+                    "start_time" => $this->current_start_time,
+                    "score" => $this->get_score(),
+                    "status" => $this->get_status(false),
+                    "max_score" => $this->get_max(),
+                    "lp_item_id" => $this->db_id,
+                    "lp_view_id" => $this->view_id,
+                    "view_count" => $this->get_attempt_id() ,
+                    "suspend_data" => $this->current_data,
+                    //"max_time_allowed" => ,$this->get_max_time_allowed()
+                    "lesson_location" => $this->lesson_location
+                );
+
                 if (self::debug > 2) {
                     error_log(
-                        'learnpathItem::write_to_db() - Inserting into item_view: ' . $sql,
+                        'learnpathItem::write_to_db() - Inserting into item_view forced: ' . print_r($params, 1),
                         0
                     );
                 }
-                Database::query($sql);
-                $this->db_item_view_id = Database::insert_id();
+
+                $this->db_item_view_id = Database::insert($item_view_table, $params);
             } else {
-                $sql = '';
                 if ($this->type == 'hotpotatoes') {
-                    $sql = "UPDATE $item_view_table SET
-                                total_time = " . $this->get_total_time() . ",
-                                start_time = " . $this->get_current_start_time() . ",
-                                score = " . $this->get_score() . ",
-                                status = '" . $this->get_status(false) . "',
-                                max_score = '" . $this->get_max() . "',
-                                suspend_data = '" . Database::escape_string($this->current_data) . "',
-                                lesson_location = '" . $this->lesson_location . "'
-                            WHERE
-                                c_id = $course_id AND
-                                lp_item_id = " . $this->db_id . " AND
-                                lp_view_id = " . $this->view_id . " AND
-                                view_count = " . $this->get_attempt_id();
+                    $params = array(
+                        'total_time' => $this->get_total_time(),
+                        'start_time' => $this->get_current_start_time(),
+                        'score' =>  $this->get_score(),
+                        'status' => $this->get_status(false),
+                        'max_score' => $this->get_max(),
+                        'suspend_data' => $this->current_data,
+                        'lesson_location' => $this->lesson_location
+                    );
+                    $where = array(
+                        'c_id = ? AND lp_item_id = ? AND lp_view_id = ? AND view_count = ?' =>
+                        array($course_id, $this->db_id, $this->view_id, $this->get_attempt_id())
+                    );
+                    Database::update($item_view_table, $params, $where);
                 } else {
                     // For all other content types...
                     if ($this->type == 'quiz') {
@@ -4121,46 +4083,61 @@ class learnpathItem
                         $iva_table = Database::get_course_table(
                             TABLE_LP_IV_INTERACTION
                         );
-                        $iva_sql = "SELECT id FROM $iva_table " .
-                            "WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id " .
-                            //  "AND order_id = $index";
-                            //also check for the interaction ID as it must be unique for this SCO view
-                            "AND (order_id = $index " .
-                            "OR interaction_id = '" . Database::escape_string($interaction[0]) . "')";
+
+                        //also check for the interaction ID as it must be unique for this SCO view
+                        $iva_sql = "SELECT id FROM $iva_table
+                                    WHERE
+                                        c_id = $course_id AND
+                                        lp_iv_id = $lp_iv_id AND
+                                        (
+                                            order_id = $index OR
+                                            interaction_id = '" . Database::escape_string($interaction[0]) . "'
+                                        )
+                                    ";
                         $iva_res = Database::query($iva_sql);
                         // id(0), type(1), time(2), weighting(3), correct_responses(4), student_response(5), result(6), latency(7)
                         if (Database::num_rows($iva_res) > 0) {
                             // Update (or don't).
                             $iva_row = Database::fetch_array($iva_res);
                             $iva_id = $iva_row[0];
-                            $ivau_sql = "UPDATE $iva_table " .
-                                "SET interaction_id = '" . Database::escape_string($interaction[0]) . "'," .
-                                "interaction_type = '" . Database::escape_string($interaction[1]) . "'," .
-                                "weighting = '" . Database::escape_string($interaction[3]) . "'," .
-                                "completion_time = '" . Database::escape_string($interaction[2]) . "'," .
-                                "correct_responses = '" . Database::escape_string($correct_resp) . "'," .
-                                "student_response = '" . Database::escape_string($interaction[5]) . "'," .
-                                "result = '" . Database::escape_string($interaction[6]) . "'," .
-                                "latency = '" . Database::escape_string($interaction[7]) . "'" .
-                                "WHERE c_id = $course_id AND id = $iva_id";
-                            Database::query($ivau_sql);
+                            // Insert new one.
+                            $params = array(
+                                'interaction_id' => $interaction[0],
+                                'interaction_type' => $interaction[1],
+                                'weighting' => $interaction[3],
+                                'completion_time' => $interaction[2],
+                                'correct_responses' => $correct_resp,
+                                'student_response' => $interaction[5],
+                                'result' => $interaction[6],
+                                'latency' => $interaction[7]
+                            );
+                            Database::update(
+                                $iva_table,
+                                $params,
+                                array(
+                                    'c_id = ? AND id = ?' => array(
+                                        $course_id,
+                                        $iva_id
+                                    )
+                                )
+                            );
+
                         } else {
                             // Insert new one.
-                            $ivai_sql = "INSERT INTO $iva_table (c_id, order_id, lp_iv_id, interaction_id, interaction_type, " .
-                                "weighting, completion_time, correct_responses, " .
-                                "student_response, result, latency)" .
-                                "VALUES" .
-                                "($course_id, " . $index . "," . $lp_iv_id . ",'" .
-                                Database::escape_string($interaction[0]) . "','" .
-                                Database::escape_string($interaction[1]) . "'," ."'" .
-                                Database::escape_string($interaction[3]) . "','" .
-                                Database::escape_string($interaction[2]) . "','" .
-                                Database::escape_string($correct_resp) . "'," ."'" .
-                                Database::escape_string($interaction[5]) . "','" .
-                                Database::escape_string($interaction[6]) . "','" .
-                                Database::escape_string($interaction[7]) . "'" .
-                                ")";
-                            Database::query($ivai_sql);
+                            $params = array(
+                                'c_id' => $course_id,
+                                'order_id' => $index,
+                                'lp_iv_id' => $lp_iv_id,
+                                'interaction_id' => $interaction[0],
+                                'interaction_type' => $interaction[1],
+                                'weighting' => $interaction[3],
+                                'completion_time' => $interaction[2],
+                                'correct_responses' => $correct_resp,
+                                'student_response' => $interaction[5],
+                                'result' => $interaction[6],
+                                'latency' => $interaction[7]
+                            );
+                            Database::insert($iva_table, $params);
                         }
                     }
                 }
@@ -4169,6 +4146,7 @@ class learnpathItem
         if (self::debug > 2) {
             error_log('End of learnpathItem::write_to_db()', 0);
         }
+
         return true;
     }
 
@@ -4242,12 +4220,13 @@ class learnpathItem
             // Store the mp3 file in the lp_item table.
             $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
             $sql = "UPDATE $tbl_lp_item SET
-                    audio = '" . Database::escape_string($file_path) . "'
+                        audio = '" . Database::escape_string($file_path) . "'
                     WHERE
                         c_id = {$course_info['real_id']} AND
-                        id = '" . Database::escape_string($this->db_id) . "'";
+                        id = '" . intval($this->db_id) . "'";
             Database::query($sql);
         }
+
         return $file_path;
     }
 

+ 1 - 1
main/newscorm/resourcelinker.inc.php

@@ -402,7 +402,7 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
             echo str_repeat("&nbsp;&gt;", $level);
 
             // The title and the text are in the content field and we only want to display the title.
-            list($title, $text) = split('<br>', $myrow['content']);
+            list($title, $text) = explode('<br>', $myrow['content']);
             if ($title == '') { $title = $myrow['content']; }
             $title = $myrow['title'];
             $text = $myrow['content'];

+ 1 - 1
main/newscorm/scorm.class.php

@@ -806,7 +806,7 @@ class scorm extends learnpath
         $result = Database::query($sql);
         $row = Database::fetch_array($result);
         $LPname = $row['path'];
-        $list = split('/', $LPname);
+        $list = explode('/', $LPname);
         $LPnamesafe = $list[0];
         //$zipfoldername = '/tmp';
         //$zipfoldername = '../../courses/'.$_course['directory'].'/temp/'.$LPnamesafe;

+ 95 - 93
main/newscorm/scormItem.class.php

@@ -1,17 +1,17 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+require_once 'learnpathItem.class.php';
+
 /**
+ * Class scormItem
+ * This class handles the <item> elements from an imsmanifest file.
  * Container for the scormItem class that deals with <item> elements in an imsmanifest file
  * @package	chamilo.learnpath.scorm
  * @author	Yannick Warnier	<ywarnier@beeznest.org>
  */
-
-/**
- * This class handles the <item> elements from an imsmanifest file.
- */
-require_once 'learnpathItem.class.php';
-class scormItem extends learnpathItem {
+class scormItem extends learnpathItem
+{
     public $identifier = '';
     public $identifierref = '';
     public $isvisible = '';
@@ -32,117 +32,117 @@ class scormItem extends learnpathItem {
     /**
      * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormItem
      * object from database records or from the DOM element given as parameter
-     * @param	string	Type of construction needed ('db' or 'manifest', default = 'manifest')
-     * @param	mixed	Depending on the type given, DB id for the lp_item or reference to the DOM element
+     * @param	string	$type Type of construction needed ('db' or 'manifest', default = 'manifest')
+     * @param	mixed	$element Depending on the type given, DB id for the lp_item or reference to the DOM element
+     * @param int $course_id
      */
-    public function __construct($type = 'manifest', &$element, $course_id = '') {
+    public function __construct($type = 'manifest', &$element, $course_id = '')
+    {
         if (isset($element)) {
-
             // Parsing using PHP5 DOMXML methods.
-
             switch ($type) {
                 case 'db':
-                    parent::__construct($element,api_get_user_id(), $course_id);
+                    parent::__construct($element, api_get_user_id(), $course_id);
                     $this->scorm_contact = false;
                     // TODO: Implement this way of metadata object creation.
                     return false;
                 case 'manifest': // Do the same as the default.
                 default:
-                     //if ($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function.
-                     $children = $element->childNodes;
+                    //if ($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function.
+                    $children = $element->childNodes;
                     foreach ($children as $child) {
-                         switch ($child->nodeType) {
-                             case XML_ELEMENT_NODE:
+                        switch ($child->nodeType) {
+                            case XML_ELEMENT_NODE:
                                 switch ($child->tagName) {
-                                     case 'title':
-                                         $tmp_children = $child->childNodes;
-                                         if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
-                                             $this->title = $child->firstChild->nodeValue;
-                                         }
-                                         break;
-                                     case 'max_score':
-                                         if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
-                                             $this->max_score = $child->firstChild->nodeValue;
-                                         }
-                                         break;
-                                     case 'maxtimeallowed':
-                                     case 'adlcp:maxtimeallowed':
-                                         $tmp_children = $child->childNodes;
-                                         if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
-                                             $this->max_time_allowed = $child->firstChild->nodeValue;
-                                         }
-                                         break;
+                                    case 'title':
+                                        $tmp_children = $child->childNodes;
+                                        if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
+                                            $this->title = $child->firstChild->nodeValue;
+                                        }
+                                        break;
+                                    case 'max_score':
+                                        if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
+                                            $this->max_score = $child->firstChild->nodeValue;
+                                        }
+                                        break;
+                                    case 'maxtimeallowed':
+                                    case 'adlcp:maxtimeallowed':
+                                        $tmp_children = $child->childNodes;
+                                        if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
+                                            $this->max_time_allowed = $child->firstChild->nodeValue;
+                                        }
+                                        break;
                                     case 'prerequisites':
                                     case 'adlcp:prerequisites':
-                                         $tmp_children = $child->childNodes;
-                                         if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
-                                             $this->prereq_string = $child->firstChild->nodeValue;
-                                         }
-                                         break;
+                                        $tmp_children = $child->childNodes;
+                                        if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
+                                            $this->prereq_string = $child->firstChild->nodeValue;
+                                        }
+                                        break;
                                     case 'timelimitaction':
                                     case 'adlcp:timelimitaction':
-                                         $tmp_children = $child->childNodes;
-                                         if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
-                                             $this->timelimitaction = $child->firstChild->nodeValue;
-                                         }
-                                         break;
+                                        $tmp_children = $child->childNodes;
+                                        if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
+                                            $this->timelimitaction = $child->firstChild->nodeValue;
+                                        }
+                                        break;
                                     case 'datafromlms':
                                     case 'adlcp:datafromlms':
                                     case 'adlcp:launchdata': //in some cases (Wouters)
-                                         $tmp_children = $child->childNodes;
-                                         if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
-                                             $this->datafromlms = $child->firstChild->nodeValue;
-                                         }
-                                         break;
+                                        $tmp_children = $child->childNodes;
+                                        if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
+                                            $this->datafromlms = $child->firstChild->nodeValue;
+                                        }
+                                        break;
                                     case 'masteryscore':
                                     case 'adlcp:masteryscore':
-                                         $tmp_children = $child->childNodes;
-                                         if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
-                                             $this->mastery_score = $child->firstChild->nodeValue;
-                                         }
-                                         break;
-                                     case 'item':
-                                         $oItem = new scormItem('manifest',$child);
-                                         if ($oItem->identifier != '') {
-                                             $this->sub_items[$oItem->identifier] = $oItem;
-                                         }
+                                        $tmp_children = $child->childNodes;
+                                        if ($tmp_children->length == 1 && $child->firstChild->nodeValue != '') {
+                                            $this->mastery_score = $child->firstChild->nodeValue;
+                                        }
+                                        break;
+                                    case 'item':
+                                        $oItem = new scormItem('manifest',$child);
+                                        if ($oItem->identifier != '') {
+                                            $this->sub_items[$oItem->identifier] = $oItem;
+                                        }
                                         break;
-                                     case 'metadata':
-                                         $this->metadata = new scormMetadata('manifest', $child);
-                                         break;
-                                 }
-                                 break;
-                             case XML_TEXT_NODE:
-                                 // This case is actually treated by looking into ELEMENT_NODEs above.
-                                 break;
-                         }
-                     }
-                     if ($element->hasAttributes()) {
-                         $attributes = $element->attributes;
-                         //$keep_href = '';
-                         foreach ($attributes as $attrib) {
-                             switch($attrib->name){
-                                 case 'identifier':
-                                     $this->identifier = $attrib->value;
-                                     break;
-                                 case 'identifierref':
-                                     $this->identifierref = $attrib->value;
-                                     break;
-                                 case 'isvisible':
-                                     $this->isvisible = $attrib->value;
-                                     break;
-                                 case 'parameters':
-                                     $this->parameters = $attrib->value;
-                                     break;
-                             }
-                         }
-                     }
+                                    case 'metadata':
+                                        $this->metadata = new scormMetadata('manifest', $child);
+                                        break;
+                                }
+                                break;
+                            case XML_TEXT_NODE:
+                                // This case is actually treated by looking into ELEMENT_NODEs above.
+                                break;
+                        }
+                    }
+                    if ($element->hasAttributes()) {
+                        $attributes = $element->attributes;
+                        //$keep_href = '';
+                        foreach ($attributes as $attrib) {
+                            switch($attrib->name){
+                                case 'identifier':
+                                    $this->identifier = $attrib->value;
+                                    break;
+                                case 'identifierref':
+                                    $this->identifierref = $attrib->value;
+                                    break;
+                                case 'isvisible':
+                                    $this->isvisible = $attrib->value;
+                                    break;
+                                case 'parameters':
+                                    $this->parameters = $attrib->value;
+                                    break;
+                            }
+                        }
+                    }
+
                     return true;
             }
-
             // End parsing using PHP5 DOMXML methods.
-
         }
+
         return false;
     }
 
@@ -153,7 +153,8 @@ class scormItem extends learnpathItem {
      * @param	integer	Optional relative order of the item at this level
      * @param	integer	Optional level. If not given, assumes it's level 0
      */
-    public function get_flat_list(&$list, &$abs_order, $rel_order = 1, $level = 0) {
+    public function get_flat_list(&$list, &$abs_order, $rel_order = 1, $level = 0)
+    {
         $list[] = array(
             'abs_order' => $abs_order,
             'datafromlms' => $this->datafromlms,
@@ -184,7 +185,8 @@ class scormItem extends learnpathItem {
      * Save function. Uses the parent save function and adds a layer for SCORM.
      * @param	boolean	Save from URL params (1) or from object attributes (0)
      */
-    public function save($from_outside = true, $prereqs_complete = false) {
+    public function save($from_outside = true, $prereqs_complete = false)
+    {
         parent::save($from_outside, $prereqs_complete);
         // Under certain conditions, the scorm_contact should not be set, because no scorm signal was sent.
         $this->scorm_contact = true;

+ 299 - 298
main/template/default/auth/courses_categories.php

@@ -2,10 +2,10 @@
 /* For licensing terms, see /license.txt */
 
 /**
-* View (MVC patter) for courses categories
-* @author Christian Fasanando <christian1827@gmail.com> - Beeznest
-* @package chamilo.auth
-*/
+ * View (MVC patter) for courses categories
+ * @author Christian Fasanando <christian1827@gmail.com> - Beeznest
+ * @package chamilo.auth
+ */
 
 if (isset($_REQUEST['action']) && Security::remove_XSS($_REQUEST['action']) !== 'subscribe') {
     $stok = Security::get_token();
@@ -25,6 +25,7 @@ $pageTotal = intval(ceil(intval($countCoursesInCategory) / $pageLength));
 $cataloguePagination = $pageTotal > 1 ?
     getCataloguePagination($pageCurrent, $pageLength, $pageTotal) :
     '';
+$search_term = isset($search_term) ? $search_term :null;
 
 if ($showSessions && isset($_POST['date'])) {
     $date = $_POST['date'];
@@ -36,343 +37,343 @@ $userInfo = api_get_user_info();
 $code = isset($code) ? $code : null;
 
 ?>
-<script>
-    $(document).ready( function() {
-        $('.star-rating li a').live('click', function(event) {
-        var id = $(this).parents('ul').attr('id');
-        $('#vote_label2_' + id).html("<?php echo get_lang('Loading'); ?>");
-            $.ajax({
-                url: $(this).attr('data-link'),
-                success: function(data) {
-                    $("#rating_wrapper_"+id).html(data);
-                    if(data == 'added') {
-                        //$('#vote_label2_' + id).html("{'Saved'|get_lang}");
-                    }
-                    if(data == 'updated') {
-                        //$('#vote_label2_' + id).html("{'Saved'|get_lang}");
+    <script>
+        $(document).ready( function() {
+            $('.star-rating li a').live('click', function(event) {
+                var id = $(this).parents('ul').attr('id');
+                $('#vote_label2_' + id).html("<?php echo get_lang('Loading'); ?>");
+                $.ajax({
+                    url: $(this).attr('data-link'),
+                    success: function(data) {
+                        $("#rating_wrapper_"+id).html(data);
+                        if(data == 'added') {
+                            //$('#vote_label2_' + id).html("{'Saved'|get_lang}");
+                        }
+                        if(data == 'updated') {
+                            //$('#vote_label2_' + id).html("{'Saved'|get_lang}");
+                        }
                     }
-                }
+                });
             });
-        });
 
-        $('.courses-list-btn').toggle(function (e) {
-            e.preventDefault();
-
-            var $el = $(this);
-            var sessionId = getSessionId(this);
-
-            $el.children('img').remove();
-            $el.prepend('<?php echo Display::display_icon('nolines_minus.gif'); ?>');
-
-            $.ajax({
-                url: '<?php echo api_get_path(WEB_AJAX_PATH) . 'course.ajax.php' ?>',
-                type: 'GET',
-                dataType: 'json',
-                data: {
-                    a: 'display_sessions_courses',
-                    session: sessionId
-                },
-                success: function (response){
-                    var $container = $el.prev('.course-list');
-                    var $courseList = $('<ul>');
-                    $.each(response, function (index, course) {
-                        $courseList.append('<li><div><strong>' + course.name + '</strong><br>' + course.coachName + '</div></li>');
-                    });
-
-                    $container.append($courseList).show(250);
-                }
+            $('.courses-list-btn').toggle(function (e) {
+                e.preventDefault();
+
+                var $el = $(this);
+                var sessionId = getSessionId(this);
+
+                $el.children('img').remove();
+                $el.prepend('<?php echo Display::display_icon('nolines_minus.gif'); ?>');
+
+                $.ajax({
+                    url: '<?php echo api_get_path(WEB_AJAX_PATH) . 'course.ajax.php' ?>',
+                    type: 'GET',
+                    dataType: 'json',
+                    data: {
+                        a: 'display_sessions_courses',
+                        session: sessionId
+                    },
+                    success: function (response){
+                        var $container = $el.prev('.course-list');
+                        var $courseList = $('<ul>');
+                        $.each(response, function (index, course) {
+                            $courseList.append('<li><div><strong>' + course.name + '</strong><br>' + course.coachName + '</div></li>');
+                        });
+
+                        $container.append($courseList).show(250);
+                    }
+                });
+            }, function (e) {
+                e.preventDefault();
+                var $el = $(this);
+                var $container = $el.prev('.course-list');
+                $container.hide(250).empty();
+                $el.children('img').remove();
+                $el.prepend('<?php echo Display::display_icon('nolines_plus.gif'); ?>');
             });
-        }, function (e) {
-            e.preventDefault();
-            var $el = $(this);
-            var $container = $el.prev('.course-list');
-            $container.hide(250).empty();
-            $el.children('img').remove();
-            $el.prepend('<?php echo Display::display_icon('nolines_plus.gif'); ?>');
-        });
 
-        var getSessionId = function (el) {
-            var parts = el.id.split('_');
-            return parseInt(parts[1], 10);
-        };
+            var getSessionId = function (el) {
+                var parts = el.id.split('_');
+                return parseInt(parts[1], 10);
+            };
 
-        <?php if ($showSessions) { ?>
-        $('#date').datepicker({
-            dateFormat: 'yy-mm-dd'
+            <?php if ($showSessions) { ?>
+            $('#date').datepicker({
+                dateFormat: 'yy-mm-dd'
+            });
+            <?php } ?>
         });
-        <?php } ?>
-    });
-</script>
-
-<div class="row">
-    <div class="span3">
-        <div id="course_category_well" class="well">
-            <ul class="nav nav-list">
-                <?php if ($showCourses) { ?>
-                <?php if (!isset($_GET['hidden_links']) || intval($_GET['hidden_links']) != 1) { ?>
-                <form class="form-search" method="post" action="<?php echo getCourseCategoryUrl(1, $pageLength, 'ALL', 0, 'subscribe'); ?>">
-                    <fieldset>
-                        <input type="hidden" name="sec_token" value="<?php echo $stok; ?>">
-                        <input type="hidden" name="search_course" value="1" />
-                        <div class="control-group">
-                            <div class="controls">
-                                <div class="input-append">
-                                    <input class="span2" type="text" name="search_term" value="<?php echo (empty($_POST['search_term']) ? '' : api_htmlentities(Security::remove_XSS($_POST['search_term']))); ?>" />
-                                    <button class="btn" type="submit"><?php echo get_lang('Search'); ?></button>
+    </script>
+
+    <div class="row">
+        <div class="span3">
+            <div id="course_category_well" class="well">
+                <ul class="nav nav-list">
+                    <?php if ($showCourses) { ?>
+                    <?php if (!isset($_GET['hidden_links']) || intval($_GET['hidden_links']) != 1) { ?>
+                        <form class="form-search" method="post" action="<?php echo getCourseCategoryUrl(1, $pageLength, 'ALL', 0, 'subscribe'); ?>">
+                            <fieldset>
+                                <input type="hidden" name="sec_token" value="<?php echo $stok; ?>">
+                                <input type="hidden" name="search_course" value="1" />
+                                <div class="control-group">
+                                    <div class="controls">
+                                        <div class="input-append">
+                                            <input class="span2" type="text" name="search_term" value="<?php echo (empty($_POST['search_term']) ? '' : api_htmlentities(Security::remove_XSS($_POST['search_term']))); ?>" />
+                                            <button class="btn" type="submit"><?php echo get_lang('Search'); ?></button>
+                                        </div>
+                                    </div>
                                 </div>
-                            </div>
-                        </div>
-                    </fieldset>
-                </form>
-            <?php
-                $hidden_links = 0;
-            } else {
-                $hidden_links = 1;
-            }
-
-            /* Categories will only show down to 4 levels, if you want more,
-             * you will have to patch the following code. We don't recommend
-             * it, as this can considerably slow down your system
-             */
-            if (!empty($browse_course_categories)) {
-                echo '<a class="btn" href="'.api_get_self().'?action=display_random_courses">'.get_lang('RandomPick').'</a><br /><br />';
-            ?>
-            </ul>
-        </div>
-        <div class="well">
-            <ul class="nav nav-list">
-            <?php
-                echo '<li class="nav-header">'.get_lang('CourseCategories').'</li>';
-
-                $action = 'display_courses';
-                // level 1
-                foreach ($browse_course_categories[0] as $category) {
-                    $category_name = $category['name'];
-                    $category_code = $category['code'];
-                    $count_courses_lv1 = $category['count_courses'];
-
-                    if ($code == $category_code) {
-                        $category_link = '<strong>'.$category_name.' ('.$count_courses_lv1.')</strong>';
+                            </fieldset>
+                        </form>
+                        <?php
+                        $hidden_links = 0;
                     } else {
-                        if (!empty($count_courses_lv1)) {
-                            $category_link = '<a href="' .
-                                getCourseCategoryUrl(
-                                    1,
-                                    $pageLength,
-                                    $category_code,
-                                    $hidden_links,
-                                    $action
-                                ) .'">'.$category_name.' ('.$count_courses_lv1.') </a>';
-                        } else {
-                            $category_link = ''.$category_name.' ('.$count_courses_lv1.')';
-                        }
+                        $hidden_links = 1;
                     }
-                    echo '<li>'.$category_link.'</li>';
-
-                    // level 2
-                    if (!empty($browse_course_categories[$category_code])) {
-                        foreach ($browse_course_categories[$category_code] as $subcategory1) {
-                            $subcategory1_name = $subcategory1['name'];
-                            $subcategory1_code = $subcategory1['code'];
-                            $count_courses_lv2 = $subcategory1['count_courses'];
-                            if ($code == $subcategory1_code) {
-                                $subcategory1_link = '<strong>'.$subcategory1_name.' ('.$count_courses_lv2.')</strong>';
-                            } else {
-                                $subcategory1_link = '<a href="' .
+
+                    /* Categories will only show down to 4 levels, if you want more,
+                     * you will have to patch the following code. We don't recommend
+                     * it, as this can considerably slow down your system
+                     */
+                    if (!empty($browse_course_categories)) {
+                    echo '<a class="btn" href="'.api_get_self().'?action=display_random_courses">'.get_lang('RandomPick').'</a><br /><br />';
+                    ?>
+                </ul>
+            </div>
+            <div class="well">
+                <ul class="nav nav-list">
+                    <?php
+                    echo '<li class="nav-header">'.get_lang('CourseCategories').'</li>';
+
+                    $action = 'display_courses';
+                    // level 1
+                    foreach ($browse_course_categories[0] as $category) {
+                        $category_name = $category['name'];
+                        $category_code = $category['code'];
+                        $count_courses_lv1 = $category['count_courses'];
+
+                        if ($code == $category_code) {
+                            $category_link = '<strong>'.$category_name.' ('.$count_courses_lv1.')</strong>';
+                        } else {
+                            if (!empty($count_courses_lv1)) {
+                                $category_link = '<a href="' .
                                     getCourseCategoryUrl(
                                         1,
                                         $pageLength,
-                                        $subcategory1_code,
+                                        $category_code,
                                         $hidden_links,
                                         $action
-                                    ) . '">'.$subcategory1_name.' ('.$count_courses_lv2.') </a> ';
+                                    ) .'">'.$category_name.' ('.$count_courses_lv1.') </a>';
+                            } else {
+                                $category_link = ''.$category_name.' ('.$count_courses_lv1.')';
                             }
-                            echo '<li style="margin-left:20px;">'.$subcategory1_link.'</li>';
-
-                            // level 3
-                            if (!empty($browse_course_categories[$subcategory1_code])) {
-                                foreach ($browse_course_categories[$subcategory1_code] as $subcategory2) {
-                                    $subcategory2_name = $subcategory2['name'];
-                                    $subcategory2_code = $subcategory2['code'];
-                                    $count_courses_lv3 = $subcategory2['count_courses'];
-                                    if ($code == $subcategory2_code) {
-                                        $subcategory2_link = '<strong>'.$subcategory2_name.' ('.$count_courses_lv3.')</strong>';
-                                    } else {
-                                        $subcategory2_link = '<a href="' .
-                                            getCourseCategoryUrl(
-                                                1,
-                                                $pageLength,
-                                                $subcategory2_code,
-                                                $hidden_links,
-                                                $action
-                                            ) . '">'.$subcategory2_name.'</a> ('.$count_courses_lv3.')';
-                                    }
-                                    echo '<li style="margin-left:40px;">'.$subcategory2_link.'</li>';
-
-                                    // level 4
-                                    if (!empty($browse_course_categories[$subcategory2_code])) {
-                                        foreach ($browse_course_categories[$subcategory2_code] as $subcategory3) {
-                                            $subcategory3_name = $subcategory3['name'];
-                                            $subcategory3_code = $subcategory3['code'];
-                                            $count_courses_lv4 = $subcategory3['count_courses'];
-                                            if ($code == $subcategory3_code) {
-                                                $subcategory3_link = '<strong>'.$subcategory3_name.' ('.$count_courses_lv4.')</strong>';
-                                            } else {
-                                                $subcategory3_link = '<a href="' .
-                                                    getCourseCategoryUrl(
-                                                        1,
-                                                        $pageLength,
-                                                        $subcategory3_code,
-                                                        $hidden_links,
-                                                        $action
-                                                    ) . '">'.$subcategory3_name.' ('.$count_courses_lv4.') </a>';
+                        }
+                        echo '<li>'.$category_link.'</li>';
+
+                        // level 2
+                        if (!empty($browse_course_categories[$category_code])) {
+                            foreach ($browse_course_categories[$category_code] as $subcategory1) {
+                                $subcategory1_name = $subcategory1['name'];
+                                $subcategory1_code = $subcategory1['code'];
+                                $count_courses_lv2 = $subcategory1['count_courses'];
+                                if ($code == $subcategory1_code) {
+                                    $subcategory1_link = '<strong>'.$subcategory1_name.' ('.$count_courses_lv2.')</strong>';
+                                } else {
+                                    $subcategory1_link = '<a href="' .
+                                        getCourseCategoryUrl(
+                                            1,
+                                            $pageLength,
+                                            $subcategory1_code,
+                                            $hidden_links,
+                                            $action
+                                        ) . '">'.$subcategory1_name.' ('.$count_courses_lv2.') </a> ';
+                                }
+                                echo '<li style="margin-left:20px;">'.$subcategory1_link.'</li>';
+
+                                // level 3
+                                if (!empty($browse_course_categories[$subcategory1_code])) {
+                                    foreach ($browse_course_categories[$subcategory1_code] as $subcategory2) {
+                                        $subcategory2_name = $subcategory2['name'];
+                                        $subcategory2_code = $subcategory2['code'];
+                                        $count_courses_lv3 = $subcategory2['count_courses'];
+                                        if ($code == $subcategory2_code) {
+                                            $subcategory2_link = '<strong>'.$subcategory2_name.' ('.$count_courses_lv3.')</strong>';
+                                        } else {
+                                            $subcategory2_link = '<a href="' .
+                                                getCourseCategoryUrl(
+                                                    1,
+                                                    $pageLength,
+                                                    $subcategory2_code,
+                                                    $hidden_links,
+                                                    $action
+                                                ) . '">'.$subcategory2_name.'</a> ('.$count_courses_lv3.')';
+                                        }
+                                        echo '<li style="margin-left:40px;">'.$subcategory2_link.'</li>';
+
+                                        // level 4
+                                        if (!empty($browse_course_categories[$subcategory2_code])) {
+                                            foreach ($browse_course_categories[$subcategory2_code] as $subcategory3) {
+                                                $subcategory3_name = $subcategory3['name'];
+                                                $subcategory3_code = $subcategory3['code'];
+                                                $count_courses_lv4 = $subcategory3['count_courses'];
+                                                if ($code == $subcategory3_code) {
+                                                    $subcategory3_link = '<strong>'.$subcategory3_name.' ('.$count_courses_lv4.')</strong>';
+                                                } else {
+                                                    $subcategory3_link = '<a href="' .
+                                                        getCourseCategoryUrl(
+                                                            1,
+                                                            $pageLength,
+                                                            $subcategory3_code,
+                                                            $hidden_links,
+                                                            $action
+                                                        ) . '">'.$subcategory3_name.' ('.$count_courses_lv4.') </a>';
+                                                }
+                                                echo '<li style="margin-left:60px;">'.$subcategory3_link.'</li>';
                                             }
-                                            echo '<li style="margin-left:60px;">'.$subcategory3_link.'</li>';
                                         }
                                     }
                                 }
                             }
                         }
-                    }
-                } ?>
-            </ul>
-        </div>
+                    } ?>
+                </ul>
+            </div>
             <?php
             }
-        }
+            }
             ?>
-        <?php if ($showSessions) { ?>
-        <div class="well">
-            <ul class="nav nav-list">
-                    <li class="nav-header"><?php echo get_lang('Sessions'); ?></li>
-                    <li>
-                        <?php if ($action == 'display_sessions' && $_SERVER['REQUEST_METHOD'] != 'POST') { ?>
-                            <strong><?php echo get_lang('Sessions'); ?></strong>
-                        <?php } else { ?>
-                            <a href="<?php echo getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions'); ?>"><?php echo get_lang('SessionList'); ?></a>
-                        <?php } ?>
-                    </li>
-                    <li class="nav-header"><?php echo get_lang('SearchActiveSessions') ?></li>
-                    <form class="form-search" method="post" action="<?php echo getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions'); ?>">
-                        <div class="input-append">
-                            <?php echo Display::input('date', 'date', $date, array(
-                                'class' => 'span2',
-                                'id' => 'date',
-                                'readonly' => ''
-                            )); ?>
-                            <button class="btn" type="submit"><?php echo get_lang('Search'); ?></button>
-                        </div>
-                    </form>
-            </ul>
+            <?php if ($showSessions) { ?>
+                <div class="well">
+                    <ul class="nav nav-list">
+                        <li class="nav-header"><?php echo get_lang('Sessions'); ?></li>
+                        <li>
+                            <?php if ($action == 'display_sessions' && $_SERVER['REQUEST_METHOD'] != 'POST') { ?>
+                                <strong><?php echo get_lang('Sessions'); ?></strong>
+                            <?php } else { ?>
+                                <a href="<?php echo getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions'); ?>"><?php echo get_lang('SessionList'); ?></a>
+                            <?php } ?>
+                        </li>
+                        <li class="nav-header"><?php echo get_lang('SearchActiveSessions') ?></li>
+                        <form class="form-search" method="post" action="<?php echo getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions'); ?>">
+                            <div class="input-append">
+                                <?php echo Display::input('date', 'date', $date, array(
+                                    'class' => 'span2',
+                                    'id' => 'date',
+                                    'readonly' => ''
+                                )); ?>
+                                <button class="btn" type="submit"><?php echo get_lang('Search'); ?></button>
+                            </div>
+                        </form>
+                    </ul>
+                </div>
+            <?php } ?>
         </div>
-        <?php } ?>
-    </div>
 
-    <div class="span9">
-        <div class="page-header">
-            <h2><?php echo get_lang('CourseCatalog')?></h2>
-        </div>
-        <?php if ($showCourses && $action != 'display_sessions') { ?>
-        <?php if (!empty($message)) { Display::display_confirmation_message($message, false); }
-        if (!empty($error)) { Display::display_error_message($error, false); }
+        <div class="span9">
+            <div class="page-header">
+                <h2><?php echo get_lang('CourseCatalog')?></h2>
+            </div>
+            <?php if ($showCourses && $action != 'display_sessions') { ?>
+                <?php if (!empty($message)) { Display::display_confirmation_message($message, false); }
+                if (!empty($error)) { Display::display_error_message($error, false); }
 
-        if (!empty($content)) { echo $content; }
+                if (!empty($content)) { echo $content; }
 
-        if (!empty($search_term)) {
-            echo "<p><strong>".get_lang('SearchResultsFor')." ".Security::remove_XSS($_POST['search_term'])."</strong><br />";
-        }
+                if (!empty($search_term)) {
+                    echo "<p><strong>".get_lang('SearchResultsFor')." ".Security::remove_XSS($_POST['search_term'])."</strong><br />";
+                }
 
-        $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
-        $user_id = api_get_user_id();
+                $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
+                $user_id = api_get_user_id();
 
-        if (!empty($browse_courses_in_category)) {
+                if (!empty($browse_courses_in_category)) {
 
-            foreach ($browse_courses_in_category as $course) {
+                    foreach ($browse_courses_in_category as $course) {
 
-                $course_hidden = ($course['visibility'] == COURSE_VISIBILITY_HIDDEN);
+                        $course_hidden = ($course['visibility'] == COURSE_VISIBILITY_HIDDEN);
 
-                if ($course_hidden) {
-                    continue;
-                }
-
-                $user_registerd_in_course = CourseManager::is_user_subscribed_in_course($user_id, $course['code']);
-                $user_registerd_in_course_as_teacher = CourseManager::is_course_teacher($user_id, $course['code']);
-                $user_registerd_in_course_as_student = ($user_registerd_in_course && !$user_registerd_in_course_as_teacher);
-                $course_public = ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD);
-                $course_open = ($course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM);
-                $course_private = ($course['visibility'] == COURSE_VISIBILITY_REGISTERED);
-                $course_closed = ($course['visibility'] == COURSE_VISIBILITY_CLOSED);
-                $course_subscribe_allowed = ($course['subscribe'] == 1);
-                $course_unsubscribe_allowed = ($course['unsubscribe'] == 1);
-                $count_connections = $course['count_connections'];
-                $creation_date = substr($course['creation_date'],0,10);
-
-                $icon_title = null;
-
-                // display the course bloc
-                echo '<div class="well_border"><div class="row">';
-
-                // display thumbnail
-                display_thumbnail($course, $icon_title);
-
-                // display course title and button bloc
-                echo '<div class="span4">';
-                display_title($course);
-                // display button line
-                echo '<div class="btn-toolbar">';
-                // if user registered as student
-                if ($user_registerd_in_course_as_student) {
-                    if (!$course_closed) {
-                        display_description_button($course, $icon_title);
-                        display_goto_button($course);
-                        if ($course_unsubscribe_allowed) {
-                            display_unregister_button($course, $stok, $search_term, $code);
+                        if ($course_hidden) {
+                            continue;
                         }
-                        display_already_registered_label('student');
-                    }
-                } elseif ($user_registerd_in_course_as_teacher) {
-                    // if user registered as teacher
-                    display_description_button($course, $icon_title);
-                    display_goto_button($course);
-                    if ($course_unsubscribe_allowed) {
-                        display_unregister_button($course, $stok, $search_term, $code);
-                    }
-                    display_already_registered_label('teacher');
-                } else {
-                    // if user not registered in the course
-                    if (!$course_closed) {
-                        display_description_button($course, $icon_title);
-                        if (!$course_private) {
+
+                        $user_registerd_in_course = CourseManager::is_user_subscribed_in_course($user_id, $course['code']);
+                        $user_registerd_in_course_as_teacher = CourseManager::is_course_teacher($user_id, $course['code']);
+                        $user_registerd_in_course_as_student = ($user_registerd_in_course && !$user_registerd_in_course_as_teacher);
+                        $course_public = ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD);
+                        $course_open = ($course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM);
+                        $course_private = ($course['visibility'] == COURSE_VISIBILITY_REGISTERED);
+                        $course_closed = ($course['visibility'] == COURSE_VISIBILITY_CLOSED);
+                        $course_subscribe_allowed = ($course['subscribe'] == 1);
+                        $course_unsubscribe_allowed = ($course['unsubscribe'] == 1);
+                        $count_connections = $course['count_connections'];
+                        $creation_date = substr($course['creation_date'],0,10);
+
+                        $icon_title = null;
+
+                        // display the course bloc
+                        echo '<div class="well_border"><div class="row">';
+
+                        // display thumbnail
+                        display_thumbnail($course, $icon_title);
+
+                        // display course title and button bloc
+                        echo '<div class="span4">';
+                        display_title($course);
+                        // display button line
+                        echo '<div class="btn-toolbar">';
+                        // if user registered as student
+                        if ($user_registerd_in_course_as_student) {
+                            if (!$course_closed) {
+                                display_description_button($course, $icon_title);
+                                display_goto_button($course);
+                                if ($course_unsubscribe_allowed) {
+                                    display_unregister_button($course, $stok, $search_term, $code);
+                                }
+                                display_already_registered_label('student');
+                            }
+                        } elseif ($user_registerd_in_course_as_teacher) {
+                            // if user registered as teacher
+                            display_description_button($course, $icon_title);
                             display_goto_button($course);
-                            if ($course_subscribe_allowed) {
-                                display_register_button($course, $stok, $code, $search_term);
+                            if ($course_unsubscribe_allowed) {
+                                display_unregister_button($course, $stok, $search_term, $code);
+                            }
+                            display_already_registered_label('teacher');
+                        } else {
+                            // if user not registered in the course
+                            if (!$course_closed) {
+                                display_description_button($course, $icon_title);
+                                if (!$course_private) {
+                                    display_goto_button($course);
+                                    if ($course_subscribe_allowed) {
+                                        display_register_button($course, $stok, $code, $search_term);
+                                    }
+                                }
                             }
                         }
-                    }
-                }
-                echo '</div>'; // btn-toolbar
-                echo '</div>'; // span4
+                        echo '</div>'; // btn-toolbar
+                        echo '</div>'; // span4
 
-                // display counter
-                echo '<div class="span2">';
-                echo '<div class="course-block-popularity"><span>'.get_lang('ConnectionsLastMonth').'</span><div class="course-block-popularity-score">'.$count_connections.'</div></div>';
-                echo '</div>';
+                        // display counter
+                        echo '<div class="span2">';
+                        echo '<div class="course-block-popularity"><span>'.get_lang('ConnectionsLastMonth').'</span><div class="course-block-popularity-score">'.$count_connections.'</div></div>';
+                        echo '</div>';
 
-                // end of course bloc
-                echo '</div></div>'; // well_border row
+                        // end of course bloc
+                        echo '</div></div>'; // well_border row
 
-            }
-        } else {
-            if (!isset($_REQUEST['subscribe_user_with_password']) && !isset($_REQUEST['subscribe_course'])) {
-                Display::display_warning_message(get_lang('ThereAreNoCoursesInThisCategory'));
-            }
-        } ?>
-        <?php } ?>
-        <?php
+                    }
+                } else {
+                    if (!isset($_REQUEST['subscribe_user_with_password']) && !isset($_REQUEST['subscribe_course'])) {
+                        Display::display_warning_message(get_lang('ThereAreNoCoursesInThisCategory'));
+                    }
+                } ?>
+            <?php } ?>
+            <?php
             echo $cataloguePagination;
-        ?>
+            ?>
+        </div>
     </div>
-</div>
 
 <?php
 

+ 13 - 7
main/template/default/export/table_pdf.tpl

@@ -2,7 +2,7 @@
 
 <h2 align="center"> {{ pdf_title }} </h2>
 
-{% if pdf_description  %}
+{% if pdf_description %}
     {{ pdf_description }}
     <br /><br />
 {% endif %}
@@ -19,6 +19,12 @@
         <td>
           <strong>{{ "Session" | get_lang }}:</strong> {{ pdf_session_info.name }}
         </td>
+
+        {% if pdf_session_info.description %}
+            <td>
+                <strong>{{ "Description" | get_lang }}:</strong> {{ pdf_session_info.description }}
+            </td>
+        {% endif %}
     </tr>
     {% endif %}
 
@@ -26,11 +32,11 @@
     <tr>
         <td>
          <strong>{{ "Course" | get_lang }}:</strong>  {{ pdf_course_info.title }} ({{ pdf_course_info.code }})
-         
-         {% if pdf_course_category %}         
+
+         {% if pdf_course_category %}
             <strong>{{ "Category" | get_lang }}:</strong> {{ pdf_course_category }}
          {% endif %}
-         
+
         </td>
     </tr>
     {% endif %}
@@ -38,7 +44,7 @@
         <td>
          <strong>{{ "Date" | get_lang }}:</strong> {{ pdf_date }}
         </td>
-    </tr>    
+    </tr>
 </table>
 
 <br />
@@ -64,8 +70,8 @@
             <td>
                 _____________________________
                 <br />
-                {{ "Date" | get_lang }}        
+                {{ "Date" | get_lang }}
             </td>
         </tr>
     </table>
-{% endif %}
+{% endif %}

+ 1 - 1
main/work/edit.php

@@ -288,7 +288,7 @@ if (!empty($work_id)) {
             echo Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
         } else {
 
-            $comments = getWorkComments($my_folder_data);
+            $comments = getWorkComments($work_item);
 
             $template = $tpl->get_template('work/comments.tpl');
             $tpl->assign('work_comment_enabled', ALLOW_USER_COMMENTS);

+ 154 - 26
main/work/work.lib.php

@@ -213,7 +213,8 @@ function get_work_data_by_path($path, $courseId = null)
 
 /**
  * @param int $id
- *
+ * @param int $courseId
+ * @param int $sessionId
  * @return array
  */
 function get_work_data_by_id($id, $courseId = null, $sessionId = null)
@@ -289,6 +290,7 @@ function get_work_count_by_student($user_id, $work_id)
         $return = Database::fetch_row($result,'ASSOC');
         $return = intval($return[0]);
     }
+
     return $return;
 }
 
@@ -313,7 +315,7 @@ function get_work_assignment_by_id($id, $courseId = null)
     $result = Database::query($sql);
     $return = array();
     if (Database::num_rows($result)) {
-        $return = Database::fetch_array($result,'ASSOC');
+        $return = Database::fetch_array($result, 'ASSOC');
     }
 
     return $return;
@@ -578,9 +580,9 @@ function display_student_publications_list(
     if (isset($_GET['direction'])) {
         $sort_params[] = 'direction='.Security::remove_XSS($_GET['direction']);
     }
-    $sort_params    = implode('&amp;', $sort_params);
-    $my_params      = $sort_params;
-    $origin         = Security::remove_XSS($origin);
+    $sort_params = implode('&amp;', $sort_params);
+    $my_params = $sort_params;
+    $origin = Security::remove_XSS($origin);
 
     $qualification_exists = false;
     if (!empty($my_folder_data['qualification']) && intval($my_folder_data['qualification']) > 0) {
@@ -635,21 +637,24 @@ function display_student_publications_list(
                     qualification,
                     weight,
                     allow_text_assignment
-                FROM ".$iprop_table." prop INNER JOIN ".$work_table." work ON (prop.ref=work.id AND prop.c_id = $course_id)
+                FROM ".$iprop_table." prop
+                INNER JOIN ".$work_table." work
+                ON (prop.ref=work.id AND prop.c_id = $course_id)
                 WHERE active IN (0, 1) AND ";
 
             if (!empty($group_id)) {
-                $sql_select_directory .= " work.post_group_id = '".$group_id."' "; // set to select only messages posted by the user's group
+                // set to select only messages posted by the user's group
+                $sql_select_directory .= " work.post_group_id = '".$group_id."' ";
             } else {
                 $sql_select_directory .= " work.post_group_id = '0' ";
             }
-            $sql_select_directory .= " AND ".
-                "  work.c_id = $course_id AND ".
-                "  work.id  = ".$work_parent->id." AND ".
-                "  work.filetype = 'folder' AND ".
-                "  prop.tool='work' $condition_session";
+            $sql_select_directory .= " AND
+                work.c_id = $course_id AND
+                work.id  = ".$work_parent->id." AND
+                work.filetype = 'folder' AND
+                prop.tool='work' $condition_session";
             $result = Database::query($sql_select_directory);
-            $row    = Database::fetch_array($result, 'ASSOC');
+            $row = Database::fetch_array($result, 'ASSOC');
 
             if (!$row) {
                 // the folder belongs to another session
@@ -657,16 +662,15 @@ function display_student_publications_list(
             }
 
             // form edit directory
+            $homework = array();
             if (!empty($row['has_properties'])) {
                 $sql = Database::query('SELECT * FROM '.$work_assigment.'
                 WHERE c_id = '.$course_id.' AND id = "'.$row['has_properties'].'" LIMIT 1');
                 $homework = Database::fetch_array($sql);
             }
             // save original value for later
-            $utc_expiry_time = $homework['expires_on'];
-
+            $utc_expiry_time = isset($homework['expires_on']) ? $homework['expires_on'] : null;
             $work_data = get_work_data_by_id($work_parent->id);
-
             $workId = $row['id'];
 
             $action = '';
@@ -820,7 +824,16 @@ function display_student_publications_list(
         $my_params = array ('edit_dir' => intval($_GET['edit_dir']));
     }
     $my_params['origin'] = $origin;
-    Display::display_sortable_config_table('work', $table_header, $table_data, $sorting_options, $paging_options, $my_params, $column_show, $column_order);
+    Display::display_sortable_config_table(
+        'work',
+        $table_header,
+        $table_data,
+        $sorting_options,
+        $paging_options,
+        $my_params,
+        $column_show,
+        $column_order
+    );
 }
 
 /**
@@ -1111,8 +1124,7 @@ function create_unexisting_work_directory($base_work_dir, $desired_dir_name)
 
 /**
  * Delete a work-tool directory
- * @param   string  Base "work" directory for this course as /var/www/chamilo/courses/ABCD/work/
- * @param   string  The directory name as the bit after "work/", without trailing slash
+ * @param   int  $id work id to delete
  * @return  integer -1 on error
  */
 function deleteDirWork($id)
@@ -1197,7 +1209,7 @@ function deleteDirWork($id)
 
 /**
  * Get the path of a document in the student_publication table (path relative to the course directory)
- * @param   integer Element ID
+ * @param   integer $id
  * @return  string  Path (or -1 on error)
  */
 function get_work_path($id)
@@ -1216,8 +1228,9 @@ function get_work_path($id)
 
 /**
  * Update the url of a work in the student_publication table
- * @param   integer ID of the work to update
- * @param   string  Destination directory where the work has been moved (must end with a '/')
+ * @param   integer $id of the work to update
+ * @param   string  $new_path Destination directory where the work has been moved (must end with a '/')
+ * @param int $parent_id
  * @return  -1 on error, sql query result on success
  */
 function updateWorkUrl($id, $new_path, $parent_id)
@@ -2170,7 +2183,7 @@ function get_work_user_list(
     $column,
     $direction,
     $work_id,
-    $where_condition,
+    $where_condition = null,
     $studentId = null,
     $getCount = false
 ) {
@@ -2378,9 +2391,12 @@ function get_work_user_list(
                 }
 
                 $work['qualification'] = $qualification_string.$feedback;
+                $work['qualification_only'] = $qualification_string;
 
                 // Date.
                 $work_date = api_convert_and_format_date($work['sent_date']);
+
+                $work['sent_date_from_db'] = $work['sent_date'];
                 $work['sent_date'] = date_to_str_ago(api_get_local_time($work['sent_date'])) . ' ' . $add_string . '<br />' . $work_date;
 
                 // Actions.
@@ -3183,7 +3199,7 @@ function getWorkDescriptionToolbar()
 
 /**
  * @param array $work
- * @return string
+ * @return array
  */
 function getWorkComments($work)
 {
@@ -3197,8 +3213,14 @@ function getWorkComments($work)
     $courseId = intval($work['c_id']);
     $workId = intval($work['id']);
 
-    $sql = "SELECT c.id, c.user_id, u.firstname, u.lastname, u.username, u.picture_uri
-            FROM $commentTable c INNER JOIN $userTable u ON(u.user_id = c.user_id)
+    if (empty($courseId) || empty($workId)) {
+        return array();
+    }
+
+    $sql = "SELECT
+            c.id, c.user_id, u.firstname, u.lastname, u.username, u.picture_uri
+            FROM $commentTable c
+            INNER JOIN $userTable u ON (u.user_id = c.user_id)
             WHERE c_id = $courseId AND work_id = $workId
             ORDER BY sent_at
             ";
@@ -4953,6 +4975,7 @@ function exportAllWork($userId, $courseInfo, $format = 'pdf')
                     foreach ($work->user_results as $userResult) {
                         //var_dump($userResult);exit;
                         $content .= $userResult['title'];
+                        // No need to use api_get_local_time()
                         $content .= $userResult['sent_date'];
                         $content .= $userResult['qualification'];
                         $content .= $userResult['description'];
@@ -4974,6 +4997,111 @@ function exportAllWork($userId, $courseInfo, $format = 'pdf')
 }
 
 /**
+ * @param int $workId
+ * @param array $courseInfo
+ * @param int $sessionId
+ * @param string $format
+ * @return bool
+ */
+function exportAllStudentWorkFromPublication(
+    $workId,
+    $courseInfo,
+    $sessionId,
+    $format = 'pdf'
+) {
+    if (empty($courseInfo)) {
+        return false;
+    }
+
+    $workData = get_work_data_by_id($workId);
+
+    if (empty($workData)) {
+        return false;
+    }
+
+    $courseCode = $courseInfo['code'];
+    $header = get_lang('Course').': '.$courseInfo['title'];
+    $teachers = CourseManager::get_teacher_list_from_course_code_to_string(
+        $courseCode
+    );
+
+    if (!empty($sessionId)) {
+        $sessionInfo = api_get_session_info($sessionId);
+        if (!empty($sessionInfo)) {
+            $header .= ' - ' . $sessionInfo['name'];
+            $header .= '<br />' . $sessionInfo['description'];
+            $teachers = SessionManager::getCoachesByCourseSessionToString(
+                $sessionId,
+                $courseCode
+            );
+        }
+    }
+
+    $header .= '<br />'.get_lang('Teachers').': '.$teachers.'<br />';
+    $header .= '<br />'.get_lang('Date').': '.api_get_local_time().'<br />';
+    $header .= '<br />'.get_lang('StudentPublication').': '.$workData['title'].'<br />';
+
+    $content = null;
+    if (!empty($workData['expires_on'])) {
+        $content .= '<br /><strong>' . get_lang('ExpiryDate') . '</strong>: ' . api_get_local_time($workData['expires_on']);
+    }
+
+    if (!empty($workData['description'])) {
+        $content .= '<br /><strong>' . get_lang('Description') . '</strong>: ' . $workData['description'];
+    }
+
+    $workList = get_work_user_list(null, null, null, null, $workId);
+
+    switch ($format) {
+        case 'pdf':
+            if (!empty($workList)) {
+                require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
+
+                //$pdf->set_custom_header($header);
+                foreach ($workList as $work) {
+                    $content .= '<hr />';
+                    // getWorkComments need c_id
+                    $work['c_id'] = $courseInfo['real_id'];
+
+                    $content .= '<h3>'.strip_tags($work['title']).'</h3>';
+                    $content .= get_lang('Date').': '.api_get_local_time($work['sent_date_from_db']).'<br />';
+                    if (!empty($work['qualification_only'])) {
+                        $content .= get_lang('Score').': '.$work['qualification_only'] . '<br />';
+                    }
+                    $content .= get_lang('Description').': '.$work['description'].'<br />';
+                    $comments = getWorkComments($work);
+
+                    if (!empty($comments)) {
+                        $content .= '<h4>'.get_lang('Feedback').': </h4>';
+                        foreach ($comments as $comment) {
+                            $content .= get_lang('User').': '.api_get_person_name(
+                                $comment['firstname'],
+                                $comment['lastname']
+                            ).'<br />';
+                            $content .= $comment['comment'];
+                            $content .= '<hr />';
+                        }
+                    }
+                }
+
+                if (!empty($content)) {
+                    $params = array(
+                        'filename' => $workData['title'] . '_' . api_get_local_time(),
+                        'pdf_title' => replace_dangerous_char($workData['title']),
+                        'course_code' => $courseInfo['code'],
+                        'add_signatures' => false
+                    );
+                    $pdf = new PDF('A4', null, $params);
+                    $pdf->html_to_pdf_with_template($content);
+                }
+                exit;
+            }
+            break;
+    }
+}
+
+/**
+ * Downloads all user files per user
  * @param int $userId
  * @param array $courseInfo
  * @return bool

+ 5 - 39
main/work/work_list_all.php

@@ -125,46 +125,12 @@ switch ($action) {
         }
         break;
     case 'export_pdf':
-        $pdf = new PDF();
-
-        $header = get_lang('Course').': '.$courseInfo['title'];
-        $teachers = CourseManager::get_teacher_list_from_course_code_to_string(
-            $courseCode
+        exportAllStudentWorkFromPublication(
+            $workId,
+            $courseInfo,
+            $sessionId,
+            'pdf'
         );
-
-        if (!empty($sessionId)) {
-            $sessionInfo = api_get_session_info($sessionId);
-            $header .= ' - '.$sessionInfo['name'];
-            $header .= '<br />'.$sessionInfo['description'];
-            $teachers = SessionManager::getCoachesByCourseSessionToString(
-                $sessionId,
-                $courseCode
-            );
-        }
-
-        $header .= '<br />'.get_lang('Teachers').': '.$teachers;
-        $header .= '<br />'.get_lang('Date').': '.api_get_local_time();
-
-        if (!empty($my_folder_data['expires_on'])) {
-            $header .= '<br />' . get_lang('ExpiryDate') . ': ' . api_get_local_time($my_folder_data['expires_on']);
-        }
-
-        if (ADD_DOCUMENT_TO_WORK) {
-            $documents = getAllDocumentToWork(
-                $my_folder_data['id'],
-                $courseInfo['real_id']
-            );
-
-            foreach ($documents as $document) {
-                $document['document_id'];
-            }
-            $studentWorks = getAllUserToWork(
-                $my_folder_data['id'],
-                $courseInfo['real_id']
-            );
-        }
-        //$pdf->content_to_pdf($header, null, $my_folder_data['title'], $courseCode);
-        exit;
         break;
 }